Skip to main content

How to Code a Number Guess Game With Python.

How to Code an Advanced Number Guess Game with Python.


banner of the game by me:)




Hello everyone, I am sure you have played the Number Wordle (Number Guess) Game. Have you ever wanted to create your own number guess game? If yes, this is the time. 

It is a game like a wordle to friends who don't know what a number guess game is. The Computer generates a random number; all you have to do is guess that number. If your guess is correct you are rewarded with some points and granted access to higher levels.

With Python, you can code this very easily, and let's get started. At this level, we will create a CLI game so that you can understand the basics, and let's move to GUI when you are ready.


Prerequisites.


All you need is Python and if you have not installed Python yet, visit https://www.python.org/downloads/ and download the appropriate Python version for you.


Getting Started.


Create an ASCII banner.


First, we want a banner to show the user when they enter the game. It will add a professional look to our game. To create a banner, there are too many online tools but I personally love this one. https://manytools.org/hacker-tools/ascii-banner/

You can simply type your game name and select a font you like. When finished, copy the banner using the button they have provided. then you can store it in a multiline string as shown below.



Code.

Import Libraries.


All you have to import is the random library and you don't have to install it using PIP as it is a built-in library.

Import the random library, using import random

import random

Then we create a class for the number so that we can get the advantage of object-oriented programming.

This is how I created my number Object.

class Number():
    def __init__(self,Level):
        self.level = Level
        self.range = Level*5
        self.number = random.randrange(self.range)

    def reveal(self):
        return self.number
   
    def get_hints(self):
       
        hints = [] # a list that contains all hints

        #1st hint For All Levels

        hints.append("The number is below "+ str(self.range)) # reveals range

        #2nd hint for level 2 or higher
        if self.level >= 2:
            if self.number % 2 == 0:  # Check if number is even
                hints.append("The Number is even")
            else:
                hints.append("The Number is Odd")

        # 3rd hint for level 4 or highr
        if self.level >=4:
            if self.number % 5 == 0:
                hints.append("The Number can be divided by 5")
            else:
                hints.append("The number can't be divided by 5")

        return hints

   


The number object takes one positional argument, Level so that it can generate a random number from different ranges corresponding to the Level of the player.


Generating a random number with Python.

To generate a random number from a specific range, here we use the randrange function from the random library which we imported earlier.

All you have to give a range to the randrange function and it will return a random number for you.

random.randrange(self.range)

And the object has three methods
  1. reveal: To reveal the generated random number 
  2. get_hintts: To give some hints to players to narrow down the range.
That's all and you can add any amount of hints you want. And in my code, you will receive more hints when you reach higher levels


Handling User Inputs.


To handle the game and the inputs we write a small main function and call it. Here is how I created it and I didn't forget to add some comments so that you can understand the code easily.

So don't forget to read the comments as well.



def main():
    print(banner)

    points = 0
    level =1
   
    won = True
    while won:
        number = Number(level)
        number.reveal() # for testing purposes
        for hint in number.get_hints():
            guess = int(input(hint+" input your guess: "))
            if guess == number.number:
                print("You won going to the next level")
                points += 15*level # rewards points for a correct guess
                print("\n You have earned "+str(points)+ " so far!")
                break
            else:
                print("wrong, Try again!")
                points -= 5*level #hints has A  price too ;-)

                won = False # if last trial was not successul breaks the while loop
       
        level +=1
    print("You Lost!")
    print("\nPoints Earned: "+str(points)+"\n")

if you can't view the full code due to the width issues, I'm embedding a GitHub Gist later in this article and you can check it out.

I have applied some point systems to our game so that users can have a real gaming experience on a command line interface. 

So all we have to do now is to call the main function and have fun.

Don't forget to 
remove the number.reveal() # for testing purposes line when you play this game.

Here have a look at the full code



Comments

Trending Now

Let's talk about cryptography.

Have you ever heard of cryptography?  People write their diaries every day. For many of them, their diary is one of their best friends to whom they tell their every secret. What happens when someone else finds such a diary? That would freak out the dairy's owner for sure. Also, it might put their lives in danger. Wise men always hide their diaries so no one else finds it.  But legends hide their message so that only they can read what they wrote. So even if the diary is found by someone else, they cannot know the secrets. for example, I wrote this in my diary today.   P dyval h isvn wvza hivba jyfwavnyhwof avkhf Can you understand it? This is just a very primitive level of cryptography yet powerful enough to hide what I wrote from 90% of people. I will discuss this type of cryptography in the next blog post. The human used cryptography from the very beginning to share their messages in secret and conceal their inventions. As you may know, many people tried to find a recip...

How to reset SUDO password of ubuntu on WSL [STEP BY STEP GUIDE]

Hello everyone, I just found out a super easy way to reset the password of Ubuntu installed on your windows PC. Step 1: Know your username your ubuntu username can be found by various ways. the easiest method is to run the $whoami command on Ubuntu terminal to get your username. Here my username is chamodhk Step 2: Reset the password Now close your Ubuntu terminal and open windows command prompt and run the command  wsl -d Ubuntu -u root now you have logged in as the root of the Ubuntu system and now type the following command. passwd <your_username> in this command replace the <your_username> part with your actual username. In my case, the command is passwd chamodhk That's it. Follow the on-screen instructions to create your new password. Don't forget to leave a comment :) bye.