You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pygame键盘移动指令失效,游戏窗口无法正常关闭求助

问题原因与修复方案

核心错误点

  • 事件类型判断逻辑错误:Pygame中判断事件类型必须使用event.type属性,你直接用event == pygame.QUIT、event == pygame.KEYDOWN这种写法完全无效,导致关闭窗口事件、键盘按下/抬起事件都无法被正确捕获,这就是角色移动和窗口关闭功能失效的根本原因。
  • 缺少ESC键关闭逻辑:代码里没有监听ESC键的按下事件,所以按下ESC自然无法关闭窗口。

修正后的完整代码

import pygame
import os

pygame.init() 

screen_width = 480 
screen_height = 640 
screen = pygame.display.set_mode((screen_width,screen_height))

pygame.display.set_caption("June's Game")

background = pygame.image.load("D:/Python/pygame_basic/background.png")

character = pygame.image.load("D:/Python/pygame_basic/character.png")
character_size = character.get_rect().size 
character_width = character_size[0] 
character_height = character_size[1] 
character_x_position = (screen_width / 2) - (character_width / 2) 
character_y_position = screen_height - character_height

to_x = 0
to_y = 0

running = True # 게임이 진행중인가

while running:
    for event in pygame.event.get(): 
        # 修正:通过event.type判断窗口退出事件
        if event.type == pygame.QUIT: 
            running = False
        # 修正:通过event.type判断键盘按下事件
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                to_x -= 5
            elif event.key == pygame.K_RIGHT:
                to_x += 5
            elif event.key == pygame.K_UP:
                to_y -= 5
            elif event.key == pygame.K_DOWN:
                to_y += 5
            # 添加ESC键关闭窗口的逻辑
            elif event.key == pygame.K_ESCAPE:
                running = False

        # 修正:通过event.type判断键盘抬起事件
        if event.type == pygame.KEYUP: 
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                to_x = 0
            elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
                to_y = 0

    character_x_position += to_x
    character_y_position += to_y

    # 可选优化:限制角色移动范围,防止移出屏幕
    character_x_position = max(0, min(character_x_position, screen_width - character_width))
    character_y_position = max(0, min(character_y_position, screen_height - character_height))

    screen.blit(background, (0,0)) 
    screen.blit(character, (character_x_position,character_y_position))
    pygame.display.update()

pygame.quit()

内容的提问来源于stack exchange,提问作者June Lim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 08:50:42