python 3.2:pygame.KEYDOWN只工作一次?

2024-04-29 16:09:54 发布

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

我的密码是:

import pygame, sys, os
from pygame.locals import *
from time import sleep
import os

path = os.getcwd()
os.chdir(path + '\Assets')

pygame.init()

FPS = 30
fpsClock = pygame.time.Clock()

DISPLAYSURF = pygame.display.set_mode((800, 500))
pygame.display.set_caption('fightR')

WHITE = (225, 225, 225)
SILVER = (192, 192, 192)
BGCOLOR = SILVER
fkx = 70
fky = 252
SPEED = 5
jump = False

#loading images
fighter_kungfu_1 = pygame.image.load('fighter_kungfu_1.png')
fighter_kungfu_jump = pygame.image.load('fighter_kungfu_jump.png')

def CheckForQuit() :
    for event in pygame.event.get():
       if event.type == QUIT:
          pygame.quit()
          sys.exit()

#MGL
while True:

    DISPLAYSURF.fill(BGCOLOR)

    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN and event.key == pygame.K_a:
            if (fkx > 2):        
                 global fkx
                 fkx = fkx - SPEED
        elif event.type == pygame.KEYDOWN and event.key == pygame.K_d:
            if (fkx < 300):
                global fkx
                fkx = fkx + SPEED
    elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
        jump = True

if (jump):
    DISPLAYSURF.blit(fighter_kungfu_jump, (fkx - 25, fky - 10))
    #sleep(0.5)
else:
    DISPLAYSURF.blit(fighter_kungfu_1, (fkx, fky))

jump = False

CheckForQuit()

pygame.display.update()
fpsClock.tick(FPS)
pygame.display.flip()

如果需要,可提供指向图像的链接:
https://drive.google.com/open?id=0B4Aq1fJx1P4AQkE1ZTZLR1ZCRW8
https://drive.google.com/open?id=0B4Aq1fJx1P4AeXB5UjYtZ29XU1k
(将它们放在“资产”文件夹中)

我在游戏中的问题是:当我按下“a”或“d”按钮并按住它时,我的角色只移动一次,而不是连续移动。在

我试图用“while”循环代替“if”和“elif”:

^{pr2}$

但它根本不起作用。在

有人能帮帮我吗?在


Tags: importeventifostypedisplaypygamespeed
1条回答
网友
1楼 · 发布于 2024-04-29 16:09:54

默认情况下,pygame.KEYDOWN事件只在按键从未按下变为按下时发生,而您只执行一次。在

如果要跟踪按下的关键点,可以在接收keydown事件时设置标志,然后在接收keyup事件时取消设置。在

或者,您可以使用get_pressed函数(https://www.pygame.org/docs/ref/key.html#pygame.key.get_pressed)来获取键盘键的当前状态。在

您还可以查看如何使用https://www.pygame.org/docs/ref/key.html#pygame.key.set_repeat设置keydown事件。但是,我认为在各种事件上设置标志是最好的解决方案,然后检查密钥状态作为第二个最佳选择。在

相关问题 更多 >