Skip to content

Commit da0de4f

Browse files
authored
Merge pull request #30 from ChathuminaVimukthi/add-ChathuminaVimukthi
Added hangman game in python
2 parents 16dc4ea + 79a3f82 commit da0de4f

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

Diff for: Hangman/code.py

+76
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
import random
2+
3+
def pick_random_word():
4+
"""
5+
This function picks a random word from the SOWPODS
6+
dictionary.
7+
"""
8+
# open the sowpods dictionary
9+
with open("sowpods.txt", 'r') as f:
10+
words = f.readlines()
11+
12+
# generate a random index
13+
# -1 because len(words) is not a valid index into the list `words`
14+
index = random.randint(0, len(words) - 1)
15+
16+
# print out the word at that index
17+
word = words[index].strip()
18+
return word
19+
20+
21+
def ask_user_for_next_letter():
22+
letter = input("Guess your letter: ")
23+
return letter.strip().upper()
24+
25+
26+
def generate_word_string(word, letters_guessed):
27+
output = []
28+
for letter in word:
29+
if letter in letters_guessed:
30+
output.append(letter.upper())
31+
else:
32+
output.append("_")
33+
return " ".join(output)
34+
35+
36+
if __name__ == '__main__':
37+
WORD = pick_random_word()
38+
39+
letters_to_guess = set(WORD)
40+
correct_letters_guessed = set()
41+
incorrect_letters_guessed = set()
42+
num_guesses = 0
43+
44+
print("Welcome to Hangman!")
45+
while (len(letters_to_guess) > 0) and num_guesses < 6:
46+
guess = ask_user_for_next_letter()
47+
48+
# check if we already guessed that
49+
# letter
50+
if guess in correct_letters_guessed or \
51+
guess in incorrect_letters_guessed:
52+
# print out a message
53+
print("You already guessed that letter.")
54+
continue
55+
56+
# if the guess was correct
57+
if guess in letters_to_guess:
58+
# update the letters_to_guess
59+
letters_to_guess.remove(guess)
60+
# update the correct letters guessed
61+
correct_letters_guessed.add(guess)
62+
else:
63+
incorrect_letters_guessed.add(guess)
64+
# only update the number of guesses
65+
# if you guess incorrectly
66+
num_guesses += 1
67+
68+
word_string = generate_word_string(WORD, correct_letters_guessed)
69+
print(word_string)
70+
print("You have {} guesses left".format(6 - num_guesses))
71+
72+
# tell the user they have won or lost
73+
if num_guesses < 6:
74+
print("Congratulations! You correctly guessed the word {}".format(WORD))
75+
else:
76+
print("Sorry, you list! Your word was {}".format(WORD))

0 commit comments

Comments
 (0)