我如何使它,当一个键被按下,另一个键被释放一个行动发生(Pygame/Python)

2024-05-03 05:10:58 发布

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

所以基本上我在做一个问答游戏,用户必须“锁定”他们的答案。为了做到这一点,用户必须在按下某个键的同时按下另一个键。例如:按住“w”键,同时按下空格键,然后放开空格键。但是当我尝试实现这一点时,什么都没有发生。到目前为止,我掌握的情况如下:

if (event.type == pygame.KEYDOWN) and (event.key == pygame.K_w) and (event.type == pygame.KEYUP) and (event.key == pygame.K_SPACE):
    print(1) 

为什么这样不行


Tags: andkey答案用户event游戏iftype
2条回答
    question_num = general_knowlege_questions[0]
    keys = pygame.key.get_pressed()
    if keys[pygame.K_w] and (General_knowledge[question_num][5] == "a"):
        test = 1
    if keys[pygame.K_d] and (General_knowledge[question_num][5] == "b"):
        test = 1
    if keys[pygame.K_s] and (General_knowledge[question_num][5] == "c"):
        test = 1
    if keys[pygame.K_a] and (General_knowledge[question_num][5] == "d"):
        test = 1

所以基本上这是我的代码来识别我的测验答案,但它最终无法识别正确的答案。顺便说一句,General\ u knowledge变量是一个列表,问题编号是自我解释的,5是包含答案的索引

一种方法是使用^{}。示例-

keys = pygame.keys.get_pressed()

if keys[pygame.K_w] and keys[pygame.K_SPACE]:
    print(1)  

编辑:我就是这样实现的-

#!/usr/bin/python3
import pygame
from pygame.locals import *
from sys import exit


#initializing variables
pygame.init()
screen=pygame.display.set_mode((640,480),0,24)
pygame.display.set_caption("Key Press Test")
f1=pygame.font.SysFont("comicsansms",24)

#main loop which displays the pressed keys on the screen
while True:
    for i in pygame.event.get():
        a=100
        screen.fill((255,255,255))
        if pygame.key.get_focused():
            press=pygame.key.get_pressed()

            # checking if they are pressed at the same time or not.
            if press[pygame.K_w] and press[pygame.K_SPACE]:
                print (1)
            for i in xrange(0,len(press)):
                if press[i]==1:
                    name=pygame.key.name(i)
                    text=f1.render(name,True,(0,0,0))
                    screen.blit(text,(100,a))
                    a=a+100
            pygame.display.update()

相关问题 更多 >