Skip to content

Commit 94b1c63

Browse files
feat: add Hangman CLI Project (#10)
1 parent cef5c7d commit 94b1c63

File tree

5 files changed

+6890
-0
lines changed

5 files changed

+6890
-0
lines changed

Hangman-CLI/Hangman1.png

32.8 KB
Loading

Hangman-CLI/Hangman2.png

29.7 KB
Loading

Hangman-CLI/game.py

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
import random
2+
3+
def getWord():
4+
with open('nounlist.txt') as f:
5+
wordList=[line.strip() for line in f]
6+
f.close()
7+
word=random.choice(wordList)
8+
return word.lower()
9+
10+
def game(word):
11+
number_of_guesses=8
12+
guessed=False
13+
guessed_letters=[]
14+
guessed_words=[]
15+
completed_word='_'*len(word)
16+
17+
print(completed_word)
18+
print('Hint: Number of letters={}'.format(len(word)))
19+
20+
while guessed!=True and number_of_guesses>0:
21+
print('Guess a Letter.\n')
22+
ch_guess=input().lower()
23+
24+
if len(ch_guess)==1 and ch_guess.isalpha():
25+
if ch_guess in guessed_letters:
26+
print('Already guessed this letter.')
27+
elif ch_guess not in word:
28+
print('Incorrect Guess.')
29+
number_of_guesses-=1
30+
guessed_letters.append(ch_guess)
31+
else:
32+
print('Right Guess.')
33+
guessed_letters.append(ch_guess)
34+
completed_word_list = list(completed_word)
35+
index_list=[i for i,alpha in enumerate(word) if alpha==ch_guess]
36+
for i in index_list:
37+
completed_word_list[i]= ch_guess
38+
completed_word=''.join(completed_word_list)
39+
40+
if '_' not in completed_word:
41+
guessed=True
42+
43+
elif len(ch_guess)==len(word) and ch_guess.isalpha():
44+
if ch_guess in guessed_words:
45+
print('You already guessed this word,Try Again.')
46+
elif ch_guess!=word:
47+
print('Incorrect Guess')
48+
number_of_guesses-=1
49+
guessed_words.append(ch_guess)
50+
else:
51+
guessed=True
52+
completed_word=word
53+
else:
54+
('Ehh.Incorrect Guess')
55+
print(completed_word)
56+
print('Number of guesses remaining: {}'.format(number_of_guesses))
57+
58+
print('\n')
59+
if guessed:
60+
print('You Win.You Have guessed the word.')
61+
else:
62+
print("You Lost.You Couldn't guess the word.\n The word was {}".format(word))
63+
64+
if __name__ =='__main__':
65+
print('********Lets Play Hangman********')
66+
word=getWord()
67+
game(word)
68+
ch='y'
69+
while ch!='n':
70+
ch=input('\nWanna play again?(Y/N)').lower()
71+
if ch=='y':
72+
word=getWord()
73+
game(word)
74+
else:
75+
print('Thank you for playing')
76+
77+

0 commit comments

Comments
 (0)