python贪吃蛇游戏项目 pygame键盘控制(移动角色)

import pygame
import sys

pygame.init()

WIDTH, HEIGHT = 640, 480
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Movement")

clock = pygame.time.Clock()

# 玩家属性
player_x = 300
player_y = 220
player_speed = 5
PLAYER_SIZE = 50

WHITE = (255, 255, 255)
BLUE = (0, 120, 255)
BG_COLOR = (30, 30, 30)

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 侦测所有按键
    keys = pygame.key.get_pressed()

    # 按住移动
    if keys[pygame.K_LEFT]:
        player_x -= player_speed
    if keys[pygame.K_RIGHT]:
        player_x += player_speed
    if keys[pygame.K_UP]:
        player_y -= player_speed
    if keys[pygame.K_DOWN]:
        player_y += player_speed
    if keys[pygame.K_q] :
        running = False

    # 边界限制
    player_x = max(0, min(player_x, WIDTH - PLAYER_SIZE))
    player_y = max(0, min(player_y, HEIGHT - PLAYER_SIZE))

    # 绘图
    screen.fill(BG_COLOR)

    # 玩家以蓝色方块显示
    pygame.draw.rect(screen, BLUE, (player_x, player_y, PLAYER_SIZE, PLAYER_SIZE))

    pygame.display.flip()
    clock.tick(60)

pygame.quit()
sys.exit()
功能 用途
pygame.key.get_pressed() 侦测所有按键(持续按住的动作)
pygame.K_LEFT 等键位 用来判断是否按住左右上下
基本移动逻辑 x += speedy -= speed
边界控制 防止角色跑出画面