Python使用空格键从输入继续 [英] Python continue from input with the space key

查看:190
本文介绍了Python使用空格键从输入继续的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个打字速度测试游戏,并试图制作它,以便当用户在python输入中输入python input()时,可以由他们在Windows上按空格而不是直接输入来提交. 我的代码类似于以下内容:

I'm making a typing speed test game and trying to make it so that when a user is typing into a python input(), it can be submitted by them pressing space rather than just enter, on Windows. My code is similar to the following:

score = 0
start_time = int(time.time())
characters = 0
words = 0
current_word = random.choice(WORDS)
next_word = random.choice(WORDS)
while (int(time.time()) - start_time) <= TIME_LIMIT:
    os.system('cls')
    print(f"Your word is {current_word}")
    print(f"The next word will be {next_word}")
    print(f"Your current score is {score}")
    attempt = input("> ")
    if attempt.lower() == current_word.lower():
        score = score + 1
        words = words + 1
        characters = characters + len(current_word)
    current_word = next_word
    next_word = random.choice(WORDS)

有什么办法可以解决这个问题,还是最好创建自己的输入函数?

Is there any way for this to work or is it best to maybe create my own input function?

推荐答案

通过创建以下自己的输入函数来解决此问题:

Solved this by creating my own input function as below:

def custom_input(prefix=""):
    """Custom string input that submits with space rather than enter"""
    concatenated_string = ""
    sys.stdout.write(prefix)
    sys.stdout.flush()
    while True:
        key = ord(getch())
        # If the key is enter or space
        if key == 32 or key == 13:
            break
        concatenated_string = concatenated_string + chr(key)
        # Print the characters as they're entered
        sys.stdout.write(chr(key))
        sys.stdout.flush()
    return concatenated_string

这篇关于Python使用空格键从输入继续的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆