Create a Number Guessing Game in Python

number guessing game in python

Introduction

Python is a versatile and beginner-friendly programming language that can be used to create a wide range of applications. One fun and educational project for beginners is creating a number guessing game. In this article, we will walk you through the process of building a simple number guessing game in Python. We’ll develop both a graphical user interface (GUI) and a command-line interface (CLI) version for this game.

Game Overview

The number-guessing game we’ll create will work like this:

  1. The computer will choose a random number from a specified range.
  2. The player will have to guess the chosen number.
  3. The computer will provide feedback on whether the guess is too high or too low.
  4. The player continues guessing until they correctly guess the number.

Setting Up the Environment

Before we start, make sure you have Python installed on your computer. You can download and install Python from the official website (https://www.python.org/downloads/). We’ll also be using a code editor (e.g., Visual Studio Code, PyCharm, or even a plain text editor) to write and run our Python code.

Once you have Python installed, you can install PyAutoGUI using pip:

pip install PyAutoGUI

What is PyAutoGUI?

PyAutoGUI is a Python module that provides functions for programmatically controlling the mouse and keyboard. It allows you to automate tasks such as opening applications, typing text, and moving the mouse pointer. It’s a handy tool for creating simple automation scripts and, in our case, building a graphical game.

GUI Version of the Game

Now, let’s write the code for our number-guessing game.

import random
import pyautogui

# Initialize variables
lower = 1
upper = 100
attempts = 0
chances_left = 10

# Generate a random number between 1 and 100
target = random.randint(lower, upper)

# Initialize the PyAutoGUI screen
pyautogui.alert("Welcome to the Number Guessing Game!")

# Get the player's name
player_name = pyautogui.prompt("Enter your name:")

# Explain the rules
pyautogui.alert(f"Hello, {player_name}! 
I'm thinking of a number between 1 and 100. 
Try to guess it. You've only 10 chances.")

# Game Loop
while attempts < 10:
    attempts += 1
    
    guess = pyautogui.prompt(f"Chances left: {chances_left}nPlease guess the number.")

    # Checks if the guess matches with the target number
    # Convert the guess variable to an integer
    if int(guess) == target:
        pyautogui.alert(f"Congratulations,
        {player_name}! You guessed the number {target} in {attempts} attempts.")
        break
    elif int(guess) < target:
        pyautogui.alert(f"Too low! Try again.")
    elif int(guess) > target:
        pyautogui.alert(f"Too High! Try again.")

    chances_left -= 1

if attempts >= 10:
        pyautogui.alert(f"Sorry! you have lost.nThe number is: {target}.")

# End the game
pyautogui.alert("Thanks for playing! Goodbye.")

In this code, we start by importing the necessary modules and generating a random number as the secret number. PyAutoGUI is then used to display dialogs to the player, get their name, and explain the rules.

We enter a game loop where the player is prompted to guess the number. Depending on their guess, they receive feedback through PyAutoGUI alerts until they guess the correct number. Once they do, a congratulatory message is displayed along with the number of attempts.

Running the Game

Save the code to a Python file (e.g., `number_guessing_game_gui.py`) and run it using a Python interpreter. The game will display a series of dialogs and allow the player to interact with it using PyAutoGUI.

Output

Output

CLI Version of the Game

Let’s create the CLI (command-line interface) Version of the Number Guessing Game.

import random

# Initialize variables
lower = 1
upper = 100
attempts = 0
chances_left = 10

# Generate a random number between 1 and 100
target = random.randint(lower, upper)

# Explain the rules
print("Please Guess the number between 
1 and 100.nYou've only 10 chances.")

# Game Loop
while attempts < 10:
    attempts += 1

    guesses = int(input(f"nChances left: {chances_left}nPlease guess the number: "))

    if int(guesses) == target:
        print(f"nCongratulations! You guessed the number {target} in {attempts} attempts.")
        break
    elif int(guesses) < target:
        print(f"nToo low! Try again.")
    elif int(guesses) > target:
        print(f"nToo High! Try again.")

    chances_left -= 1

if attempts >= 10:
        print(f"nSorry! You have lost.nThe number is: {target}.")

The game’s underlying logic remains exactly unchanged from the previous version, with the key difference being that in this instance, players have the option to engage with it through a command-line interface.

Running the Game

Save the code to a Python file (e.g., `number_guessing_game_cli.py`) and run it code editor or the command line. The game will start, and the player can begin guessing the secret number.

Output

Please Guess the number between 1 and 100.
You've only 10 chances.

Chances left: 10
Please guess the number: 55

Too High! Try again.

Chances left: 9
Please guess the number: 45

Too High! Try again.

Chances left: 8
Please guess the number: 35

Congratulations! You guessed the number 35 in 3 attempts.

Summary

Creating a number guessing game in Python is an excellent way to practice your programming skills and have some fun in the process. What sets this article apart is its dual approach, teaching readers how to build both Graphical User Interface (GUI) and Command Line Interface (CLI) versions of the game.

The first part of the article focuses on the Graphical User Interface (GUI) version of the game. Here, we introduce PyAutoGUI, a powerful Python library for automating graphical interactions. You’ll discover how to leverage PyAutoGUI to design an engaging GUI for the Number Guessing Game.

The second part of the article focuses on building the Command Line Interface (CLI) version of the Number Guessing Game. You’ll learn how to generate random numbers, create loops for user interactions, and provide feedback based on the player’s guesses.

By the end of the article, you’ll have a strong understanding of game development in Python and the ability to create two distinct versions of the Number Guessing Game. You can further enhance the game by adding features such as difficulty levels or a high score system. 

Happy coding!

Share your love
Subhankar Rakshit
Subhankar Rakshit

Hey there! I’m Subhankar Rakshit, the brains behind PySeek. I’m a Post Graduate in Computer Science. PySeek is where I channel my love for Python programming and share it with the world through engaging and informative blogs.

Articles: 147

Leave a Reply

Your email address will not be published. Required fields are marked *