我正在尝试编写一个 python 打字测试,它在 60 秒的定时 while 循环中显示列表中的 5 个字母单词。如果用户在每个键入的单词后按回车键,一切都会正常,但这允许退格,这不是我的目标。在没有按下回车键的情况下输入 5 个键(包括箭头键和退格键)后 input() 是否能够继续?就像按下回车键一样继续下一个单词?
import time
import random
t_end = time.time() + 60 # Set timer for 60 seconds
correct = 0
incorrect = 0
attempts = 0
accuracy = 0
words=["buggy", "Help!", "etc.."] #TODO: put lots of 5 character words a list
while time.time() < t_end:
for word in random.sample(words, 1):
print(word, end=" ")
wpm_count += 1
user_txt = input(" ")
if (user_txt == word):
correct += 1
else:
incorrect += 1
#Calculate and display results
accuracy = (correct / attempts ) * 100
print("=-=-=- Results: -=-=-= \nCorrect: " + str(correct) + " \nErrors: " + str(incorrect) + " \n Total WPM: " + str(attempts) + "\nAccuracy: " + str(accuracy) )
是的,您可以使用 curses 模块中的 getch() 函数来读取键盘输入,而无需用户在每个单词后按 Enter 键。这是使用 getch() 实现代码的示例:
import time
import random
import curses
t_end = time.time() + 60 # Set timer for 60 seconds
correct = 0
incorrect = 0
attempts = 0
accuracy = 0
words=["buggy", "Help!", "etc.."] #TODO: put lots of 5 character words a list
# initialize the curses module
stdscr = curses.initscr()
curses.cbreak()
stdscr.keypad(True)
# loop until the timer runs out
while time.time() < t_end:
for word in random.sample(words, 1):
stdscr.addstr(word + " ")
stdscr.refresh()
# read input without requiring Enter
user_txt = ""
while len(user_txt) < len(word):
c = stdscr.getch()
if c == curses.KEY_BACKSPACE:
user_txt = user_txt[:-1] # remove last character
elif c >= 32 and c <= 126: # printable characters
user_txt += chr(c)
elif c == 27: # escape key
break
# compare input to expected word
attempts += 1
if user_txt == word:
correct += 1
else:
incorrect += 1
# cleanup curses module
curses.nocbreak()
stdscr.keypad(False)
curses.echo()
curses.endwin()
# calculate and display results
accuracy = (correct / attempts ) * 100
print("=-=-=- Results: -=-=-= \nCorrect: " + str(correct) + " \nErrors: " + str(incorrect) + " \n Total WPM: " + str(attempts) + "\nAccuracy: " + str(accuracy) )