PyQt5 - Number Guessing Game

PyQt5 - Number Guessing Game

Creating a number guessing game in PyQt5 involves setting up a basic GUI application where a user can input guesses and receive feedback on whether their guess is too high, too low, or correct. Below is a step-by-step guide to create this game:

Step 1: Install PyQt5

If you haven't installed PyQt5, you can do so using pip:

pip install pyqt5 

Step 2: Create the Game Logic

First, you need to create the logic for the number guessing game. This will involve generating a random number and comparing the user's guess to this number.

Step 3: Set Up the PyQt5 Window

Create a basic PyQt5 window with input fields and buttons for the user to interact with.

Example Code

Here's a complete example of how you might set up a simple number guessing game using PyQt5:

import sys import random from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QLineEdit, QPushButton class NumberGuessingGame(QWidget): def __init__(self): super().__init__() self.initUI() self.random_number = random.randint(1, 100) def initUI(self): self.layout = QVBoxLayout() self.info_label = QLabel("Guess a number between 1 and 100") self.layout.addWidget(self.info_label) self.guess_input = QLineEdit() self.layout.addWidget(self.guess_input) self.guess_button = QPushButton("Guess") self.guess_button.clicked.connect(self.check_guess) self.layout.addWidget(self.guess_button) self.setLayout(self.layout) self.setWindowTitle("Number Guessing Game") self.setGeometry(300, 300, 300, 150) def check_guess(self): guess = int(self.guess_input.text()) if guess < self.random_number: self.info_label.setText("Too low!") elif guess > self.random_number: self.info_label.setText("Too high!") else: self.info_label.setText("Correct! The number was " + str(self.random_number)) def main(): app = QApplication(sys.argv) ex = NumberGuessingGame() ex.show() sys.exit(app.exec_()) if __name__ == '__main__': main() 

How It Works:

  • The NumberGuessingGame class creates the GUI window.
  • The initUI method sets up the layout, a label for instructions, a line edit for input, and a button to submit guesses.
  • The check_guess method is connected to the button click event and checks the user's guess against the randomly generated number.
  • When the user makes a guess, feedback is provided through the label text.

When you run this script, it will display a window where you can input a number and click the "Guess" button to see if your guess is correct. The game generates a new random number each time it's started.


More Tags

drag post-build nsjsonserialization asp.net-mvc-2 outliers chrome-ios named-pipes stata http-status-code-503 mouse

More Programming Guides

Other Guides

More Programming Examples