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...

Generate all possible phone numbers with Python | Generates Crores of Phone Numbers within minutes.

Recently,  I learned about itertools in python. Especially, about the functions permutations, combinations, and products and I tried to make a script that generates all phone numbers in our country. I bet your phone number is too on the list. let the hack begin!!! First, you need to install itertools in your computer  Simply open your terminal and type                sudo apt-get  install  -y python-more- itertools Then Write the code below from itertools import product file_name = "phonebook.txt" phonebook = open (file_name, 'a' ) prefixes = [ '+9471' ] product_a = product([ '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , '0' ], [ '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , '0' ], [ '1' , '2' , '3' , '4' , '5...