The Code Behind a Simple Guess the Number Game

Zara Waseem
3 min readNov 25, 2023

Recently, for a project, I created a easy Guess the Number game on Replit using Python. Join me as I share the story of this coding escapade, unveiling the simple layers of code that brought the game to life.

Setting the Stage: Introduction and Difficulty Selection

At the beginning of our code, we set the stage for the game. The random module is imported to introduce unpredictability into the game. The guess_the_number() function, the backbone of the game, is introduced.

import random

def guess_the_number():

Welcome Message and Difficulty Selection

Players are welcomed with a friendly message, and the available difficulty levels are presented. The player then inputs their preferred difficulty level, a crucial step that influences the challenge they will face.

   # Display game introduction and difficulty options
print("Welcome to Advanced Guess the Number!")
print("Choose a difficulty level:")
print("1. Easy (1-10)")
print("2. Medium (1-50)")
print("3. Hard (1-100)")
# Get user input for difficulty
difficulty = int(input("Enter the number for your chosen difficulty: "))

User Input and Secret Number Generation

Upon receiving the player’s difficulty choice, the code generates a secret number using the random module. The range of this secret number is determined by the selected difficulty level, ensuring that each game experience is unique.

   # Generate a secret number based on the chosen difficulty
if difficulty == 1:
secret_number = random.randint(1, 10)
elif difficulty == 2:
secret_number = random.randint(1, 50)
elif difficulty == 3:
secret_number = random.randint(1, 100)
else:
print("Invalid difficulty level. Exiting the game.")
return

The Heart of the Game: The Game Loop

The essence of the game lies in the main loop, where the player repeatedly inputs guesses until they either guess correctly or choose to exit. The code captures each guess and increments the attempts counter.

# Main game loop
while True:
# Get user's guess
guess = int(input("Take a guess: "))
attempts += 1

Scoring System

In the game I have also intergrated a scoring system. Players start with a score of 100, and points are deducted for each incorrect guess. This dynamic scoring system not only makes the game more challenging but also introduces an element of strategy as players aim to achieve the highest score possible.

With each guess, immediate responses is given to the user. If a guess is too low, the system gently chimes, “Too low! Try again. ” Conversely, a lofty guess elicits, “Too high! Try again.” This allows the user to narrow down the possibilities and try predicting and getting the correct number

 score = 100  # Starting score
attempts = 0

while True:
guess = int(input("Take a guess: "))
attempts += 1

if guess < secret_number:
print("Too low! Try again.")
elif guess > secret_number:
print("Too high! Try again.")
else:
print(f"Congratulations! You guessed the number in {attempts} attempts.")
print(f"Your score is: {score}")
break

# Penalize the score for each attempt
score -= 10

Replay Option

After a game concludes, players have the option to replay. The code seamlessly transitions to a new game or exits gracefully based on the player’s choice. Otherwise if the user wished to stop playing a messages pops up, saying “Thanks for playing”.

    replay = input("Do you want to play again? (yes/no): ").lower()
if replay == 'yes':
guess_the_number()
else:
print("Thanks for playing!")

This game is super simple to build and doesn’t take much time. I built my game using Python on Replit and this is the link to the game: https://replit.com/@zaraw0305/Number-Game If you would like you can go in and fork the code and make a game more to your pleasing. This was just a small project for me as I start learning to code. Happy coding!

--

--