forked from dipu-s-repo68/hacktoberfest2024-third.github.io
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGame: Hangman
106 lines (94 loc) · 2.43 KB
/
Game: Hangman
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import random
def choose_word():
word_list = ["python", "hangman", "challenge", "programming", "developer", "function", "variable"]
return random.choice(word_list)
def display_hangman(attempts):
stages = [
"""
------
| |
| O
| /|\\
| / \\
|
""",
"""
------
| |
| O
| /|\\
| /
|
""",
"""
------
| |
| O
| /|
|
|
""",
"""
------
| |
| O
|
|
|
""",
"""
------
| |
|
|
|
|
""",
"""
------
|
|
|
|
|
""",
"""
|
|
|
|
|
"""
]
return stages[attempts]
def play_hangman():
print("Welcome to Hangman!")
word_to_guess = choose_word()
guessed_letters = []
attempts = 6
word_completion = "_" * len(word_to_guess)
while attempts > 0 and "_" in word_completion:
print(display_hangman(attempts))
print("Word to guess: ", " ".join(word_completion))
print("Guessed letters: ", " ".join(guessed_letters))
guess = input("Guess a letter: ").lower()
if len(guess) != 1 or not guess.isalpha():
print("Please enter a single valid letter.")
continue
if guess in guessed_letters:
print("You already guessed that letter. Try again.")
continue
guessed_letters.append(guess)
if guess in word_to_guess:
word_completion = "".join([letter if letter == guess or letter in guessed_letters else "_" for letter in word_to_guess])
print("Good job! The letter is in the word.")
else:
attempts -= 1
print("Sorry, that letter is not in the word. You have {} attempts left.".format(attempts))
if "_" not in word_completion:
print(f"Congratulations! You've guessed the word: {word_to_guess}.")
else:
print(display_hangman(attempts))
print(f"Game over! The word was: {word_to_guess}.")
if __name__ == "__main__":
play_hangman()