Python 使用空格键从输入继续

标签 python input key-bindings

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

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)

有什么方法可以让它工作,还是最好创建我自己的输入函数?

最佳答案

通过创建我自己的输入函数解决了这个问题,如下所示:

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 使用空格键从输入继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47954657/

相关文章:

vim - 如何以不同方式映射 Ctrl+A 和 Ctrl+Shift+A?

python - 将不重复的随机数 append 到列表中

python - 更改 matplotlib pyplot 图例中线条的线宽

jquery - Ryan Fait 自定义表单元素插件。多个 CSS 类问题

javascript - 将图像数据设置到输入文件标签中

iphone - iOS 5 : Set min and max value of input type ="date"

java - 按住键后做某事并在释放和按下时重复

python - 基于记录数据的SqlAlchemy模型关联

python - 用 Python 制作 JSON

java - jdialog 输入和转义不起作用