Skip to content

Commit 5c957b2

Browse files
authored
Add files via upload
1 parent aa28c05 commit 5c957b2

File tree

1 file changed

+114
-0
lines changed

1 file changed

+114
-0
lines changed
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
import random
2+
3+
def choose_word():
4+
words = ["python", "hangman", "programming", "developer", "challenge"]
5+
return random.choice(words)
6+
7+
def display_hangman(tries):
8+
stages = [
9+
"""
10+
------
11+
| |
12+
| O
13+
| /|\\
14+
| / \\
15+
|
16+
""",
17+
"""
18+
------
19+
| |
20+
| O
21+
| /|\\
22+
| /
23+
|
24+
""",
25+
"""
26+
------
27+
| |
28+
| O
29+
| /|
30+
|
31+
|
32+
""",
33+
"""
34+
------
35+
| |
36+
| O
37+
| |
38+
|
39+
|
40+
""",
41+
"""
42+
------
43+
| |
44+
| O
45+
|
46+
|
47+
|
48+
""",
49+
"""
50+
------
51+
| |
52+
|
53+
|
54+
|
55+
|
56+
""",
57+
"""
58+
59+
""",
60+
]
61+
return stages[tries]
62+
63+
def play_hangman():
64+
word = choose_word()
65+
word_completion = "_" * len(word)
66+
guessed = False
67+
guessed_letters = []
68+
guessed_words = []
69+
tries = 6
70+
71+
print("Let's play Hangman!")
72+
73+
while not guessed and tries > 0:
74+
print(display_hangman(tries))
75+
print(word_completion)
76+
guess = input("Please guess a letter or word: ").lower()
77+
78+
if len(guess) == 1 and guess.isalpha():
79+
if guess in guessed_letters:
80+
print("You already guessed that letter.")
81+
elif guess not in word:
82+
print("Sorry, that letter is not in the word.")
83+
tries -= 1
84+
guessed_letters.append(guess)
85+
else:
86+
print("Good job! That letter is in the word.")
87+
guessed_letters.append(guess)
88+
word_completion = "".join([guess if letter == guess else word_completion[i] for i, letter in enumerate(word)])
89+
90+
if "_" not in word_completion:
91+
guessed = True
92+
93+
elif len(guess) == len(word) and guess.isalpha():
94+
if guess in guessed_words:
95+
print("You already guessed that word.")
96+
elif guess != word:
97+
print("Sorry, that's not the word.")
98+
tries -= 1
99+
guessed_words.append(guess)
100+
else:
101+
guessed = True
102+
word_completion = word
103+
104+
else:
105+
print("Invalid input. Please try again.")
106+
107+
if guessed:
108+
print(f"Congratulations! You've guessed the word '{word}' correctly!")
109+
else:
110+
print(display_hangman(tries))
111+
print(f"Sorry, you've run out of tries. The word was '{word}'.")
112+
113+
if __name__ == "__main__":
114+
play_hangman()

0 commit comments

Comments
 (0)