w3resource

Number Guessing Game with GUI in Python


Number Guessing Game with GUI:

Upgrade the number guessing game with a graphical user interface.

Input values:
1. User interacts with the graphical user interface (GUI) by entering a guessed number.
2. Users can also set the range of numbers for the game.

Output value:
Visual representation of the game interface displaying feedback on the guessed number, hints, and whether the guess is correct.

Example:

Input values:
1. Set the range of numbers: 1 to 100
- User sets the range of numbers for the game to be between 1 and 100.
Output value:
Visual representation of the game interface displays the set range of numbers.
Input values:
2. Guess a number: 50
- User enters 50 as the guess number.
Output value:
Visual representation of the game interface displays feedback that the guess number is too high or too low.
Input values:
3. Guess a number: 25
- User enters 25 as the guess number.
Output value:
Visual representation of the game interface displays feedback that the guess number is too low.
Input values:
4. Guess a number: 37
- User enters 37 as the guess number.
Output value:
Visual representation of the game interface displays feedback that the guess number is too high.
Input values:
5. Guess a number: 30
- User enters 30 as the guess number.
Output value:
Visual representation of the game interface displays feedback that the guess number is correct.

Solution 1: Number Guessing Game with GUI Using Tkinter

Following solution uses the tkinter library to create a graphical user interface for the number guessing game. The game allows the user to set a range for the numbers, guess the correct number, and receive feedback whether the guess is too high, too low, or correct.

Code:

import tkinter as tk
import random

# Function to start the game
def start_game():
    global number_to_guess
    min_val = int(min_entry.get())
    max_val = int(max_entry.get())
    number_to_guess = random.randint(min_val, max_val)  # Generate random number to guess
    feedback_label.config(text="Game started! Guess a number.")  # Feedback message
    guess_button.config(state="normal")  # Enable the guess button

# Function to check the guessed number
def check_guess():
    guess = int(guess_entry.get())
    if guess < number_to_guess:
        feedback_label.config(text="Too low! Try again.")
    elif guess > number_to_guess:
        feedback_label.config(text="Too high! Try again.")
    else:
        feedback_label.config(text="Correct! You guessed the number!")

# Set up the main window
root = tk.Tk()
root.title("Number Guessing Game")

# GUI elements
min_label = tk.Label(root, text="Enter Minimum Number:")
min_label.pack()
min_entry = tk.Entry(root)
min_entry.pack()

max_label = tk.Label(root, text="Enter Maximum Number:")
max_label.pack()
max_entry = tk.Entry(root)
max_entry.pack()

start_button = tk.Button(root, text="Start Game", command=start_game)
start_button.pack()

feedback_label = tk.Label(root, text="Set the range and start the game.")
feedback_label.pack()

guess_label = tk.Label(root, text="Enter your guess:")
guess_label.pack()
guess_entry = tk.Entry(root)
guess_entry.pack()

guess_button = tk.Button(root, text="Submit Guess", command=check_guess, state="disabled")
guess_button.pack()

# Run the application
root.mainloop()

Output:

Python: Number Guessing Game.

Explanation:

  • Set Range: User sets the minimum and maximum number for the range.
  • Start Game: A random number is generated between the provided range.
  • Guess Number: User enters a guess, and feedback is displayed if the guess is too low, too high, or correct.

Solution 2: Number Guessing Game with GUI Using PyQt5

In the following solution, we use PyQt5 to create the GUI for the number guessing game. Similar to the tkinter version, this game lets the user set a range and guess the correct number, with feedback displayed on the interface.

Code:

import sys
import random
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton, QLineEdit, QVBoxLayout

class NumberGuessingGame(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        
    def initUI(self):
        # Initialize the layout
        self.layout = QVBoxLayout()
        
        # Widgets for min and max range
        self.min_label = QLabel('Enter Minimum Number:')
        self.min_entry = QLineEdit()
        self.max_label = QLabel('Enter Maximum Number:')
        self.max_entry = QLineEdit()
        self.start_button = QPushButton('Start Game', self)
        self.start_button.clicked.connect(self.start_game)

        # Feedback and Guess widgets
        self.feedback_label = QLabel('Set the range and start the game.')
        self.guess_label = QLabel('Enter your guess:')
        self.guess_entry = QLineEdit()
        self.guess_button = QPushButton('Submit Guess', self)
        self.guess_button.clicked.connect(self.check_guess)
        self.guess_button.setDisabled(True)

        # Add widgets to layout
        self.layout.addWidget(self.min_label)
        self.layout.addWidget(self.min_entry)
        self.layout.addWidget(self.max_label)
        self.layout.addWidget(self.max_entry)
        self.layout.addWidget(self.start_button)
        self.layout.addWidget(self.feedback_label)
        self.layout.addWidget(self.guess_label)
        self.layout.addWidget(self.guess_entry)
        self.layout.addWidget(self.guess_button)
        
        # Set layout and window title
        self.setLayout(self.layout)
        self.setWindowTitle('Number Guessing Game')
    
    # Function to start the game
    def start_game(self):
        try:
            min_val = int(self.min_entry.text())
            max_val = int(self.max_entry.text())
            if min_val >= max_val:
                self.feedback_label.setText("Invalid range. Please try again.")
                return

            self.number_to_guess = random.randint(min_val, max_val)  # Generate random number
            self.feedback_label.setText(f"Game started! Guess a number between {min_val} and {max_val}.")
            self.guess_button.setDisabled(False)
        except ValueError:
            self.feedback_label.setText("Please enter valid numbers for the range.")

    # Function to check the guessed number
    def check_guess(self):
        try:
            guess = int(self.guess_entry.text())
            if guess < self.number_to_guess:
                self.feedback_label.setText("Too low! Try again.")
            elif guess > self.number_to_guess:
                self.feedback_label.setText("Too high! Try again.")
            else:
                self.feedback_label.setText("Correct! You guessed the number!")
            
            self.guess_entry.clear()  # Clear the guess entry field for the next input
        except ValueError:
            self.feedback_label.setText("Please enter a valid number.")

# Run the application
if __name__ == '__main__':
    app = QApplication(sys.argv)
    game = NumberGuessingGame()
    game.show()
    sys.exit(app.exec_())

Output:

Python: Number Guessing Game.

Explanation:

  • Set Range: User inputs the minimum and maximum values for the number range.
  • Start Game: A random number is generated when the game starts.
  • Guess Number: User guesses the number, and the game provides feedback on whether the guess is too high, too low, or correct.


Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/projects/python/python-project-build-a-gui-number-guessing-game.php