当前位置: 欣欣网 > 码农

Python 坠落的小鸟游戏

2024-02-07码农

大家好!今天给你们带来了坠落的小鸟游戏,帮我们更好了解pygame库。

完整代码:

  • importpygameimportsysimportrandom# 初始化pygamepygame.init()# 设置屏幕大小screen_width = 400screen_height = 600screen = 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, scorebird_y = 300bird_y_change = 0pipe_x = screen_widthpipe_height = random.randint(200, 400)game_over = Falsescore = 0# 小鸟参数bird_x = 50bird_y = 300bird_width = 30bird_height = 30bird_y_change = 0# 重力gravity = 0.5# 跳跃高度jump_height = -10# 障碍物参数pipe_width = 70pipe_height = random.randint(200, 400)pipe_color = greenpipe_x = screen_widthpipe_speed = 2gap = 200 # 上下管道之间的间隙# 游戏状态game_over = Falsescore = 0# 游戏主循环running = Truewhilerunning: # 处理事件forevent in pygame.event.get():ifevent.type == pygame.QUIT:running = Falseifevent.type == pygame.KEYDOWN:ifevent.key == pygame.K_SPACE and not game_over:bird_y_change = jump_heightifevent.key == pygame.K_SPACE and game_over:reset_game() # 更新小鸟位置bird_y_change+= gravitybird_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_widthpipe_height = random.randint(200, 400)score+= 1 # 每通过一个障碍物,分数加1 # 碰撞检测ifbird_y > screen_height - bird_height or bird_y < 0:game_over = Trueifpipe_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)# 退出pygamepygame.quit()sys.exit()