Who hasn't played Hangman. This famous pen-paper game is quite simple to play and can keep players occupied for hours. A little bit of a changed version of Hangman can be built in Python.
It doesn't have the hanging man picture but gives you 10 chances to guess a random word from a set of words. Using lists and if-statements, this game can be coded faster than playing a round of Hangman.
It doesn't have the hanging man picture but gives you 10 chances to guess a random word from a set of words. Using lists and if-statements, this game can be coded faster than playing a round of Hangman.
Check out the code here:
possible_words = ['Hello','Apple','Level'] import random question = random.choice(possible_words) question = question.lower() wrong_letters = [] right_letters = [] word = ['_ ' for x in range(len(question))] print("Welcome to Hangman\n\nGuess letters and find the word in 10 chances\n\n") while len(wrong_letters) < 10 and '_ ' in word: print('Word: ') for x in word: print(x,end='') inp = input("\nEnter letter: ") inp = inp.lower() if len(inp) == 1 and inp.isalpha(): if inp not in wrong_letters and inp not in right_letters: if inp in question: for l in range(len(question)): if question[l] == inp: word[l] = inp right_letters.append(inp) else: wrong_letters.append(inp) print('Letter not in word, You have ',10-len(wrong_letters),' chances remaining') else: print('Letter already tried') else: print('Wrong input') if len(wrong_letters) == 10: print("Sorry, you lost\n\nWord was ",question) else: print('Congratulations, You found the word. Word was ',question)
Some points you need to note here are:
possible_words is the list that contains all possible words from which the computer chooses an random word
right_letters and wrong_letters are to keep count of all letters already played and which of those were right and which of those were wrong
if count of wrong_letters exceeds 10, the computer breaks the while loop and prints a 'You lose' statement
Output:
Welcome to Hangman Guess letters and find the word in 10 chances Word: _ _ _ _ _ Enter letter: L Word: _ _ _ l_ Enter letter: app Wrong input Word: _ _ _ l_ Enter letter: a Word: a_ _ l_ Enter letter: 123 Wrong input Word: a_ _ l_ Enter letter: P Word: appl_ Enter letter: e Congratulations, You found the word. Word was apple >>>
Clearly, the code makes sure all inputs are one-letter inputs and shows the correct word in the end.
This code can be edited to make it better and suited to the users likes.
Here is the final code: Hangman
Make sure to follow the blog to be updated as soon as a post is released. Just click the blue 'follow' button in the menu to follow.
If you want to check out other games: PYTHON GAMES COMPILATION (thepygrammer.blogspot.com) or SIMPLE ANAGRAM SOLVER (thepygrammer.blogspot.com)
Comments
Post a Comment