📅  最后修改于: 2023-12-03 15:34:06.381000             🧑  作者: Mango
这是一个用 Python 编写的简单的接球比赛。该游戏的目标是尽可能多地接住从天空降落的球。你可以用键盘上的向左和向右箭头控制球员来移动球员位置,以便更好地接球。
克隆代码仓库
git clone https://github.com/username/repo.git
cd repo
安装依赖库
pip install pygame
运行游戏
python game.py
游戏循环主体代码片段:
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
# 检测按键,移动球员
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and player.x > 0:
player.move_left()
elif keys[pygame.K_RIGHT] and player.x < SCREEN_WIDTH - player.width:
player.move_right()
# 更新球员和球的位置
player.update()
ball.update()
# 判断球是否落在地面或被接住
if ball.y > GROUND:
ball.reset()
elif ball.collide(player):
ball.reset()
score += 1
# 绘制游戏界面
screen.fill(BLUE)
player.draw(screen)
ball.draw(screen)
draw_text(screen, "Score: " + str(score), 30, SCREEN_WIDTH/2, 10)
pygame.display.update()
clock.tick(60)
球员和球的类定义代码片段:
class Player:
def __init__(self, x, y, width, height, speed):
self.x = x
self.y = y
self.width = width
self.height = height
self.speed = speed
def move_left(self):
self.x -= self.speed
def move_right(self):
self.x += self.speed
def update(self):
pass # 球员的位置是由键盘按键控制的,不需要自动更新
def draw(self, screen):
pygame.draw.rect(screen, RED, (self.x, self.y, self.width, self.height))
class Ball:
def __init__(self, x, y, radius, speed):
self.x = x
self.y = y
self.radius = radius
self.speed = speed
def reset(self):
self.x = random.randint(0, SCREEN_WIDTH)
self.y = random.randint(-100, -self.radius)
def update(self):
self.y += self.speed
def collide(self, player):
dist_x = abs(self.x - player.x - player.width/2)
dist_y = abs(self.y - player.y - player.height/2)
if dist_x > (player.width/2 + self.radius) or dist_y > (player.height/2 + self.radius):
return False
if dist_x <= player.width/2 or dist_y <= player.height/2:
return True
corner_dist_sq = (dist_x - player.width/2)**2 + (dist_y - player.height/2)**2
return corner_dist_sq <= (self.radius**2)
def draw(self, screen):
pygame.draw.circle(screen, YELLOW, (self.x, self.y), self.radius)
该接球比赛是一个简单的游戏示例,可以帮助初学者学习如何使用 Pygame 编写游戏。通过实现这个游戏,你可以学习如何使用类和 Pygame 中的常用方法,如:按键检测,游戏循环,绘制图形等等。