I'm pretty new to programming and started of by learning some Python. I thought it would be a fun challenge to create a game just like "Typeracer" but only typing the alphabet as fast as possible. I used Tkinter to build a GUI for it. I started with just checking if a user input is equal to a string then display that they won using this code:
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()
But then I wanted to up the challenge and require the user input to be exactly equal to the next letter in the alphabet, no typos was allowed.
I'm sort of stuck at this point and my problem is that I don't know how to write code that only checks the next input from the user. And if it's the expected input, do this, else do that.
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()
Any help or tips are greatly appriciated! Thanks!