-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhangman-game-python.py
More file actions
109 lines (94 loc) · 3.09 KB
/
hangman-game-python.py
File metadata and controls
109 lines (94 loc) · 3.09 KB
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
107
108
109
import random
def intro():
print("Hello! What is your name?")
user = input()
print("Nice to meet you, {user}. Let's get ready to play a game of Hangman!")
print("The rules are simple: enter a letter that might be in the secret word.")
print("You can make only six wrong guesses before you lose.")
print("Type 'hint' to reveal one letter of the word.")
print("Let's Begin!")
def display_graphics(attempts):
graphics = [
'''------------
''',
'''------------
| |
''',
'''------------
| |
| O
''',
'''------------
| |
| O
| / |
''',
'''------------
| |
| O
| / |
| |
''',
'''------------
| |
| O
| / |
| |
| / |
| '''
]
# Ensure attempts are within the bounds of the graphics list
index = min(attempts, len(graphics) - 1)
print(graphics[index])
def reveal_hint(word, dashes, used_hints):
available_positions = [i for i in range(len(word)) if dashes[i] == '_']
if available_positions:
position = random.choice(available_positions)
dashes[position] = word[position]
used_hints.add(position)
return dashes
def play_game():
wordlist = ['bee', 'rainbow', 'flamingo', 'science', 'chocolate', 'cables', 'printer', 'blue', 'adventure', 'fountain']
word = random.choice(wordlist)
word = list(word) # Convert word to list of characters
dashes = ['_'] * len(word)
used_hints = set()
print(f"The length of the word is: {len(word)}")
print("Generating secret word! :)")
print(' '.join(dashes))
attempts = 0
guessed_letters = set()
while attempts < 6:
letter = input('Enter a letter you would like to guess or type "hint" for a hint: ').lower()
if letter == 'hint':
if len(used_hints) < len(word):
dashes = reveal_hint(word, dashes, used_hints)
print('Hint revealed!')
print(' '.join(dashes))
else:
print("No hints left to reveal.")
continue
if letter in guessed_letters:
print("You already guessed that letter.")
continue
guessed_letters.add(letter)
if letter in word:
print('YAY! The letter is in the word.')
for index, char in enumerate(word):
if char == letter:
dashes[index] = letter
print(' '.join(dashes))
if '_' not in dashes:
print('Congratulations! You have guessed the word. You win!')
break
else:
print('The letter is not in the word.')
attempts += 1
display_graphics(attempts)
if attempts == 6:
display_graphics(attempts) # Display the final state
print(f'Too many incorrect guesses. You lost! The word was: {"".join(word)}')
break # End the game immediately
print('Goodbye!')
intro()
play_game()