2
2
import tkinter as tk
3
3
from tkinter import messagebox
4
4
5
+
5
6
def choose_word ():
6
7
words = ["apple" , "banana" , "cherry" , "date" , "elderberry" , "fig" , "grape" ]
7
8
return random .choice (words )
8
9
10
+
9
11
class HangmanGame :
10
12
def __init__ (self , master ):
11
13
self .master = master
@@ -22,7 +24,8 @@ def __init__(self, master):
22
24
self .entry_guess = tk .Entry (master )
23
25
self .entry_guess .pack ()
24
26
25
- self .button_guess = tk .Button (master , text = "Guess" , command = self .make_guess )
27
+ self .button_guess = tk .Button (
28
+ master , text = "Guess" , command = self .make_guess )
26
29
self .button_guess .pack ()
27
30
28
31
def display_word (self ):
@@ -38,34 +41,41 @@ def make_guess(self):
38
41
guess = self .entry_guess .get ().lower ()
39
42
40
43
if len (guess ) != 1 or not guess .isalpha ():
41
- messagebox .showwarning ("Invalid Input" , "Please enter a single letter." )
44
+ messagebox .showwarning (
45
+ "Invalid Input" , "Please enter a single letter." )
42
46
return
43
47
44
48
if guess in self .guessed_letters :
45
- messagebox .showinfo ("Already Guessed" , "You've already guessed this letter." )
49
+ messagebox .showinfo ("Already Guessed" ,
50
+ "You've already guessed this letter." )
46
51
return
47
52
48
53
self .guessed_letters .append (guess )
49
54
50
55
if guess not in self .word :
51
56
self .attempts += 1
52
- self .label_attempts .config (text = f"Attempts left: { 6 - self .attempts } " )
57
+ self .label_attempts .config (
58
+ text = f"Attempts left: { 6 - self .attempts } " )
53
59
54
60
self .label_word .config (text = self .display_word ())
55
61
56
62
if "_" not in self .display_word ():
57
- messagebox .showinfo ("Congratulations!" , f"You guessed the word: { self .word } " )
63
+ messagebox .showinfo ("Congratulations!" ,
64
+ f"You guessed the word: { self .word } " )
58
65
self .master .destroy ()
59
66
60
67
if self .attempts >= 6 :
61
- messagebox .showinfo ("Game Over" , f"Out of attempts! The word was: { self .word } " )
68
+ messagebox .showinfo (
69
+ "Game Over" , f"Out of attempts! The word was: { self .word } " )
62
70
self .master .destroy ()
63
71
72
+
64
73
def main ():
65
74
root = tk .Tk ()
66
75
root .title ("Hangman Game" )
67
76
game = HangmanGame (root )
68
77
root .mainloop ()
69
78
79
+
70
80
if __name__ == "__main__" :
71
81
main ()
0 commit comments