Python 只有一个事件键在工作
所以我正在用python开发一个游戏。这是我的密码:Python 只有一个事件键在工作,python,pygame,Python,Pygame,所以我正在用python开发一个游戏。这是我的密码: bif="main_background.jpg" pif="player_head.png" import pygame, sys from pygame.locals import * pygame.init() screen=pygame.display.set_mode((900,600),0,32) background=pygame.image.load(bif).convert() player_sprite=pygame
bif="main_background.jpg"
pif="player_head.png"
import pygame, sys
from pygame.locals import *
pygame.init()
screen=pygame.display.set_mode((900,600),0,32)
background=pygame.image.load(bif).convert()
player_sprite=pygame.image.load(pif).convert_alpha()
x,y=0,0
movex, movey=0,0
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type==KEYDOWN:
if event.key==K_RIGHT:
movex=+1
if event.type==K_LEFT:
movex=-1
if event.type==K_UP:
movey=-1
if event.type==K_DOWN:
movey=+1
if event.type==KEYUP:
if event.key==K_RIGHT:
movex=0
if event.type==K_LEFT:
movex=0
if event.type==K_UP:
movey=0
if event.type==K_DOWN:
movey=0
x+=movex
y+=movey
screen.blit(background, (0,0))
screen.blit(player_sprite, (x,y))
pygame.display.update()
但问题是只有第一个event.key起作用(K_RIGHT)
只有当我按下向右箭头键时,精灵才会移动
我还尝试用elif替换第二、第三和第四个event.key,但都不起作用。您使用的是
event.type
而不是event.key
来替换所有其他键,除了K_RIGHT
(有效)。这就解释了为什么其他键不起作用。此外,你应该写:
movex += 1
或
等等,使精灵改变位置。这将增加和减少精灵的位置。写入
movex+=1
是movex=movex+1
的简写,您使用的是事件。键入而不是事件。除了K_RIGHT
(正常工作)以外的所有其他键都键入。这就解释了为什么其他键不起作用。此外,你应该写:
movex += 1
或
等等,使精灵改变位置。这将增加和减少精灵的位置。书写movex+=1
是movex=movex+1
的简写,你检查event.key==K_RIGHT
但是对于其他方向,你做event.type==K_LEFT
等。你检查event.key==K_RIGHT
但是对于其他方向,您需要event.type==K_LEFT
等。次要问题:您确定要同时使用KEYDOWN
和keydup
事件来移动精灵吗?次要问题:您确定要同时使用KEYDOWN
和keydup
事件来移动精灵吗?谢谢。你能用这个答案旁边的复选标记把它标记为回答你问题的那个吗?谢谢。你能用这个答案旁边的复选标记把它标记为回答你问题的那个吗?