當前位置: 妍妍網 > 碼農

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()