簡體   English   中英

我如何做到在按下一個鍵並釋放另一個鍵的同時發生動作? (pygame的/蟒)

[英]How do I make it so that while a key is pressed and another key is released an action occurs? (Pygame/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) 

為什么不起作用?

一種方法是使用pygame.key.get_pressed() 范例-

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()
    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_knowledge變量是一個列表,問題編號是自我解釋,而5是包含答案的索引。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM