-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMIT Hangman Puzzle (Full).py
96 lines (85 loc) · 2.82 KB
/
MIT Hangman Puzzle (Full).py
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
# -*- coding: utf-8 -*-
"""Python 102 - Unpacked "hangman.py"
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1ehgkzLFe8kMFJn6u2Zm4LKSmgnGHUTx5
"""
import random
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
print("Loading word list from file...")
inFile = open(WORDLIST_FILENAME, 'r')
line = inFile.readline()
wordlist = line.split()
print(" ", len(wordlist), "words loaded.")
return wordlist
def choose_word(wordlist):
return random.choice(wordlist)
wordlist = load_words()
def get_guessed_word(secret_word, letters_guessed):
guess = ''
for ch in secret_word:
if ch in letters_guessed:
guess = guess + ch
else:
guess = guess + '_ '
return guess
def get_available_letters(letters_guessed):
alphabet = string.ascii_lowercase
alpha = ''
for letter in alphabet:
if letter not in letters_guessed:
alpha = alpha + letter
return alpha
def hangman():
secret_word = choose_word(wordlist)
complete = False
word = []
for ch in secret_word:
if ch not in word:
word.append(ch)
num_guesses = len(word) + 4
print("Hello! Your word is", len(secret_word),"characters long.")
print("For this word, you will only need",num_guesses,"guesses.")
warnings = 3
letters_guessed = []
while (num_guesses > 0):
print(" ")
print("#################################################")
print("Your possible guesses are", get_available_letters(letters_guessed))
print("You have",num_guesses, "guesses left")
guess = input("Enter your guess here: ")
if (guess not in string.ascii_lowercase) or (len(guess) > 1) or (guess in letters_guessed):
if (guess not in string.ascii_lowercase):
print("Invalid character, Try again!")
elif (len(guess) > 1):
print("Your guess should be only one character, Try again!")
elif (guess in letters_guessed):
print("Wait, didn't you already try that?")
warnings = warnings - 1
if warnings > 0:
print("You have", warnings,"warnings left.")
else:
print("You have 0 warnings left. You lost a guess.")
num_guesses = num_guesses - 1
continue
letters_guessed.append(guess)
print("Your guess:", get_guessed_word(secret_word, letters_guessed))
if guess in secret_word:
print("You're getting there.")
else:
print("That isn't it.")
if guess in "aeiou":
num_guesses = num_guesses - 2
else:
num_guesses = num_guesses - 1
if '_ ' not in get_guessed_word(secret_word, letters_guessed):
print("You did it!")
complete = True
break
if complete == False:
print("Well you tried.")
print("The word was", secret_word, ".")
print("Your score was", len(word) * num_guesses, ".")
hangman()