[英]Detecting when a key is pressed and break when another key is pressed[Python]
所以我正在制作一個沒有 PyGame 的游戲,我想添加一個部分,您可以嘗試按給定字母“數字”的正確鍵盤字母,這意味着 A - 1, B - 2, C - 3,等等。我想讓你不能把每把鑰匙都搗碎,所以我加了一個計數器。 但是 - 計數器不起作用。 幫助!
def keyboardpart(l,x,num):
for i in range(num):
keypress = False
c = 0
dn = random.randint(0,25)
var = l[dn]
print(dn+1)
flag1 = False
start = time.time()
while time.time()-start < x:
if keypress and not keyboard.is_pressed(var):
if c > 3:
break
c+=1
elif keyboard.is_pressed(var) and not keypress:
keypress = True
print(keypress,c)
if not keypress:
print("Sorry, you missed that key.")
flag1 = True
break
if flag1:
keyboardpart(l,x,num)
檢查是否按下了任何鍵,然后檢查是否按下了目標鍵。 還要等到所有鍵都釋放后再重試。
試試這個代碼:
import random, keyboard, time
l = [chr(65+i) for i in range(26)] # A-Z
def keyboardpart(l,x,num):
for i in range(num):
keyboard.is_pressed(65) # process OS events
while len(keyboard._physically_pressed_keys): pass # wait until keys released
keypress = False
c = 0
dn = random.randint(0,25)
var = l[dn]
print(dn+1, l[dn])
flag1 = False
start = time.time()
while time.time()-start < x:
if len(keyboard._physically_pressed_keys): # any key down
if keyboard.is_pressed(var): # check target key
keypress = True
break
else: # wrong key
c+=1
if c >= 3: break # allow 3 tries
while len(keyboard._physically_pressed_keys): pass # wait until keys released
print(keypress, c)
print(keypress,c)
if not keypress:
print("Sorry, you missed that key.")
flag1 = True
break
if flag1:
keyboardpart(l,x,num)
keyboardpart(l,100,4)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.