【问题标题】:Detecting when a key is pressed and break when another key is pressed[Python]检测何时按下一个键并在按下另一个键时中断[Python]
【发布时间】:2021-02-02 16:04:17
【问题描述】:

所以我正在制作一个没有 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)

【问题讨论】:

  • 如果您在同一个循环中设置c = 0c &gt; 3 怎么可能是真的?您的意思是在循环之外声明它吗?
  • 我对每个不同的字母都使用 c = 0,所以每次循环时,我都会选择玩家必须输入的另一个字母。 while 循环作为一个计时器,玩家可以尝试输入。但是,我希望它基本上每次按下另一个键时计数,当超过 3 时打破 while 循环并重新启动。
  • 没关系,我的错。

标签: python module keyboard


【解决方案1】:

检查是否按下了任何键,然后检查是否按下了目标键。还要等到所有键都释放后再重试。

试试这个代码:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-23
    • 1970-01-01
    • 2014-09-03
    • 1970-01-01
    • 2021-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多