键盘事件
通过判断键盘按下进行位移指令
# 引用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=0running =True
# 进行循环
while running :# 绘制背景screen.blit(bgImg,(0,0))# 绘制玩家screen.blit(playerImg, (playerX, playerY))# 返回当前反应事件for event in pygame.event.get():#判断退出条件为点击叉号if event.type == pygame.QUIT:#退出循环running =False# 新增 KEYDOWN判断键盘按下的类型if event.type == pygame.KEYDOWN:# 新增 判断按下向左右键进行移动赋值if event.key == pygame.K_RIGHT:playerStep=1elif event.key == pygame.K_LEFT:playerStep=-1# 新增 KEYUP判断键盘抬起的类型if event.type == pygame.KEYUP:# 新增 抬起键盘时将移动距离改为0playerStep = 0# 新增 进行位移playerX+=playerStep# 控制边界if playerX > 378:playerX = 378if playerX < 0:playerX = 0if playerY > 572:playerY = 572if playerY > 572:playerY = 572# 界面更新pygame.display.update()
当如下所示按方向键控制飞机移动则成功