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

Find the Resultant vector of two Vectors With PYTHON!!

NEW ARTICLE:  How to Find the resultant of multiple vectors with Python! Using Python We can do many complex calculations. I learned how to calculate Resultant Vector using a formula with its size and direction in my Physics class. Then, I simply developed a CLI software to calculate the resultant of given two vectors Hope you like it :>) Follow me... Step :1 You need to install python on your computer. No matter what the operating system is you can find the ideal version of python from the official website of Python org And you will need a code editor like VS code and can download it with a simple Google search. (Hope you hate the first step Haha ) Step 2: we use the math module to calculate our resultant vector. The method I used as follows math.radians() : converts degrees to radians math.degrees() : converts radians to degrees math.sqrt()  : find the square root of a number math.atan() :find the tan inverse Step 3: the formula I used to calculate the size of the resultant is as

How to send and receive discord messages with your bot in 2023.

Hello everyone. Welcome back to the Blog of Chamodh today I will show you how to send and receive discord messages with your bot. Before getting started, I remind you that this is the second episode of the series How to make Discord bot in 2023 and if you haven't read the previous one, please read that first as I explain how to create your bot application and add it to a server there. READ:  https://blogofchamodh.blogspot.com/2023/02/how-to-make-your-own-discord-bot-2023.html We don't gonna use virtual environments, IDEs, or any other utility because we can use Replit for our coding purposes.  Let's Get Started. STEP1: Set up Replit It is really simple. Just go to  https://replit.com/~ and sign up if you have never used its service before and create a new Repl. I don't hope to guide you in this as this is an intermediate tutorial. Make sure to select Python as you create the new Repl because we are going to use Python for our back end. STEP 2: Get your token. To run ou