大家好!今天给你们带来了坠落的小鸟游戏,帮我们更好了解pygame库。
完整代码:
importpygame
importsys
importrandom
# 初始化pygame
pygame.init()
# 设置屏幕大小
screen_width = 400
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
# 设置颜色
white = (255, 255, 255)
blue = (0, 0, 255) # 小鸟的颜色
green = (0, 255, 0) # 障碍物的颜色
black = (0, 0, 0) # 文字颜色
# 设置帧率
clock = pygame.time.Clock()
fps = 60
# 设置字体
font = pygame.font.SysFont(None, 32)
defdisplay_score(score):
score_text = font.render(f'Score: {score}', True, black)
screen.blit(score_text,(10, 10))
defreset_game():
globalbird_y, bird_y_change, pipe_x, pipe_height, game_over, score
bird_y = 300
bird_y_change = 0
pipe_x = screen_width
pipe_height = random.randint(200, 400)
game_over = False
score = 0
# 小鸟参数
bird_x = 50
bird_y = 300
bird_width = 30
bird_height = 30
bird_y_change = 0
# 重力
gravity = 0.5
# 跳跃高度
jump_height = -10
# 障碍物参数
pipe_width = 70
pipe_height = random.randint(200, 400)
pipe_color = green
pipe_x = screen_width
pipe_speed = 2
gap = 200 # 上下管道之间的间隙
# 游戏状态
game_over = False
score = 0
# 游戏主循环
running = True
whilerunning:
# 处理事件
forevent in pygame.event.get():
ifevent.type == pygame.QUIT:
running = False
ifevent.type == pygame.KEYDOWN:
ifevent.key == pygame.K_SPACE and not game_over:
bird_y_change = jump_height
ifevent.key == pygame.K_SPACE and game_over:
reset_game()
# 更新小鸟位置
bird_y_change+= gravity
bird_y+= bird_y_change
# 绘制背景
screen.fill(white)
# 绘制小鸟
pygame.draw.rect(screen,blue, (bird_x, bird_y, bird_width, bird_height))
# 绘制障碍物
pygame.draw.rect(screen,pipe_color, (pipe_x, 0, pipe_width, pipe_height))
pygame.draw.rect(screen,pipe_color, (pipe_x, pipe_height + gap, pipe_width, screen_height))
# 更新障碍物位置
pipe_x-= pipe_speed
# 障碍物循环
ifpipe_x < -pipe_width:
pipe_x = screen_width
pipe_height = random.randint(200, 400)
score+= 1 # 每通过一个障碍物,分数加1
# 碰撞检测
ifbird_y > screen_height - bird_height or bird_y < 0:
game_over = True
ifpipe_x < bird_x + bird_width < pipe_x + pipe_width:
ifbird_y < pipe_height or bird_y + bird_height > pipe_height + gap:
game_over = True
# 显示分数
display_score(score)
# 游戏结束处理
ifgame_over:
reset_game()# 此处重置游戏以便重新开始
# 更新显示
pygame.display.update()
# 控制帧率
clock.tick(fps)
# 退出pygame
pygame.quit()
sys.exit()