-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhangman.py
More file actions
137 lines (120 loc) · 2.45 KB
/
hangman.py
File metadata and controls
137 lines (120 loc) · 2.45 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
# A program to play the classic game of Hangman
# ----------------
# Import libraries
# ----------------
from random_word import RandomWords
import random
import os
# ----------------
# Constants
# ----------------
HANGMAN_PICS = [r'''
-----
|
|
|
|
|
=========''',r'''
-----
| |
|
|
|
|
=========''', r'''
-----
| |
O |
|
|
|
=========''', r'''
-----
| |
O |
| |
|
|
=========''', r'''
-----
| |
O |
/| |
|
|
=========''', r'''
-----
| |
O |
/|\ |
|
|
=========''', r'''
-----
| |
O |
/|\ |
/ |
|
=========''', r'''
-----
| |
O |
/|\ |
/ \ |
|
=========''']
# Once again, converted to raw text to avoid any issues.
# ----------------
# Subprograms
# ----------------
def choose_random_word():
global random_word
r = RandomWords()
random_word = r.get_random_word()
# ----------------
# Main program
# ----------------
choose_random_word()
print("Welcome to Hangman!")
# Create a list of underscores to represent the word
global word_display
word_display = []
for i in range(len(random_word)):
word_display.append("_")
print(' '.join(word_display))
# Create a list to store the letters guessed by the player
global guessed_letters
guessed_letters = []
# Create a variable to store the number of incorrect guesses
global incorrect_guesses
incorrect_guesses = 0
wordGuessed = False
while not wordGuessed:
os.system('cls' if os.name == 'nt' else 'clear')
print(HANGMAN_PICS[incorrect_guesses])
print()
print(' '.join(word_display))
print()
print(f"Guessed letters: {' '.join(guessed_letters)}")
print()
guess = input("Enter a letter: ").lower()
if guess in guessed_letters:
print("You have already guessed that letter.")
continue
guessed_letters.append(guess)
if guess in random_word:
for i in range(len(random_word)):
if random_word[i] == guess:
word_display[i] = guess
print(' '.join(word_display))
else:
incorrect_guesses += 1
print(HANGMAN_PICS[incorrect_guesses - 1])
if "_" not in word_display:
wordGuessed = True
print("Congratulations! You guessed the word!")
elif incorrect_guesses == (len(HANGMAN_PICS) - 1):
wordGuessed = True
print(f"Sorry, you have run out of guesses. The word was {random_word}.")