使用Pygame做一个乒乓球游戏

项目介绍

使用Pygame做一个乒乓球游戏。左侧为电脑,右侧为玩家。

在这里插入图片描述

视频地址-YT
视频搬运-B站
视频教程约90分钟。
代码地址

环境:需要pygame库,可用pip安装:pip install pygame

1. 基础版本

v1-1

首先进行一些初始化,初始化pygame以及物体的初始状态。
然后是主循环,游戏的主循环主要包含3个内容

  1. 处理事件(这里主要是键盘按键)
  2. 更新物体的状态
  3. 在屏幕上绘制
# 基础 ping pang游戏
import sys
import random
import pygame# 初始化
pygame.init()
clock = pygame.time.Clock()screen_width = 1280
screen_height = 720
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("PingPang")
# 使用长方形表示球和球拍
ball = pygame.Rect(screen_width // 2 - 15, screen_height // 2 - 15, 30, 30)
player = pygame.Rect(screen_width - 20, screen_height // 2 - 70, 10, 140)
opponent = pygame.Rect(10, screen_height // 2 - 70, 10, 140)bg_color = pygame.Color('grey12')
light_grey = (200, 200, 200)ball_speed_x = 7 * random.choice((1, -1))
ball_speed_y = 7 * random.choice((1, -1))    
player_speed = 0
opponent_speed = 7while True:for event in pygame.event.get():if event.type == pygame.QUIT:pygame.quit()sys.exit()if event.type == pygame.KEYDOWN:if event.key == pygame.K_DOWN:player_speed += 7if event.key == pygame.K_UP:player_speed -= 7if event.type == pygame.KEYUP:if event.key == pygame.K_DOWN:player_speed -= 7if event.key == pygame.K_UP:player_speed += 7# update#ball_animation()#player_animation()#opponent_animation()# drawscreen.fill(bg_color)pygame.draw.rect(screen, light_grey, player)pygame.draw.rect(screen, light_grey, opponent)pygame.draw.ellipse(screen, light_grey, ball)pygame.draw.aaline(screen, light_grey, (screen_width / 2, 0), (screen_width / 2, screen_height))pygame.display.flip()clock.tick(60)

v1-2

然后我们实现上面的三个更新逻辑,更新物体状态。

  • ball_animation()
  • player_animation()
  • opponent_animation()
def ball_animation():"""更新球的运动"""global ball_speed_x, ball_speed_yball.x += ball_speed_xball.y += ball_speed_yif ball.top <= 0 or ball.bottom >= screen_height:ball_speed_y *= -1if ball.left <= 0 or ball.right >= screen_width:ball_speed_x *= -1ball_restart()if ball.colliderect(player) or ball.colliderect(opponent):ball_speed_x *= -1def player_animation():"""更新玩家的运动"""player.y += player_speedif player.top <= 0:player.top = 0if player.bottom >= screen_height:player.bottom = screen_heightdef opponent_animation():"""更新对手的运动"""if opponent.top < ball.y:opponent.top += opponent_speedif opponent.bottom > ball.y:opponent.bottom -= opponent_speedif opponent.top <= 0:opponent.top = 0if opponent.bottom >= screen_height:opponent.bottom = screen_heightdef ball_restart():"""重置球的位置"""global ball_speed_x, ball_speed_yball.center = (screen_width // 2, screen_height // 2)ball_speed_y *= random.choice((1, -1))ball_speed_x *= random.choice((1, -1))

实现了这3个函数后,记得在主循环中的# update 处调用这个三个函数。

2. 添加分数和时间

  1. 为游戏添加分数显示:添加字体并渲染出分数。
  2. 发球时有3秒倒计时:通过pygame.time.get_ticks() 获得时间。

在这里插入图片描述

# 添加得分和计时器
import sys
import random
import pygamepygame.init()
clock = pygame.time.Clock()screen_width = 1280
screen_height = 720
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("PingPang")ball = pygame.Rect(screen_width // 2 - 15, screen_height // 2 - 15, 30, 30)
player = pygame.Rect(screen_width - 20, screen_height // 2 - 70, 10, 140)
opponent = pygame.Rect(10, screen_height // 2 - 70, 10, 140)bg_color = pygame.Color('grey12')
light_grey = (200, 200, 200)ball_speed_x = 7 * random.choice((1, -1))
ball_speed_y = 7 * random.choice((1, -1))    
player_speed = 0
opponent_speed = 7# Text Variables
player_score = 0
opponent_score = 0
# 创建字体
game_font = pygame.font.Font("freesansbold.ttf", 32)# Timer
score_time = Truedef ball_animation():global ball_speed_x, ball_speed_yglobal player_score, opponent_scoreglobal score_timeball.x += ball_speed_xball.y += ball_speed_yif ball.top <= 0 or ball.bottom >= screen_height:ball_speed_y *= -1if ball.left <= 0 or ball.right >= screen_width:    if ball.left <= 0:player_score += 1if ball.right >= screen_width:opponent_score += 1score_time = pygame.time.get_ticks()if ball.colliderect(player) or ball.colliderect(opponent):ball_speed_x *= -1def player_animation():player.y += player_speedif player.top <= 0:player.top = 0if player.bottom >= screen_height:player.bottom = screen_heightdef opponent_animation():if opponent.top < ball.y:opponent.top += opponent_speedif opponent.bottom > ball.y:opponent.bottom -= opponent_speedif opponent.top <= 0:opponent.top = 0if opponent.bottom >= screen_height:opponent.bottom = screen_heightdef ball_restart():global ball_speed_x, ball_speed_yglobal score_timeball.center = (screen_width // 2, screen_height // 2)# 计算耗时,并显示剩余时间# 获得当前时间current_time = pygame.time.get_ticks()# 与上次得分时间比较if current_time - score_time < 700:number_three = game_font.render("3", False, light_grey)screen.blit(number_three, (screen_width // 2 - 10, screen_height // 2 + 20))if 700 < current_time - score_time < 1400:number_two = game_font.render("2", False, light_grey)screen.blit(number_two, (screen_width // 2 - 10, screen_height // 2 + 20))if 1400 < current_time - score_time < 2100:number_one = game_font.render("1", False, light_grey)screen.blit(number_one, (screen_width // 2 - 10, screen_height // 2 + 20))if current_time - score_time < 2100:ball_speed_x, ball_speed_y = 0, 0else:ball_speed_y = 7 * random.choice((1, -1))ball_speed_x = 7 * random.choice((1, -1))score_time = Nonewhile True:for event in pygame.event.get():if event.type == pygame.QUIT:pygame.quit()sys.exit()if event.type == pygame.KEYDOWN:if event.key == pygame.K_DOWN:player_speed += 7if event.key == pygame.K_UP:player_speed -= 7if event.type == pygame.KEYUP:if event.key == pygame.K_DOWN:player_speed -= 7if event.key == pygame.K_UP:player_speed += 7ball_animation()player_animation()opponent_animation()# update# drawscreen.fill(bg_color)pygame.draw.rect(screen, light_grey, player)pygame.draw.rect(screen, light_grey, opponent)pygame.draw.ellipse(screen, light_grey, ball)pygame.draw.aaline(screen, light_grey, (screen_width / 2, 0), (screen_width / 2, screen_height))# 显示得分player_text = game_font.render(f"{player_score}", False, light_grey)screen.blit(player_text, (660, 360))opponent_text = game_font.render(f"{opponent_score}", False, light_grey)screen.blit(opponent_text, (600, 360))if score_time:ball_restart()pygame.display.flip()clock.tick(60)

3. 优化碰撞逻辑、添加声音

如果你运行了第2节的程序,你会发现有时候球的反弹有时很奇怪,比如有时候会在球拍上。
本节我们将

  • 优化碰撞逻辑:在ball_animation()通过判断球与球拍的位置,修改球的运动。
  • 添加碰撞和得分音效: pygame.mixer.Sound
# 添加得分和计时器
# 基础 ping pang游戏
import sys
import random
import pygame# setup
pygame.init()
pygame.mixer.pre_init(44100, -16, 2, 512)
clock = pygame.time.Clock()screen_width = 1280
screen_height = 720
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("PingPang")# Reactangles
ball = pygame.Rect(screen_width // 2 - 15, screen_height // 2 - 15, 30, 30)
player = pygame.Rect(screen_width - 20 , screen_height // 2 - 70, 10, 140)
opponent = pygame.Rect(10, screen_height // 2 - 70, 10, 140)bg_color = pygame.Color('grey12')
light_grey = (200, 200, 200)ball_speed_x = 7 * random.choice((1, -1))
ball_speed_y = 7 * random.choice((1, -1))    
player_speed = 0
opponent_speed = 7# Text Variables
player_score = 0
opponent_score = 0
game_font = pygame.font.Font("freesansbold.ttf", 32)# Timer
score_time = True# Sound
pong_sound = pygame.mixer.Sound("pong.ogg")
score_sound = pygame.mixer.Sound("score.ogg")def ball_animation():global ball_speed_x, ball_speed_yglobal player_score, opponent_scoreglobal score_timeball.x += ball_speed_xball.y += ball_speed_yif ball.top <= 0 or ball.bottom >= screen_height:pong_sound.play()ball_speed_y *= -1# score if ball.left <= 0 or ball.right >= screen_width:    score_sound.play()if ball.left <= 0:player_score += 1if ball.right >= screen_width:opponent_score += 1score_time = pygame.time.get_ticks()if ball.colliderect(player) and ball_speed_x > 0: pong_sound.play()if abs(ball.right - player.left) < 10 :ball_speed_x *= -1elif abs(ball.bottom - player.top) < 10 and ball_speed_y > 0:ball_speed_y *= -1elif abs(ball.top - player.bottom) < 10 and ball_speed_y < 0:ball_speed_y *= -1if ball.colliderect(opponent) and ball_speed_x < 0:pong_sound.play()if abs(ball.left - opponent.right) < 10:ball_speed_x *= -1elif abs(ball.bottom - opponent.top) < 10 and ball_speed_y > 0:ball_speed_y *= -1     elif abs(ball.top - opponent.bottom) < 10 and ball_speed_y < 0:ball_speed_y *= -1def player_animation():player.y += player_speedif player.top <= 0:player.top = 0if player.bottom >= screen_height:player.bottom = screen_heightdef opponent_animation():if opponent.top < ball.y:opponent.top += opponent_speedif opponent.bottom > ball.y:opponent.bottom -= opponent_speedif opponent.top <= 0:opponent.top = 0if opponent.bottom >= screen_height:opponent.bottom = screen_heightdef ball_restart():global ball_speed_x, ball_speed_yglobal score_timeball.center = (screen_width // 2, screen_height // 2)current_time = pygame.time.get_ticks()if current_time - score_time < 700:number_three = game_font.render("3", False, light_grey)screen.blit(number_three, (screen_width // 2 - 10, screen_height // 2 + 20))if 700 < current_time - score_time < 1400:number_two = game_font.render("2", False, light_grey)screen.blit(number_two, (screen_width // 2 - 10, screen_height // 2 + 20))if 1400 < current_time - score_time < 2100:number_one = game_font.render("1", False, light_grey)screen.blit(number_one, (screen_width // 2 - 10, screen_height // 2 + 20))if current_time - score_time < 2100:ball_speed_x, ball_speed_y = 0, 0else:ball_speed_y = 7 * random.choice((1, -1))ball_speed_x = 7 * random.choice((1, -1))score_time = Nonewhile True:for event in pygame.event.get():if event.type == pygame.QUIT:pygame.quit()sys.exit()if event.type == pygame.KEYDOWN:if event.key == pygame.K_DOWN:player_speed += 7if event.key == pygame.K_UP:player_speed -= 7if event.type == pygame.KEYUP:if event.key == pygame.K_DOWN:player_speed -= 7if event.key == pygame.K_UP:player_speed += 7ball_animation()player_animation()opponent_animation()# update# drawscreen.fill(bg_color)pygame.draw.rect(screen, light_grey, player)pygame.draw.rect(screen, light_grey, opponent)pygame.draw.ellipse(screen, light_grey, ball)pygame.draw.aaline(screen, light_grey, (screen_width / 2, 0), (screen_width / 2, screen_height))player_text = game_font.render(f"{player_score}", False, light_grey)screen.blit(player_text, (660, 360))opponent_text = game_font.render(f"{opponent_score}", False, light_grey)screen.blit(opponent_text, (600, 360))if score_time:ball_restart()pygame.display.flip()clock.tick(60)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/760392.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

java NIO群聊系统

demo要求&#xff1a; 1&#xff09;编写一个NIO群聊系统&#xff0c;实现服务器端和客户端之间的数据简单通讯&#xff08;非阻塞&#xff09; 2&#xff09;实现多人群聊 3&#xff09;服务器端&#xff1a;可以监测用户上线&#xff0c;离线&#xff0c;并实现消息转发功…

python 爬虫 地理空间DEM 制作中国地形

一.配置Python 爬虫 环境 from selenium import webdriver import time # from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.by import Byfrom selenium.webdriver.common.keys import Keys # from selenium.webdriver.comm…

Langchain-chatchat+ChatGlm3-6b部署

我的环境 升级了下配置&#xff0c;加载知识库成功 内存&#xff1a;16GB 32B 显卡&#xff1a;GTX1060-6G RTX4080 Laptop-12G 1. 基础环境准备 1.1. 安装anaconda&#xff0c;创建环境python版本3.11 conda create -n chatglm3 python3.11 conda activate chatglm3 1.…

如何在CentOS搭建docker compose ui可视化工具并无公网IP远程管理容器

&#x1f49d;&#x1f49d;&#x1f49d;欢迎来到我的博客&#xff0c;很高兴能够在这里和您见面&#xff01;希望您在这里可以感受到一份轻松愉快的氛围&#xff0c;不仅可以获得有趣的内容和知识&#xff0c;也可以畅所欲言、分享您的想法和见解。 推荐:kwan 的首页,持续学…

蓝桥杯 2023 省A 更小的数

主要思路&#xff1a; 输入一个长度为n的字符串&#xff0c;用二维数组dp[i][j]来记录子串[i, j]是否需要反转一次才能满足条件。使用动态规划自底向上地填充dp数组。根据问题的要求&#xff0c;需要考虑字符串的子串中字符的大小关系来判断是否需要反转。最后统计满足条件的子…

静态扭矩,是用公称扭矩还是最小动态扭矩作为对比?——​suntorque智能扭矩系统​

在机械工程和动力学领域&#xff0c;扭矩是一个至关重要的概念。当我们讨论到扭矩时&#xff0c;常常会遇到静态扭矩和动态扭矩的说法。特别是在实际应用中&#xff0c;工程师们经常需要对比和选择使用哪种扭矩作为参考。那么&#xff0c;静态扭矩&#xff0c;是用公称扭矩还是…

【C/C++】详解 assert() 断言(什么是assert? assert有什么作用?)

目录 一、前言 二、什么是 assert ? 三、assert 的用法 四、assert 案例解析 五、assert 断言的使用原则 六、共勉 一、前言 在编写程序过程中&#xff0c;尤其是调试代码时&#xff0c;往往需要一个提醒代码漏洞/Bug的小助手&#xff0c;以便于程序员及时修改和完善代码…

109 项目整合 spring-quartz 启动自动执行定时任务

前言 项目中使用了 quartz 来支持定时任务的相关基础支撑, 但是 最近添加了一个 资源消耗比较高的定时任务, 发布到测试环境之后, 发现服务突然 起不起来了[资源比较有限] 然后 查看了一下日志, 这个定时任务怎么在执行?, 不是 配置的是 凌晨两点么, 然后 仔细一看 几乎配置…

python课后习题一

题目&#xff1a; 1. 2. 解题过程&#xff1a; 1. """计算年数和天数""" minute int(input("请输入分钟数&#xff1a;")) hours minute // 60 days hours // 24 years days // 365 last_days days % 365 print(f"{minut…

【IEDM2023】背势垒电荷运动诱导GaN HEMT随时间的非稳态击穿

分享一篇2023年IEDM上GaN HEMT&#xff08;高电子迁移率晶体管&#xff09;的研究论文&#xff0c;标题为“Charge Movement in Back Barrier Induced Time-Dependent On-State Breakdown of GaN HEMT”。论文讨论了在GaN HEMT中&#xff0c;由于背栅&#xff08;Back Barrier&…

BigDecimal类的使用,用于精确计算任意精度的数字

BigDecimal类 BigDecimal 是 Java 中用于精确表示任意精度的十进制数的类。在很多情况下,使用基本数据类型(如 double 或 float)进行浮点数计算可能会导致精度丢失或舍入错误。BigDecimal 提供了一种更精确的解决方案,可以处理需要高精度计算的场景,比如财务应用或科学计算…

力扣---括号生成---回溯---dfs/二进制

暴力--二进制 采用与&#xff1a;力扣---子集---回溯&#xff08;子集型回溯&#xff09;---递归-CSDN博客 中二进制求解一样的思路&#xff0c;即遍历0~-1&#xff08;从二进制去考虑&#xff09;&#xff0c;如果这个数的第 i 位为0&#xff0c;则括号的第 i 位为‘&#xff…

Excel第27享:基于if函数嵌套的多结果唯一性匹配

1、需求描述 如下图所示&#xff0c;现在有E列、F列、G列三列数据&#xff0c;在D列中填充“最终对应编号”&#xff0c;匹配原则是&#xff1a;E列、F列、G列三列数据中&#xff0c;哪个有数据就填充哪个数据&#xff0c;如果都没有&#xff0c;就显示空值即可。 2、解决思路…

redis 常见的异常

目录 一、缓存穿透 1、概念 解决方案 &#xff08;1&#xff09;布隆过滤器 (2)、缓存空对象 二、缓存雪崩 1、概念 解决方案 &#xff08;1&#xff09;redis高可用 &#xff08;2&#xff09;限流降级 &#xff08;3&#xff09;数据预热 一、缓存穿透 1、概念 缓…

【Greenhills】GHS-MULTI IDE-Ubuntu纯命令系统部署license文件

【更多软件使用问题请点击亿道电子官方网站查询】 1、 文档目标 记录在Ubuntu纯命令系统中部署license文件的步骤。 2、 问题场景 客户服务器为Linux纯命令行的环境&#xff0c;客户也无其他服务器可以部署&#xff0c;需在纯命令行上尝试安装。 3、软硬件环境 1&#xff09…

Windows系统部署eXtplorer文件管理器结合内网穿透构建私人云存储服务器

文章目录 1. 前言2. eXtplorer网站搭建2.1 eXtplorer下载和安装2.2 eXtplorer网页测试2.3 cpolar的安装和注册 3.本地网页发布3.1.Cpolar云端设置3.2.Cpolar本地设置 4.公网访问测试5.结语 1. 前言 通过互联网传输文件&#xff0c;是互联网最重要的应用之一&#xff0c;无论是…

8.测试教程-自动化测试selenium-3

文章目录 1.unittest框架解析2.批量执行脚本2.1构建测试套件2.2用例的执行顺序2.3忽略用例执行 3.unittest断言4.HTML报告生成5.异常捕捉与错误截图6.数据驱动 大家好&#xff0c;我是晓星航。今天为大家带来的是 自动化测试selenium第三节 相关的讲解&#xff01;&#x1f600…

ISIS邻居以及路由计算

ISIS报文细节&#xff0c;ISIS报文分为三个部分&#xff1a; 1、通用报文头 Intradomain Routeing Pro Dis&#xff1a;ISIS&#xff1a;域内路由协议鉴别符&#xff1a;0x83代表ISIS协议 Length Indicator&#xff1a;27 头部长度&#xff08;包含了通用头部和专用头部&…

【原创】三十分钟实时数据可视化网站前后端教程 Scrapy + Django + React 保姆级教程向

这个本来是想做视频的&#xff0c;所以是以讲稿的形式写的。最后没做视频&#xff0c;但是觉得这篇文还是值得记录一下。真的要多记录&#xff0c;不然一些不常用的东西即使做过几个月又有点陌生了。 文章目录 爬虫 SCRAPYxpath 后端 DJANGO前端 REACT Hello大家好这里是小鱼&a…

【spring】@Conditional注解学习

Conditional介绍 Conditional注解用于按照设定的条件进行判断&#xff0c;从而决定是否将某个bean注册到Spring容器中。 Conditional注解是在Spring 4.0版本中引入的&#xff0c;它提供了一种更加灵活的方式来控制bean的创建和注册。在此之前&#xff0c;开发者通常使用Profi…