-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhangman.py
More file actions
79 lines (67 loc) · 2.3 KB
/
hangman.py
File metadata and controls
79 lines (67 loc) · 2.3 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
import os
import sys
import random
with open('eggs/word_list.txt','r') as f: # (filepath/word_list.txt)
word_list = [word.strip() for word in f.readlines()]
word = random.choice(word_list)
def choose_word(word_list):
return random.choice(word_list)
def display_word(word, guessed_letters):
display = ""
for letter in word:
if letter in guessed_letters:
display += letter
else:
display += "_"
return display
# Function to get a letter from the user
def get_letter():
letter = input("\nGuess a letter: ").lower()
if not letter.isalpha() or len(letter) != 1:
print("Invalid input! Please enter a single letter.")
return get_letter()
else:
return letter
# Function to play the game
def play_game():
word = choose_word(word_list)
guessed_letters = set()
attempts = 6
print("The word you need to guess has", len(word), "letters.")
while attempts > 0:
display = display_word(word, guessed_letters)
print(display)
if "_" not in display:
print("You got it! Awesome.")
return
letter = get_letter()
if letter in guessed_letters:
print("You already guessed that letter. You still have",attempts, "attempts left.")
elif letter in word:
guessed_letters.add(letter)
print("Good guess! You still have",attempts, "attempts left.")
else:
attempts -= 1
guessed_letters.add(letter)
print("Sorry, that letter is not in the word. You only have",attempts, "attempts left")
print(f"\nYou ran out of attempts. The correct answer is {word}.")
def main():
os.system('cls' if os.name == 'nt' else 'clear')
app_name = 'The Hangman'
app_name = 'Guess the number v2'
print(f'{"-" * 48}')
print(f'{" " * 12}{app_name}{" " * 12}')
print(f'{"-" * 48}')
play_game()
while True:
response = input('\nDo you want to continue? (Y/N)')
if response == 'y' or response == 'Y':
main()
elif response == 'n' or response == 'N':
print('\nThank you and have a great day.\n')
sys.exit()
else:
print('\nError: Please select y or n.\n')
continue
if __name__ == '__main__':
main()