Welcome folks today in this blog post we will be building a word guessing game
in command line using random
module in python. All the full source code of the application is shown below.
Get Started
In order to get started you need to make an app.py
file and copy paste the following code
app.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 |
from random import randint file = open('words.txt','r') words = file.readlines() length = len(words) def getRandomWord(): random_no = randint(0,length) word = words[random_no].strip() return word def gamePlay(random_word): chances = 7 is_found = False gussed_letters = [] guess = '' print(' '+'_ '*len(random_word)+'\n') while chances>0: guess = input('Guess the letter or the Entire word: ') if guess==random_word: is_found = True else: if guess in gussed_letters : print(f"You have already gussed the letter {guess}..try something else\n") continue print(' ',end='') is_current_guess = False for letter in random_word: if letter == guess : is_current_guess = True gussed_letters.append(letter) print(letter,end=' ') if len(random_word) == len(gussed_letters): is_found = True elif letter in gussed_letters: print(letter,end=' ') else: print('_',end=' ') print() if is_found: print(f"Congrats your guess was correct, the word was '{random_word}'\n") break if not is_current_guess: print(f'{guess} is not in word') chances-=1 print(f'You have {chances} chances remaining\n') if not is_found: print(f"\n Sorry your guesses were wrong, the word was '{random_word}'\n") def main(): print(" Word Guessing Game ".center(60,'-')) while True: random_word = getRandomWord() gamePlay(random_word) choice = input("Do You Wanna Play(yes/no) :") if choice in ['no','No','NO','n','N']: break if __name__ == '__main__': main() |
Now make an words.txt
file inside the root directory and copy paste the following words to it
words.txt
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 97 98 99 100 |
chart arena spite twist crowd front shark spill tempt merit floor still child climb ridge sweat rumor staff whole forge aisle snake guilt brush noble smile drown prove sweet rough shape blind split trial touch reach jewel shame title debut choke stool opera throw peace terms blade cycle exile judge train chalk rider field climb rifle union organ sheep shine album money craft clock pride blast knock close white south motif break smile enfix leave mercy split crown shelf learn funny Koran trend first aloof guilt draft beard troop watch X-ray proof noble night strap class penny bride space tower |
Now if you execute the python
script by typing the below command
python app.py