pygame小游戲打飛機_3鍵盤事件
鍵盤事件
通過判斷鍵盤按下的方向鍵執行位移指令
# 引用pygame
import pygame
# 使程序初始化
pygame.init()
# 設置圖像參數
screen = pygame.display.set_mode((480, 700))
# 設置標題
pygame.display.set_caption('打飛機')
# 引入圖片
icon = pygame.image.load('ufo.png')
pygame.display.set_icon(icon)
# 引入背景圖片
bgImg = pygame.image.load('background.png')
# 引入玩家圖片
playerImg = pygame.image.load('player.png')
# 定義玩家初始位置
playerX = 225
playerY = 350
# 新增 定義變量表示運動距離
playerStep = 0
running = True
# 進行循環 游戲主循環
while running:
# 繪制背景
screen.blit(bgImg, (0, 0))
# 繪制玩家
screen.blit(playerImg, (playerX, playerY))
# 獲取游戲事件隊列中的所有事件(涉及到玩家的各種交互,如鼠標點擊、鍵盤操作、窗口事件等)
for event in pygame.event.get():
# 如果事件是QUIT事件,如點擊窗口的關閉按鈕,則退出循環
if event.type == pygame.QUIT:
# 退出循環
running = False
# 新增 KEYDOWN判斷鍵盤按下的類型
if event.type == pygame.KEYDOWN:
# 新增 判斷按下向左右鍵進行移動賦值
if event.key == pygame.K_RIGHT:
playerStep = 1
elif event.key == pygame.K_LEFT:
playerStep = -1
# 新增 KEYUP判斷鍵盤抬起的類型
if event.type == pygame.KEYUP:
# 新增 抬起鍵盤時將移動距離改為0
playerStep = 0
# 新增 進行位移
playerX += playerStep
# 控制邊界
if playerX > 378:
playerX = 378
if playerX < 0:
playerX = 0
if playerY > 572:
playerY = 572
if playerY < 0:
playerY = 0
# 界面更新
pygame.display.update()
如下所示當按方向鍵(左、右)能控制飛機移動則成功

浙公網安備 33010602011771號