-
Notifications
You must be signed in to change notification settings - Fork 1
/
hangman.py
74 lines (59 loc) · 1.72 KB
/
hangman.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
import random
def get_file_len(fl):
"""
Returns the number of lines in a given file.
"""
count = 0
fl.seek(0) # Go to the beginning og the file to be safe
for line in fl:
count += 1
fl.seek(0)
return count
def get_random_word():
"""
Fetches a random word from the wordlist.
"""
f = open('wordfile.txt', 'r')
lines = f.readlines()
length = get_file_len(f)
f.close()
rand = random.randint(0, length)
word = lines[rand].strip() # Remove unwanted new line and space characters
return word
def run(lives=5):
"""
Runs our Hangman game with given lives.
"""
word = get_random_word()
display_word = '*' * len(word)
while '*' in display_word and lives > 0:
print("\nCurrent word: " + display_word)
print(str(lives) + " lives remaining!")
ch = input("Enter a character: ")
for x in range(len(word)):
if ch == word[x]:
display_word = list(display_word)
display_word[x] = ch
display_word = ''.join(display_word)
lives -= 1
if display_word == word:
print("Congratulations! You've won!")
else:
print("You've lost! :(")
if __name__ == '__main__':
print("Welcome to Hangman!")
print("Choose difficulty level for the game:")
print("(1) Low difficulty - 10 lives")
print("(2) Medium difficulty - 5 lives")
print("(3) High difficulty - 3 lives")
dif = int(input("Enter difficulty level: "))
if dif == 1:
run(10)
elif dif == 2:
run(5)
elif dif == 3:
run(3)
else:
print("Invalid entry.")
print("Running game with default difficulty of 5.")
run()