我正在尝试为学校项目构建一个粗略的打字游戏。我尝试使用线程方法(我只知道一点点)来使计时器与输入同时运行。这个想法是在计时器到时停止打字游戏。也许可以有一种不涉及使用线程的替代解决方案,它可以允许同时打字和倒计时。
我的方法最终的结果是,我只能在按回车键时停止打字,并且时间停止不起作用。感谢您的帮助! 我的代码:
import time
import datetime
import random
import threading
library = ["Hello","World"]
#There will be some text here
alphabet = {'a':0,'A':0,'b':0,'B':0,'c':0,'C':0,'d':0,'D':0,'e':0,'E':0,'f':0,'F':0,'g':0,'G':0,'h':0,'H':0,'i':0,'I':0,'J':0,'j':0,'k':0,'K':0,'l':0,'L':0,'m':0,'M':0,'n':0,'N':0,'o':0,'O':0,'p':0,'P':0,'q':0,'Q':0,'r':0,'R':0,'s':0,'S':0,'t':0,'T':0,'u':0,'U':0,'v':0,'V':0,'w':0,'W':0,'x':0,'X':0,'y':0,'Y':0,'z':0,'Z':0,',':0,'.':0,'-':0,"'":0,":":0}
alphabet2 = {'a':0,'A':0,'b':0,'B':0,'c':0,'C':0,'d':0,'D':0,'e':0,'E':0,'f':0,'F':0,'g':0,'G':0,'h':0,'H':0,'i':0,'I':0,'J':0,'j':0,'k':0,'K':0,'l':0,'L':0,'m':0,'M':0,'n':0,'N':0,'o':0,'O':0,'p':0,'P':0,'q':0,'Q':0,'r':0,'R':0,'s':0,'S':0,'t':0,'T':0,'u':0,'U':0,'v':0,'V':0,'w':0,'W':0,'x':0,'X':0,'y':0,'Y':0,'z':0,'Z':0,',':0,'.':0,'-':0,"'":0,"!":0,":":0}
def countdown1(h, m, s):
total_seconds = h * 3600 + m * 60 + s
while total_seconds > 0:
# Timer represents time left on countdown
timer = datetime.timedelta(seconds = total_seconds)
print(timer, end="\r")
# Delays the program one second
time.sleep(1)
# Reduces total time by one second
total_seconds -= 1
print("Start now!")
done = False
def countdown2():
c = 0
if done:
print("You used "+str(c)+" seconds to type!! Good Job!!")
while not done:
time.sleep(1)
c += 1
count = 0
print('You have 1 minute to type the following text')
c = random.randint(0,len(library)-1)
print(library[c])
print('Type after countdown, hit return after finishing or when the time is up')
countdown1(0,0,3)
threading.Thread(target=countdown2,daemon = True).start()
word = input().replace(" ", "")
done = True
passage = library[c].replace(" ", "")
total = len(passage)
for i in passage:
if i in alphabet2:
alphabet2[i] += 1
letter1 = []
letter2 = []
for i in word:
if i in alphabet:
alphabet[i] += 1
for key in alphabet.values():
letter1.append(int(key))
for key in alphabet2.values():
letter2.append(int(key))
for j in range(57):
count += min(letter1[j],letter2[j])
print('Congrats! You got '+str(count)+'/'+str(total)+' right!')
我不知道你是否可以接受,但你可以使用 Tkinter 创建这样的打字游戏,而不使用
threading
lib:
import tkinter as tk
from tkinter import messagebox
window = tk.Tk()
timeout = 30
time_left = timeout
label = tk.Label(window, text=time_left)
label.config(font=('Courier', 44))
label.pack()
text = tk.Text(window)
text.pack()
def update():
global time_left
global text
time_left -= 1
label.configure(text=time_left)
if time_left > 0:
window.after(1000, update)
else:
tk.messagebox.showinfo('Your score', str(len(text.get('1.0', 'end-1c'))))
window.after(1000, update)
window.mainloop()