This tutorial will show how to create a simple Hangman game using the Python computer programming language. For this tutorial, I will be using PyCharm as the Python IDE but you can use any IDE that you prefer.
The function of this game will be simple. First, when you run the application a quick Dialog will be prompted explaining the rules and instructions of the game. Next, will be the actual function of the game. The player will pick a word and the players will have to guess the word but they will only get Five attempts to guess the word before the Players lose the game.
Hangman Game Code
#Importing the Time module
import time
# Start game and instruction
name = input("What is your name? ")
print("Hello, " + name, "Time to play hangman!")
time.sleep(1)
print("Here are the rules : ")
time.sleep(0.5)
time.sleep(1)
print("You get 5 Attempts ")
time.sleep(0.5)
time.sleep(1)
print("Every time you guess wrong you lose an Attempt")
time.sleep(0.5)
time.sleep(1)
print("Let's Begin!")
time.sleep(0.5)
# Creating the function of the game
# Set word to guess
PlayerWord = input("Choose a word : ")
# Number of guesses place holder
guesses = ("")
# Amount of total Attempts
Attempts = 5
# check if the Attempts are more than zero
while Attempts > 0:
# make a counter that starts with zero
WrongGuessCounter = 0
# for every character in Chosen Word
for char in PlayerWord:
# see if the character is in the players guess
if char in guesses:
# print then out the character
print(char)
else:
# if not found, print a X
print("X")
# and increase the WrongGuessCounter counter with one
WrongGuessCounter += 1
# print You Won
if WrongGuessCounter == 0:
print("You won! Good Guessing")
# exit the script
break
# ask the user go guess a character
guess = input("guess a character:")
# set the players guess to guesses
guesses += guess
# if the guess is not found in the Chosen Word
if guess not in PlayerWord:
# Attempts decreases by 1 for each wrong guess
Attempts -= 1
# print wrong
print("Wrong")
# how many Attempts are left
print("You have", + Attempts, "more guesses")
else:
print("Correct!")
# how many Attempts are left
print("You have", + Attempts, "more guesses")
# if the Attempts reaches Zero the players lose the game
if Attempts == 0:
# print "You Lose"
print("Players Have Lost, Try Again!")
If you are just learning Python, Iv added comments to each line of code to explain its function.