如何在一定时间后跳过输入?Python 3

2024-04-27 03:26:48 发布

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

我是Python新手,正在自学。我正在尝试用Python 3制作一个老虎机游戏。我想给用户0.2秒的时间点击“回车”来停止,但我想不出来。下面是老虎机的代码:

def pyslot():
score = 0

    while True:
        rand1 = random.randint(1, 9)
        rand2 = random.randint(1, 9)
        rand3 = random.randint(1, 9)
        print(str(rand1) + "  " + str(rand2) + "  " + str(rand3))
        time.sleep(0.2)
        stop = input("")
        if stop == "":
            break
    if rand1 == rand2 and rand1 == rand3:
        print("All three?! No way!")
        score += 50
    elif (rand1 == rand2 and rand1 != rand3) or (rand2 == rand3 and rand2 != rand1) or (rand1 == rand3 and rand1 != rand2):
        print("Two are the same! Not too shabby!")
        score += 20
    else:
        print("No matches... too bad!")
    return score

我不知道怎么了。我在堆栈溢出上尝试了多种解决方案,但都不起作用。任何帮助都将不胜感激。另外,如何清除最后一行打印(这样程序就不会打印大量的槽卷)


1条回答
网友
1楼 · 发布于 2024-04-27 03:26:48

您可以使用^{}模块来检测按键并根据按键来停止进程。首先,您需要使用:pip install keyboard安装它,然后在代码中导入。下面是如何做到这一点的(顺便说一下,我已经重构了条件,因为有相当多的冗余检查):

import random, time, keyboard

def pyslot():
    score = 0

    while True:
        rand1 = random.randint(1, 9)
        rand2 = random.randint(1, 9)
        rand3 = random.randint(1, 9)
        print(str(rand1) + "  " + str(rand2) + "  " + str(rand3))
        time.sleep(0.2)
        if keyboard.is_pressed('enter'):
            print("You pressed Enter") # just to test
            break
    
    if rand1 == rand2 == rand3:
        print("All three?! No way!")
        score += 50
    elif rand1 == rand2 or rand2 == rand3 or rand1 == rand3:
        print("Two are the same! Not too shabby!")
        score += 20
    else:
        print("No matches... too bad!")
    return score

pyslot()

请注意,您需要以管理员身份运行,才能让python访问您的键盘

sudo python <file_name>可以做这项工作。最后,这里是输出:

7  9  1
4  4  4
6  4  6
2  9  7
5  7  2
4  5  3
4  9  7
4  5  1

You pressed Enter
No matches... too bad!

相关问题 更多 >