下载地址:飞行的小鸟.zip - 蓝奏云文件大小:87.8 K|https://shunianssy.lanzouw.com/i3YOF1bus43i
代码如下;
import pgzrun
import random
# 设置窗口宽度和高度
WIDTH = 800
HEIGHT = 600
# 创建小鸟角色并设置初始位置
bird = Actor("bird.png")
bird.pos = (100, HEIGHT/2)
# 设置管道间隙和移动速度
pipe_gap = 200
pipe_speed = 4
# 创建上方管道和下方管道角色
top_pipe = Actor("pipe_up.png", anchor=("left", "bottom"))
bottom_pipe = Actor("pipe_down.png", anchor=("left", "top"))
# 初始化得分和游戏结束状态
score = 0
game_over = False
def update():
global score, game_over
if not game_over:
# 小鸟下落
bird.y += 2
# 检查是否碰撞到管道或超出窗口
if bird.y >= HEIGHT or check_collision():
game_over = True
else:
# 检查是否通过了管道,更新得分
check_score()
# 更新管道位置
update_pipes()
def on_key_down():
if not game_over:
# 按下键盘时,小鸟向上飞行
bird.y -= 50
def draw():
screen.clear()
# 绘制角色和得分
bird.draw()
top_pipe.draw()
bottom_pipe.draw()
screen.draw.text("Score: " + str(score), (10, 10), color="white")
if game_over:
# 如果游戏结束,显示游戏结束文本
screen.draw.text("Game Over", center=(WIDTH/2, HEIGHT/2), color="white")
def reset_game():
global score, game_over
# 重置得分和游戏结束状态
score = 0
game_over = False
# 将小鸟位置恢复到初始位置
bird.y = HEIGHT/2
# 创建新的管道
create_pipes()
def check_collision():
# 检查小鸟是否与管道或超出窗口碰撞
return bird.colliderect(top_pipe) or bird.colliderect(bottom_pipe) or bird.y >= HEIGHT
def check_score():
global score
if bird.x > top_pipe.x + top_pipe.width/2 and bird.x < top_pipe.x + top_pipe.width/2 + pipe_speed:
# 小鸟通过一对管道,增加得分
score += 1
def create_pipes():
# 随机生成管道的高度
pipe_gap_y = random.randint(200, 400)
# 设置上下管道的位置
top_pipe.pos = (WIDTH, pipe_gap_y - pipe_gap/2)
bottom_pipe.pos = (WIDTH, pipe_gap_y + pipe_gap/2)
def update_pipes():
global score
# 移动管道
top_pipe.x -= pipe_speed
bottom_pipe.x -= pipe_speed
if top_pipe.right < 0:
# 管道超出窗口左侧,重置管道位置并增加得分
top_pipe.x = WIDTH
bottom_pipe.x = WIDTH
create_pipes()
score += 1
# 创建初始管道
create_pipes()
# 运行游戏
pgzrun.go()