1、**pygame.KEYDOW ------ **检测按键瞬间动作
检测按键被按下的瞬间事件:pygame.KEYDOWN # 有延迟
获取按键状态 (实现平滑移动) : pygame.key.get_pressed()
键盘上的左箭头:pygame.K_LEFT
键盘上的右箭头:pygame.K_RIGHT
python
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player_rect.x -= 10 # 直接修改 x 坐标
elif event.key == pygame.K_RIGHT:
player_rect.x += 10 # 直接修改 x 坐标
2、pygame.key.get_pressed() ------ 持续获取按键状态
注意:如果使用 get_pressed,不需要放在 if event.type == KEYDOWN 块中
python
# 在 while 循环内部,事件处理之后
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player_rect.x -= 5 # 每帧移动 5 像素,速度更平滑
if keys[pygame.K_RIGHT]:
player_rect.x += 5
3、边界检查
python
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and player_rect.left > 0:
player_rect.x -= 5
if keys[pygame.K_RIGHT] and player_rect.right < screen_width: # screen_width 是窗口宽度
player_rect.x += 5
4、按键控制方块移动(完整代码)
python
import pygame
import sys
# 初始化
pygame.init()
# 设置窗口
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption("键盘控制方块移动")
# 创建玩家矩形 (x, y, width, height)
player_rect = pygame.Rect(350, 250, 50, 50)
player_color = (255, 0, 0) # 红色
# 时钟对象,用于控制帧率
clock = pygame.time.Clock()
running = True
while running:
# 1. 事件处理
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 2. 获取按键状态 (实现平滑移动)
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player_rect.x -= 5
if keys[pygame.K_RIGHT]:
player_rect.x += 5
# 可选:添加上下移动
if keys[pygame.K_UP]:
player_rect.y -= 5
if keys[pygame.K_DOWN]:
player_rect.y += 5
# 3. 边界检查 (防止移出屏幕)
if player_rect.left < 0:
player_rect.left = 0
if player_rect.right > 800:
player_rect.right = 800
if player_rect.top < 0:
player_rect.top = 0
if player_rect.bottom > 600:
player_rect.bottom = 600
# 4. 绘制
screen.fill((0, 0, 0)) # 黑色背景
pygame.draw.rect(screen, player_color, player_rect) # 绘制玩家
# 5. 更新显示
pygame.display.flip()
# 控制帧率为 60 FPS
clock.tick(60)
pygame.quit()
sys.exit()
5、补充知识点:创建矩形
创建玩家矩形 (x, y, width, height)
player_rect = pygame.Rect(350, 250, 50, 50) #x,y,宽,高
player_color = (255, 0, 0) # 红色
pygame.draw.rect(screen, player_color, player_rect)
player_rect = pygame.Rect(350, 250, 50, 50)player_rect.x -= 5 x坐标-5