Я создаю игру Hangman для домашней работы, которая использует tkinter для создания окна с холстом, полем ввода и некоторыми надписями. Моя самая большая трудность на данный момент заключается в том, что буква, которую вводит пользователь, учитывается в остальной части кода и изменяет другие переменные. Например, если пользователь вводит неправильную букву, мой «счетчик попыток» должен быть вычтен на единицу, буква должна быть помещена под меткой «Воспроизведенные буквы:», и должна появиться часть тела палача. Если пользователь вводит правильно, то буква заменяет соответствующее подчеркивание.
Как мне изменить мой код, в котором введенная буква пользователя меняет другие функции / переменные?
Я часами возился с моим кодом, кое-что меняя в попытке, но ничего, что я делаю, кажется, не работает и только создает больше проблем.
currentLetter = ''
wordchoice = ''
t = IntVar()
new_list = []
letters_played = StringVar()
letter = None
#Creates the word bank
def wordbank(new_list):
with open("Dictionary.txt","r") as w_choices:
for line in w_choices:
x = line.strip('\n')
new_list.append(x)
#Randomly chooses a word off of the list and holds it as a variable
def grab_word():
wordchoice = random.choice(new_list)
return wordchoice
#Creates the canvas for the Hangman body and texts that will show if you lose
def canvas(game): #hangman and body
global t, wordchoice
Lose = StringVar()
Reveal = StringVar()
Play = StringVar()
w = Canvas(game, width=500, height=500)
w.pack()
w.create_rectangle(100,50,400,60, fill = "grey") #hangman stand
w.create_rectangle(100,50,60,400, fill = "grey")
w.create_line(250,60,250,100)
if t == 4:
w.create_oval(225,100,275,150, fill = "red") #body parts
if t == 3:
w.create_oval(225,100,275,150, fill = "red")
w.create_line(250,150,250,300)
if t == 2:
w.create_oval(225,100,275,150, fill = "red")
w.create_line(250,150,250,300)
w.create_line(250,200,200,185)
w.create_line(250,200,300,185)
if t == 1:
w.create_oval(225,100,275,150, fill = "red")
w.create_line(250,150,250,300)
w.create_line(250,200,200,185)
w.create_line(250,200,300,185)
w.create_line(250,300,200,375)
w.create_line(250,300,300,375)
if t == 0:
w.create_oval(225,100,275,150, fill = "red")
w.create_line(250,150,250,300)
w.create_line(250,200,200,185)
w.create_line(250,200,300,185)
w.create_line(250,300,200,375)
w.create_line(250,300,300,375)
Lose.set("Sorry! You lost. Your word was")
Reveal.set(wordchoice)
Play.set("If you would like to play again, press")
Button(game, text="Restart", command=restart_program).pack()
def gettingLetter(event):
global currentLetter, letter
currentLetter = letter.get()
letter.delete(0, END)
#User inputs a letter and it uses the function above to assign the input to a variable
def entry_field():
global letter
guess = Label(game, text="Enter a letter")
guess.pack()
letter = Entry(game)
letter.bind("<Return>", gettingLetter)
letter.pack()
#Trouble here: Putting the user input into a string variable that will show all of the inputs the user has done
def Letters():
global letters_played, letter, currentLetter
letters_played.set(letters_played.get() + currentLetter)
Letterbox = Label(game, text= "Letters Played: ").pack()
letters = Label(game, text = letters_played.get()).pack()
#Trouble here: Displays the len of the word as underscores. Can't figure out how to have
#the underscores be replaced with the correct letter if the user inputs it.
def underscore():
global currentLetter, wordchoice
x = list(grab_word())
unders = []
for i in x:
unders += "_"
unds = Label(game, text = unders)
unds.pack()
#Trouble here: Counter will not go do from 5 after each incorrect input
def tries_counter(t, currentLetter, wordchoice):
t.set(5)
counter = Label(game, text = "Tries left:").pack()
tries = Label(game, text = t.get()).pack()
if currentLetter in wordchoice:
pass
else:
t.set(t.get()-1)
Я ожидаю, что буква изменит отдельные области окна (количество попыток, количество сыгранных букв, подчеркивание и т. д.), однаконичего не происходит.