Hangman is a paper and pencil word guessing game for two players. One player (the computer) thinks of a word, phrase, or sentence, and the other tries to figure it out by suggesting letters within a certain number of guesses.
import random
from rich import print
from PyDictionary import PyDictionary
PyDictionary is a Dictionary Module for Python 2/3 to get meanings, translations, synonyms, and antonyms of words.
Title = '''
_
| |
| |__ __ _ _ __ __ _ _ __ ___ __ _ _ __
| '_ \ / _` | '_ \ / _` | '_ ` _ \ / _` | '_ \
| | | | (_| | | | | (_| | | | | | | (_| | | | |
|_| |_|__,_|_| |_|__, |_| |_| |_|__,_|_| |_|
__/ |
|___/
'''
HangmanPictures = ['''
+‐‐-+
| |
|
|
|
|
=========''', '''
+‐‐-+
| |
O |
|
|
|
=========''', '''
+‐‐-+
| |
O |
| |
|
|
=========''', '''
+‐‐-+
| |
O |
/| |
|
|
=========''', '''
+‐‐-+
| |
O |
/|\ |
|
|
=========''', '''
+‐‐-+
| |
O |
/|\ |
/ |
|
=========''', '''
+‐‐-+
| |
O |
/|\ |
/ \ |
|
=========''']
def getRandomWord():
# Select a random word from a text file "words.txt".
word_file = "words.txt"
WORDS = open(word_file).read().splitlines()
myWord = ""
while len(myWord)<7: # It keeps looping until the length of the word is seven or more characters.
myWord = random.choice(WORDS)
return myWord
def displayBoard(missedLetters, correctLetters, secretWord):
# It displays our game's state. Firstly, it display the hangman's image corresponding to the number of lives left. Some of this code is inspired by [Invent with Python](https://inventwithpython.com/).
print(HangmanPictures[len(missedLetters)])
print()
# Secondly, it prints all the wrong guesses.
print('Missed letters:', end=' ')
for letter in missedLetters:
print(letter, end=' ')
print()
blanks = '_' * len(secretWord)
for i in range(len(secretWord)): # It replaces blanks with correctly guessed letters.
if secretWord[i] in correctLetters:
blanks = blanks[:i] + secretWord[i] + blanks[i+1:]
for letter in blanks: # Thirdly, it shows the secret word with spaces in between each letter, the correctly guessed letters are printed in blue.
if letter in correctLetters:
print("[blue]" + letter + "[/blue]", end=' ')
else:
print(letter, end=' ')
print()
def getGuess(secretWord, alreadyTried):
# It returns the letter the player entered through the keyboard. It makes sure the player entered a single letter, and not something else. It also provides a hint to the user about the secret word.
while True:
print('Try to guess a letter or type help.')
guess = input().lower()
if guess == "help": # If the user or player types "help"...
dict = PyDictionary()
print(dict.meaning(secretWord)) # It prints the meaning of the secret word.
elif len(guess) != 1:
print('Please enter a single letter.')
elif guess in alreadyTried:
print('You have already typed that letter. Choose again.')
elif guess not in 'abcdefghijklmnopqrstuvwxyz':
print('Please enter a letter. Words do not contain letters.')
else:
return guess
def playAgain():
# This function asks the player if he wants to play again.
print('Do you want to play again? (yes or no)')
# If he wants to play again, it calls the "main" method where the game's magic happens.
if input().lower().startswith('y'):
main()
def win(secretWord, correctLetters):
# It returns True if the player has won, i.e., he has found all the letters of the "secretWord". Otherwise, it returns False. correctLetters is _a string which contains all the letters that the player has correctly guessed_.
foundAllLetters = True
for i in range(len(secretWord)):
if secretWord[i] not in correctLetters:
foundAllLetters = False
return foundAllLetters
def loose(missedLetters):
# It returns True if the player has lost. Otherwise, it returns False. missedLetters is _a string which contains all the letters that the player has typed but they are not part of the secretWord_. The player run out of lives when len(missedLetters) == len(HangmanPictures) - 1, that is 6.
return len(missedLetters) == len(HangmanPictures) - 1
def update(letter, secretWord, correctLetters, missedLetters):
# It updates our game. letter is the letter typed by the user. It returns True o False depending on whether the user has guessed correctly or not and the two updated strings correctLetters and missedLetters.
if letter in secretWord: # If letter is a correct guess, we add it to correctLetters.
correctLetters = correctLetters + letter
return True, correctLetters, missedLetters
else: # If letter is not a correct guess, we add it to missedLetters.
missedLetters = missedLetters + letter
return False, correctLetters, missedLetters
Observe this code:
def f(myString, myList, mySecondList):
myString += 'e'
myList = [1, 2, 3, 4, 5]
mySecondList.append("lemon") # mySecondList is a list (mutable) and a copy of the pointer is passed to the function so mySecondList.append("lemon") changes the contents of the list.
def main():
myString = 'a b c d'
myList = [1, 2, 3]
mySecondList = ["apple", "banana", "orange"]
f(myString, myList, mySecondList)
print(myString)
print(myList)
print(mySecondList)
if __name__ == "__main__":
main()
The result is: a b c d # It is not a b c d e [1, 2, 3] # It is not 1 2 3 4 5 [‘apple’, ‘banana’, ‘orange’, ’lemon’]
Python doesn’t copy objects you pass during a function call. Function parameters are names. When you call a function, Python binds these parameters to whatever objects you pass (via names in a caller scope). Any time you see varname = … or varname += …, you are creating a new name binding within the function’s scope. Whatever value varname was bound to before is lost within this scope.
def evaluateGame(guess, secretWord, correctLetters, missedLetters):
# It evaluates our game. It returns True if the game is finished. Otherwise, it returns False.
if guess and win(secretWord, correctLetters): # If the user has guessed correctly not just a letter, but the whole secret word...
print('Yes! The secret word is "' + secretWord + '"! You have won!') # ... we congratulate him
return True # ... and return True, in other words, the game is done.
elif not guess and loose(missedLetters): # If the user has failed in his guess and he has run out of lives...
displayBoard(missedLetters, correctLetters, secretWord) #... we display our game's state or board
print(f'You have lost after {str(len(correctLetters))} correct guesses. The word was [yellow]{secretWord}[/yellow].')
return True # ... and return True, in other words, the game is done.
return False # If we are here, the game is not done yet.
def main():
print(Title)
missedLetters = ''
correctLetters = ''
secretWord = getRandomWord()
gameIsDone = False
while not gameIsDone: # It loops while the game is not done.
# 1. It displays the board or state of the game.
displayBoard(missedLetters, correctLetters, secretWord)
# 2. We let the user to type or introduce a letter.
letter = getGuess(secretWord, missedLetters + correctLetters)
# 3. It updates the game's state.
guess, correctLetters, missedLetters = update(letter, secretWord, correctLetters, missedLetters)
# 4. It evaluates the game's state.
gameIsDone = evaluateGame(guess, secretWord, correctLetters, missedLetters)
# If the game is done, we ask the player if he wants to play again.
if gameIsDone:
playAgain()
if __name__ == '__main__':
main()
Rock paper scissors is a hand game in which each player simultaneously forms one of three shapes with an outstretched hand. These shapes are “rock” (a closed fist), “paper” (a flat hand), and “scissors” (a fist with the index finger and middle finger extended).
It has three possible outcomes: a draw, a win, or a loss. A player who decides to play rock will beat another player who has chosen scissors (“rock crushes scissors”) but will lose to one who has played paper (“paper covers rock”). A player who decides to play paper will lose to a play of scissors (“scissors cuts paper”). If both players choose the same shape, the game is tied.
import random
from rich import print
Title = '''
_____ _
| __ \ | |
| |__) |___ ___| | __ _ __ __ _ _ __ ___ _ __
| _ // _ \ / __| |/ / | '_ \ / _` | '_ \ / _ \ '__|
| | \ \ (_) | (__| < | |_) | (_| | |_) | __/ |
|_| ____/ ___|_|_\ | ./ __,_| ./ ___|_|
| | | |
|_| |_|
'''
pictures = ['''
_______
‐‐-' ____)
(_____)
(_____)
(____)
‐‐-.(___)
''', '''
_______
‐‐-' ____)____
______)
_______)
_______)
‐‐-.________)
''', '''
_______
‐‐-' ____)____
______)
__________)
(____)
‐‐-.(___)
''']
def getUserInput():
# It prints the rules of the game and asks the user to introduce its choice.
print("Rules of the Rock paper scissor game are as follows: \n" + "Rock vs paper -> Paper covers rock! Paper wins. \n" + "Rock vs scissor -> Rock smashes scissors! Rock wins. \n" + "Paper vs scissor -> Scissors cuts paper! Scissors wins. \n")
correctEntry = False
while not correctEntry:
userInput = input("Enter a choice: rock (1), paper (2), scissors (3): ")
if userInput == "1" or userInput.lower().startswith('r'):
choice = 'rock'
correctEntry = True
elif userInput == "2" or userInput.lower().startswith('p'):
choice = 'paper'
correctEntry = True
elif userInput == "3" or userInput.lower().startswith('s'):
choice = 'scissor'
correctEntry = True
return choice
def evaluateGame(user, computer):
# It evaluates the game and prints the result.
if user == computer:
print(f"Both players selected {user}. It's a tie!")
elif user == "rock":
if computer == "scissors":
print("[red]Rock smashes scissors![/red] You win!")
else:
print("[red]Paper covers rock![/red] You lose.")
elif user == "paper":
if computer == "rock":
print("[red]Paper covers rock![/red] You win!")
else:
print("[red]Scissors cuts paper![/red] You lose.")
elif user == "scissors":
if computer == "paper":
print("[red]Scissors cuts paper![/red] You win!")
else:
print("[red]Rock smashes scissors![/red] You lose.")
def playAgain():
# This function asks the player if he wants to play again.
print('Do you want to play again? (yes or no)')
# If he wants to play again, it calls the "main" method where the game's magic happens.
if input().lower().startswith('y'):
main()
def drawGame(user, computer):
# It prints and draws the game's state. In other words, it prints and draws what choices the player and computer are playing.
print(f"\nUser choice {user}. Computer choice {computer}.\n")
userPicture = ["rock", "paper", "scissors"].index(user)
computerPicture = ["rock", "paper", "scissors"].index(computer)
print(pictures[userPicture])
print(pictures[computerPicture])
def main():
user = getUserInput() # Firstly, it gets the user input.
actions = ["rock", "paper", "scissors"]
computer = random.choice(actions) # Secondly, the computer selects randomly one of the three options of the game.
drawGame(user, computer) # Thirdly, it draws the game's state.
evaluateGame(user, computer) # Fourthly, it evaluates the game.
playAgain() # Finally, it asks the user if the wants to play the game again.
if __name__ == '__main__':
main()
Let’s start by creating a number guessing game in Python. The code is quite simple and self-explanatory.
import random
n = random.randint(1, 99)
lives = 7
notFound = True
while lives>0 and notFound:
guess = int(input(f"Enter an integer from 1 to 99. You have {lives} lives: "))
lives -= 1
if guess < n:
print("Your guess is too low")
elif guess > n:
print("Your guess is too high")
else:
print("You got it")
notFound = False
if lives==0:
print("Your have run out of lives")
Obviously, we can do much, much better. Let’s program a number guessing game in Python with three levels.
import random
# It generates and returns a secret number, the number of lives, and the number of digits.
def getSecretNum(level):
numDigits = 3
if level==1:
# It returns a random number between 1 and 99, 7 lives, and counts the number of digits in the secret number.
secretNum = random.randint(1, 99)
lives = 7
numDigits = len(str(secretNum))
elif level==2 or level==3:
lives = level*3 + 1
numbers = list('0123456789') # It creates a list of digits from 0 to 9.
random.shuffle(numbers) # It shuffles the list to get all digits in random order.
# It gets the first three digits in the list for the secret number.
secretNum = ''
for i in range(3):
secretNum += str(numbers[I])
return secretNum, lives, numDigits
def readInput(numDigits):
# It read the user's input.
guess = ''
# It checks that the user has introduced a number of numDigits digits.
while len(guess) != numDigits or not guess.isdecimal():
guess = input(f'Enter a {numDigits} digits number: ')
return guess
def getClues(level, guess, secretNum):
# It returns a string with the clues based on the user's guess
if level==1:
if int(guess) < secretNum:
clues = 'Your guess is too low'
elif int(guess) > secretNum:
clues = 'Your guess is too high'
else:
clues = 'You got it!'
elif level==2:
if guess == secretNum:
return 'You got it!'
clues = []
for i in range(len(guess)):
if guess[i] == secretNum[i]:
# A Fermi means the digit is correct and it is in the correct location.
clues.append('Fermi')
elif guess[i] in secretNum:
# A Pico means the digit is correct, but it is in the wrong spot.
clues.append('Pico')
# A Bagel means the digit is not correct - it is not in the answer at all.
else:
clues.append('Bagels')
else: # level is 3
if guess == secretNum:
return 'You got it!'
clues = []
for i in range(len(guess)):
if guess[i] == secretNum[i]:
# A Fermi means one digit is correct and it is in the correct position.
clues.append('Fermi')
elif guess[i] in secretNum:
# A Pico means one digit is correct, but it is in the wrong spot.
clues.append('Pico')
# A Bagel means all digits are incorrect.
if len(clues) == 0:
return "Bagels"
else:
# Shuffle the clues and join them into a single string
random.shuffle(clues)
clues = ' '.join(clues)
return clues
def main():
print('''Guess Number.
‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
Level 1. Guess a number from 1 to 99. I will tell you if each guess is too high or too low. You have 7 lives.
‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
Level 2. Bagels. Guess a 3 digit number with no repeated digits. I will tell you a 3 letter code, each letter refers to its corresponding number.
A Bagel means the digit is not correct - it is not in the answer at all.
A Pico means the digit is correct, but it is in the wrong spot.
A Fermi means the digit is correct and it is in the correct location.
For example, if the secret number was 431 and your guess was 541, the
clues would be Bagel Pico Fermi.
‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
Level 3. Bagels+, guess a 3 digit number with no repeated digits. I will tell you the following code:
A Bagel means all digits are incorrect.
A Pico means one digit is correct, but it is in the wrong spot.
A Fermi means one digit is correct and it is in the correct location.
For example, if the secret number was 432 and your guess was 541, the
clues would be Pico.''')
level = int(input('What is your desired level? '))
secretNum, maxGuesses, numDigits = getSecretNum(level)
print('I am thinking of a number.')
print(f'You have {maxGuesses} guesses to get it.')
numGuesses = 1
while numGuesses <= maxGuesses: # As long as the user has not run out of lives.
guess = readInput(numDigits) # It reads the user's input.
clues = getClues(level, guess, secretNum) # It returns a string with the clues based on the user's guess.
print(clues) # It prints the clues.
numGuesses += 1
if clues == 'You got it!':
break # The user is correct, so it breaks the loop.
elif numGuesses > maxGuesses:
print('You ran out of guesses.')
print('The answer was {}'.format(secretNum))
break
if __name__ == '__main__':
main()
Guess Number.
‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
Level 1. Guess a number from 1 to 99. I will tell you if each guess is too high or too low. You have 7 lives.
‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
Level 2. Bagels. Guess a 3 digit number with no repeated digits. I will tell you a 3 letter code, each letter refers to its corresponding number. A Bagel means the digit is not correct - it is not in the answer at all. A Pico means the digit is correct, but it is in the wrong spot. A Fermi means the digit is correct and it is in the correct location. For example, if the secret number was 431 and your guess was 541, the clues would be Bagel Pico Fermi.
‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
Level 3. Bagels+, guess a 3 digit number with no repeated digits. I will tell you the following code: A Bagel means all digits are incorrect. A Pico means one digit is correct, but it is in the wrong spot. A Fermi means one digit is correct and it is in the correct location. For example, if the secret number was 432 and your guess was 541, the clues would be Pico.
What is your desired level? 2 I am thinking of a number. You have 7 guesses to get it. \ Enter a 3 digits number: 012 [‘Bagels’, ‘Bagels’, ‘Bagels’]
Enter a 3 digits number: 345 [‘Bagels’, ‘Bagels’, ‘Pico’]
Enter a 3 digits number: 678 [‘Pico’, ‘Bagels’, ‘Fermi’]
Enter a 3 digits number: 468 [‘Bagels’, ‘Fermi’, ‘Fermi’]
Enter a 3 digits number: 548 [‘Fermi’, ‘Bagels’, ‘Fermi’]
Enter a 3 digits number: 568 You got it!