In this tutorial on game development, we are focusing on how to create a word guessing game in Python. The objective of this game is pretty simple users just have to guess the word that is stored in our database. Creating a word guessing game is not that hard to learn how to create a word guessing game in python you just need the basic knowledge of Python and it’s a nice game project to include in your portfolio.

How the code will work?

  1. We will be using a list of words as our database and one word will be chosen randomly from our database to guess by the user.
  2. The user will be asked to guess a letter in the randomly chosen word if the randomly chosen word contains that letter then it will be shown as output else the program will let the user know they were wrong.
  3. The user will have a limited amount of terns to guess every letter in the word if the user gets every letter in the word and in the allotted turns then the user wins the game else the user loses.

Basic requirements to create the guessing game:

Random module:

Python random module is an in-built module of Python which is used to generate random numbers. These are pseudo-random numbers as these are not truly random. It has a function called randint() which consists of two main arguments; one is the lowest number and the other one is the largest number that we want our random number to be generated between. This module can be used to perform random actions such as generating random numbers, printing random values for a list or string, etc.

Step -1: List of words that can be accepted

Importing the required library

import random

Creating a list of words in which the user has to guess the correct word.

words = ['kindly', 'recite', 'repeat', 'tree', 'display', 'geeks', 'coader', 'programmer', 'python', 'premium', 'watch']

Randomly choose one of the listed words and if you want you can also show the word.

word = random.choice(words)
#print (word)

Step -2: Adding blank spaces

Creating a line of underscores to represent character spaces, one for each character in the randomly chosen word, is a simple yet smart method to show how many characters are in the word.

spaces = ['_']* len(word)
#show spaces
Spaces

Here we are creating a function to do the following things

  1.  Find all of the letter positions from the user’s guess (some character).
  2.  If the letter exists in the word then the function will replace the underscores in spaces with the correct letters in that position.
def get_letter_position(guess, word, spaces):
    # Create and set a variable called index to be -2
    index = -2
    # create a loop to continue to look through the word for every single position where that letter exists
    while index != -1:
        #check if the character/guess is in word, it then removes the character from the word and add it to spaces
        if guess in word:
            index = word.find(guess)
            #remove that letter from the word
            # this is the special character that will let us know that the        character is removed from the word
            removed_character ='*'
            word = word[:index]+removed_character+word[index+1:]
            spaces[index] = guess
        else:
            index = -1
       
    return (word, spaces)

Creating a function to check if the user guessed all of the letters in the word (“1=Yes” mean they did guess all of the letters in the word, “-1=No” saying that the user did not get all of the letters in the word)

Step -3: Validating user input

def win_check():
    for i in range(0, len(spaces)):
        if spaces[i] == '_':
            return -1
    return 1 

Step -4: Creating the UI

Designing the Game and developing the UI part.

#choose some number of turns for the user to guess the word
num_turns = len(word)
for i in range(0, num_turns):
    #ask the user to guess a character
    guess = input('Guess a character:')
   
    if guess in word:
        word, spaces = get_letter_position(guess, word, spaces)
        print(spaces)
    else:
        print('Sorry that letter is not in the word.')
       
    #check if the player guess the word
    if win_check() == 1:
        print('Congratulations you won')
        break
       
    print('you have'+str(num_turns - i)+' turns left.')
    print()

Output:

Guess a character:e
['_', '_', 'e', 'e']
you have 9 turns left.
you have 5 turns left.

Guess a character:n
['k', 'i', 'n', 'd', '_', '_']
you have 4 turns left.

Guess a character:y
['k', 'i', 'n', 'd', '_', 'y']
you have 3 turns left.

Guess a character:l
['k', 'i', 'n', 'd', 'l', 'y']
Congratulations you won

This is how your code should look:

import random

words = ['kindly', 'recite', 'repeat', 'tree', 'display', 'geeks', 'coader', 'programmer', 'python', 'premium', 'watch']

word = random.choice(words)

spaces = ['_']* len(word)

def get_letter_position(guess, word, spaces):
    index = -2
    while index != -1:
        if guess in word:
            index = word.find(guess)
            removed_character ='*'
            word = word[:index]+removed_character+word[index+1:]
            spaces[index] = guess
        else:
            index = -1
     
    return (word, spaces)


def win_check():
    for i in range(0, len(spaces)):
        if spaces[i] == '_':
            return -1
     
    return 1

num_turns = len(word)
for i in range(-1, num_turns):
    guess = input('Guess a character:')
 
    if guess in word:
        word, spaces = get_letter_position(guess, word, spaces)
        print(spaces)
    else:
        print('Sorry that letter is not in the word.')
     
    if win_check() == 1:
        print('Congratulations you won')
        break
     
    print('you have '+str(num_turns - i)+' turns left.')
    print()

Output:

Final words

In this blog post, we learned How to create a word guessing game in python. This program is meant to be a fun and easy learning project to help you get started with coding. Here we created a game that will ask the user to guess a word and then the user will have to guess the word that the computer is thinking of (using the random module). If the user is able to guess the word correctly, the user will be rewarded with a ‘Congratulations you won’ message. If you have any queries, feel free to comment in the comment section below.

Here are some useful tutorials that you can read: