我正在制作一个打字速度测试游戏,并试图做到这一点,以便当用户在 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/