我对编程相当陌生,从学习一些Python开始。我认为这将是一个有趣的挑战,创造一个游戏就像“Typeracer”,但只键入字母尽可能快。我用Tkinter为它构建了一个GUI。我刚开始检查用户输入是否等于字符串,然后使用以下代码显示他们赢了:
from tkinter import *
import time
key = "abcdefghijklmnopqrstuvwxyz"
start_time = time.time()
root = Tk()
root.title("ABC Game")
answer = Entry(root, width=50)
answer.grid(row=0, column=0)
def check_answer():
if answer.get() == key:
end_time = time.time()
result_time = round(end_time - start_time, 3)
label_won = Label(root, text="Correct! Your time was: " + str(result_time))
label_won.grid(row=2, column=0)
else:
label_lost = Label(root, text="Incorrect")
label_lost.grid(row=2, column=0)
answer_button = Button(root, text="Submit", command=check_answer)
answer_button.grid(row=1, column=0)
root.mainloop()
但后来我想挑战一下,要求用户输入与字母表中的下一个字母完全相等,不允许输入错误
我在这一点上有点卡住了,我的问题是我不知道如何编写只检查用户下一次输入的代码。如果它是预期的输入,那么做这个,否则做那个
from tkinter import *
import time
alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
"n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
root = Tk()
root.title = "ABC Game"
game_running = False
#This is the part where I'm stuck, might be faults in the code at other places as well
def key_pressed(event):
global pressed_key
pressed_key = repr(event.char)
n_keys_pressed = 0
for letters in alphabet:
while n_keys_pressed <= 28:
if str(pressed_key) == alphabet[n_keys_pressed]:
n_keys_pressed += 1
print("You hit: " + repr(event.char))
def start_game():
global game_running
game_running = True
start_time = time.time
type_frame = Frame(root)
start_button = Button(root, text="Click me to start the timer", width=50, height=10, command=start_game)
start_button.grid(row=0, column=0)
entry = Entry(root, width=50)
entry.grid(row=1, column=0)
root.mainloop()
非常感谢您的任何帮助或提示!谢谢
您需要使用导入时间功能并键入time.timer(为计时需要多少秒)
相关问题 更多 >
编程相关推荐