大家好!今天給你們帶來了墜落的小鳥遊戲,幫我們更好了解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()