仅有1个事件键可以使用

2024-09-27 07:27:55 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我在用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.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()

但问题是事件.key正在工作(Kyu RIGHT)

精灵只在我按右箭头键时移动。在

我也试过换第二,第三和第四事件.key但也没用。在


Tags: keyimportrighteventiftypesysscreen
2条回答

您使用的是event.type而不是event.key作为所有其他键,除了K_RIGHT(它可以工作)。这就解释了为什么其他钥匙不起作用了。另外,你应该写下:

movex += 1

或者

^{pr2}$

等等来改变精灵的位置。这将增加和减少精灵的位置。写movex += 1movex = movex + 1的简写。在

您选中event.key==K_RIGHT,但对于其他方向,则执行event.type==K_LEFT

相关问题 更多 >

    热门问题