Skip to content
Related Articles

Related Articles

PyQt5 – Rock Paper and Scissor Game

Improve Article
Save Article
  • Last Updated : 29 Nov, 2022
Improve Article
Save Article

In this article we will see how we can create a rock paper and scissor game using PyQt5. Rock paper scissors is a hand game usually played between two people, in which each player simultaneously forms one of three shapes with an outstretched hand. These shapes are “rock”, “paper”, and “scissors”. Below is the representation of how the game will look like.

 

GUI implementation steps : 1. Create a head label that will show the title of the game, set its font and properties 2. Below the head label create a user label that will show the hand sign selected by user 3. Create a computer label that will show hand sign picked by the computer 4. In between the user and the computer label create a label to show text “vs” 5. Create a result label to show the result set font and other properties to it 6. Create three push buttons for rock, paper and scissor respectively 7. Create a reset button to reset the game Back end implementation steps : 1. Create user choice and counter variable set its value to -1 2. Add actions to the rock, paper and scissor button 3. Inside the actions set the choice value according to the button pressed and set the counter value to 3 and make all the three button disable 4. Create timer object that calls the method after every one second 5. Inside the timer method check if the counter value is -1 then do nothing else set the counter value to the computer label and decrement the counter 6. And check if the counter value is equal to 0 then get a random value from 1 to 3, according to value set the hand symbol to the computer label 7. Call the who_win method to get the result 8. Inside the who_wins method first check if the match is draw else find the winner and set the winner to the result label 9. Add action to the reset button 10. Inside the reset button action, set counter value to -1, enable all the buttons and remove the image from the computer and user label

Implementation: 

Python3




# importing libraries
from PyQt5.QtWidgets import *
from PyQt5 import QtCore, QtGui
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import random
import sys
 
 
class Window(QMainWindow):
 
    def __init__(self):
        super().__init__()
 
        # setting title
        self.setWindowTitle("Python ")
 
        # setting geometry
        self.setGeometry(100, 100, 320, 400)
 
        # calling method
        self.UiComponents()
 
        # showing all the widgets
        self.show()
 
    # method for components
    def UiComponents(self):
 
        # counter variable
        self.counter = -1
 
        # choice variable
        self.choice = 0
 
        # creating head label
        head = QLabel("Rock Paper Scissor", self)
 
        # setting geometry to the head
        head.setGeometry(20, 10, 280, 60)
 
        # font
        font = QFont('Times', 15)
        font.setBold(True)
        font.setItalic(True)
        font.setUnderline(True)
 
        # setting font to the head
        head.setFont(font)
 
        # setting alignment of the head
        head.setAlignment(Qt.AlignCenter)
 
        # setting color effect to the head
        color = QGraphicsColorizeEffect(self)
        color.setColor(Qt.darkCyan)
        head.setGraphicsEffect(color)
 
        # creating a vs label
        self.vs = QLabel("vs", self)
 
        # setting geometry
        self.vs.setGeometry(150, 110, 30, 50)
 
        # setting font
        font.setUnderline(False)
        font.setItalic(False)
        self.vs.setFont(font)
 
        # creating your choice label
        self.user = QLabel("You", self)
 
        # setting geometry
        self.user.setGeometry(50, 100, 70, 70)
        self.user.setStyleSheet(
            "border : 2px solid black; background : white;")
 
        # setting alignment
        self.user.setAlignment(Qt.AlignCenter)
 
        # creating computer choice label
        self.computer = QLabel("Computer", self)
 
        # setting geometry
        self.computer.setGeometry(200, 100, 70, 70)
        self.computer.setStyleSheet(
            "border : 2px solid black; background : white;")
 
        # setting alignment
        self.computer.setAlignment(Qt.AlignCenter)
 
        # result label
        self.result = QLabel(self)
 
        # setting geometry to the result
        self.result.setGeometry(25, 200, 270, 50)
 
        # setting font
        self.result.setFont(QFont('Times', 14))
 
        # setting alignment
        self.result.setAlignment(Qt.AlignCenter)
 
        # setting border and color
        self.result.setStyleSheet(
            "border : 2px solid black; background : white;")
 
        # creating three push button
        # for rock paper and scissor
        self.rock = QPushButton("Rock", self)
        self.rock.setGeometry(30, 270, 80, 35)
 
        self.paper = QPushButton("Paper", self)
        self.paper.setGeometry(120, 270, 80, 35)
 
        self.scissor = QPushButton("Scissor", self)
        self.scissor.setGeometry(210, 270, 80, 35)
 
        # adding actions to the buttons
        self.rock.clicked.connect(self.rock_action)
        self.paper.clicked.connect(self.paper_action)
        self.scissor.clicked.connect(self.scissor_action)
 
        # creating push button to reset all the game
        game_reset = QPushButton("Reset", self)
 
        # setting geometry
        game_reset.setGeometry(100, 320, 120, 50)
 
        # setting color effect
        color = QGraphicsColorizeEffect(self)
        color.setColor(Qt.red)
        game_reset.setGraphicsEffect(color)
 
        # adding action tot he reset button
        game_reset.clicked.connect(self.reset_action)
 
        # creating a timer object
        timer = QTimer(self)
 
        # adding action to the timer
        timer.timeout.connect(self.showTime)
 
        # starting the timer
        timer.start(1000)
 
    def showTime(self):
 
        # if counter value is - 1
        if self.counter == -1:
            pass
 
        # if counter is not - 1
        else:
 
            # setting counter value to the label
            self.computer.setText(str(self.counter))
 
            if self.counter == 0:
                self.comp_choice = random.randint(1, 3)
 
                # if computer choice is 1
                if self.comp_choice == 1:
 
                    # setting rock image to the computer label
                    self.computer.setStyleSheet(
                        "border-image : url(rock.png);")
 
                elif self.comp_choice == 2:
                    # setting paper image to the computer label
                    self.computer.setStyleSheet(
                        "border-image : url(Paper.png);")
 
                else:
                    # setting scissor image to the computer label
                    self.computer.setStyleSheet(
                        "border-image : url(scissor.png);")
 
                # checking who won the match
                self.who_won()
 
            # decrementing the counter value
            self.counter -= 1
 
    def rock_action(self):
 
        # making choice as 1
        self.choice = 1
 
        # setting rock image to the user label
        self.user.setStyleSheet("border-image : url(rock.png);")
 
        # making counter value to 3
        self.counter = 3
 
        # disabling the push button
        self.rock.setDisabled(True)
        self.paper.setDisabled(True)
        self.scissor.setDisabled(True)
 
    def paper_action(self):
 
        # making choice as 2
        self.choice = 2
 
        # setting rock image to the user label
        self.user.setStyleSheet("border-image : url(Paper.png);")
 
        # making counter value to 3
        self.counter = 3
 
        # disabling the push button
        self.rock.setDisabled(True)
        self.paper.setDisabled(True)
        self.scissor.setDisabled(True)
 
    def scissor_action(self):
 
        # making choice as 3
        self.choice = 3
 
        # setting rock image to the user label
        self.user.setStyleSheet("border-image : url(scissor.png);")
 
        # making counter value to 3
        self.counter = 3
 
        # disabling the push button
        self.rock.setDisabled(True)
        self.paper.setDisabled(True)
        self.scissor.setDisabled(True)
 
    def reset_action(self):
 
        # making result label empty
        self.result.setText("")
 
        # resting the counter value
        self.counter = -1
 
        # enabling the push buttons
        self.rock.setEnabled(True)
        self.paper.setEnabled(True)
        self.scissor.setEnabled(True)
 
        # removing images from the user and computer label
        self.user.setStyleSheet("border-image : null;")
        self.computer.setStyleSheet("border-image : null;")
 
    def who_won(self):
 
        # if match is draw
        if self.choice == self.comp_choice:
 
            # setting text to the result label
            self.result.setText("Draw Match")
 
        else:
            # condition for winning
            # user choose rock
            if self.choice == 1:
                # computer choose paper
                if self.comp_choice == 2:
                    # setting text to the result
                    self.result.setText("Computer Wins")
                else:
                    self.result.setText("User Wins")
 
            # user chooses paper
            elif self.choice == 2:
                # computer choose scissor
                if self.comp_choice == 3:
                    # setting text to the result
                    self.result.setText("Computer Wins")
                else:
                    self.result.setText("User Wins")
 
            # if user chooses scissor
            elif self.choice == 3:
                # computer choose rock
                if self.comp_choice == 1:
                    # setting text to the result
                    self.result.setText("Computer Wins")
                else:
                    self.result.setText("User Wins")
 
 
# create pyqt5 app
App = QApplication(sys.argv)
 
# create the instance of our Window
window = Window()
 
# start the app
sys.exit(App.exec())

Output :

Code Explanation:

  1. The code starts by creating a new class, Window.
  2. This class will be the main window for our application.
  3. Next, the __init__() method is called.
  4. In this method, we set the title of the window and configure its geometry.
  5. We also call UiComponents(), which is a special method that will show all of our widgets in the window.
  6. Now let’s take a look at what happens when we run this code.
  7. First, we create an instance of Window and set its title to “Python”.
  8. Then we configure the window’s geometry by setting its size to 100 x 100 pixels and its position to 320 x 400 pixels onscreen (see Figure 1-1).
  9. Figure 1-1: The Python Window with Its Geometry Configured Next, we call UiComponents().
  10. This method will show all of our widgets in the window (see Figure 1-2).
  11. Window object Figure 1-2: The Python Window With All Its Widgets Shown In this example, there are only two widgets in our window—the text box and the button.
  12. However, you can add as many widgets
  13. The code creates a new window and sets its title to “Python”.
  14. It then sets the window’s geometry to (100, 100, 320, 400).
  15. Finally, it calls the UiComponents() method on the window object.
  16. The UiComponents() method is responsible for displaying all of the widgets in the window.
  17. The code first shows all of the widgets by calling show().
  18. After showing all of the widgets, the code calls a method called updateWidget().
  19. This method is responsible for updating each widget in the window.
  20. The code starts by creating a QLabel object and setting its geometry to 20, 10, and 280 pixels wide by 60 pixels high.
  21. The label’s font is then set to Times New Roman with bold and italic settings enabled, and underline enabled.
  22. Finally, the head’s alignment is set to Qt.AlignCenter.
  23. Next, the code creates a choice variable and sets it to 0.
  24. The choice variable will store the user’s selection between rock (0) and paper (1).
  25. The next line of code creates a head label object and sets its geometry to 20, 10, 280 pixels wide by 60 pixels high.
  26. The label’s font is then set to Times New Roman with bold and italic settings enabled, as well as underline disabled.
  27. Finally, the head’s alignment is set to Qt.AlignLeftJustified.
  28. Next , we create two buttons using QPushButton objects .
  29. One button will be used for selecting rock or paper , while the other will be used for cancelling out of the game .
  30. We first create a QPushButton object named “rock” .
  31. This button will be used for selecting whether or not the player wants to play with rocks .
  32. The code creates a QLabel object and sets its geometry to 20 x 10 pixels, with the top-left corner at (280, 60) pixels.
  33. The font is then set to Times New Roman font with the bold, italic, and underline properties set to True.
  34. Finally, the head’s alignment is set to Qt.AlignCenter.
  35. The code starts by creating a new QGraphicsItem, which is the head of the user interface.
  36. The head object has a GraphicsEffect property that can be set to one of several color effects.
  37. In this example, we use the QGraphicsColorizeEffect class to change the color of the head object to dark cyan.
  38. Next, we create a new QLabel object and set its geometry to 150 x 110 pixels in size, with a width of 30 pixels and a height of 50 pixels.
  39. We also set its font properties to underline (false) and italic (false), so that it will not display any text.
  40. Finally, we create another QLabel object called user and set its geometry to 50 x 100 pixels in size, with a width of 70 pixels and a height of 70 pixels.
  41. Now let’s take a look at some code that uses these objects: # setting colors self.head.setGraphicsEffect(Qt.darkCyan) # creating vs label self.vs = QLabel(“vs”, self) # setting geometry self.vs.setGeometry(150, 110, 30, 50)
  42. The code will create a QGraphicsItem object called head, and set the graphics effect to colorize.
  43. The head will also have a QLabel object created and assigned as its parent.
  44. The label will be given a geometry of 150 x 110 pixels, with a width of 30 pixels and a height of 50 pixels.
  45. Next, the font for the label will be set to italic and underline disabled.
  46. Finally, the user QLabel object will be created with the same dimensions as head.
  47. The code starts by creating a user interface.
  48. The user interface consists of three labels, a computer choice label, and three push buttons.
  49. The first button, the rock button, is set to have a geometry of 30 x 270 pixels with an 80 pixel border and a 35 pixel center point.
  50. The second button, the paper button, is set to have a geometry of 120 x 270 pixels with an 80 pixel border and a 35 pixel center point.
  51. The third button, the scissors button, is set to have a geometry of 210 x 270 pixels with an 80 pixel border and a 35 pixel center point.
  52. Next, the code sets up actions for each of the buttons.
  53. For the rock button, the code connects it to an action that prints “Rock” onscreen when it is clicked.
  54. For the paper button, the code connects it to an action that prints “Paper” onscreen when it is clicked.
  55. For the scissors button, the code connects it to an action that prints “Scissors” onscreen when it is clicked.
  56. The code creates a user interface with three push buttons.
  57. The first push button, Rock, is configured to have the following geometry: 30 x 270 x 80 pixels.
  58. The second push button, Paper, is configured to have the following geometry: 120 x 270 x 80 pixels.
  59. The third push button, Scissor, is configured to have the following geometry: 210 x 270 x 80 pixels.
  60. Each of the buttons has an action associated with it.
  61. The rock button’s action is connected to the rock_action function and will be executed when it is clicked.
  62. The paper button’s action is connected to the paper_action function and will be executed when it is clicked.
  63. The scissor button’s action is connected to the sc
  64. The code starts by creating a QPushButton object named game_reset.
  65. The button has the following properties: name: “game_reset” label: “Reset” icon: “ui/images/pushbutton.png” Next, the code sets the geometry of the button using setGeometry().
  66. The coordinates are (100, 320, 120, 50).
  67. The size of the button is also specified (it will be 100×32 pixels).
  68. Finally, a color effect is added to the button with setGraphicsEffect().
  69. This effect uses Qt’s red color as its base color.
  70. The next step is to create an action handler for the game_reset button.
  71. This handler will be called when someone clicks on it.
  72. The code creates a QTimer object and attaches an action to it called timeout().
  73. This action will cause the timer to run for 1000 milliseconds (1 second).
  74. After that time has elapsed, the showTime() function will be executed.
  75. This function simply displays a message onscreen saying “timer started.”
  76. The code creates a QPushButton named game_reset and sets its geometry to 100 x 320 pixels, with a width of 120 pixels and a height of 50 pixels.
  77. It also sets the button’s color to red.
  78. Next, the code creates a QGraphicsColorizeEffect object and sets its color to Qt.red.
  79. Finally, the code adds an action to the game_reset button called clicked, which connects it to the self.reset_action function.
  80. This function will be executed when the user clicks on the game_reset button.
  81. The last part of this code is responsible for creating a timer object and adding an action to it called timeout that connects it to the self.showTime function.
  82. This function will
  83. The code starts by initializing some variables.
  84. The first variable is self.counter, which will keep track of the number of times the rock, paper, and scissor buttons have been clicked.
  85. Next, the code sets up three buttons (rock, paper, and scissor) and defines their respective actions.
  86. When a user clicks on the rock button, the code sets self.choice to 1 and sets the border image for the user’s label to rock.png.
  87. When a user clicks on the paper button, the code sets self.choice to 2 and sets the border image for the user’s label to Paper.png.
  88. Finally, when a user clicks on the scissor button, the code sets self.choice to 3 and sets the border image fortheuser’slabeltoScissor.png .
  89. Next comes some logic that checks who won each match between users Rock vs Paper , Rock vs Scissor , and Paper vs Scissor .
  90. If one of these matches has already been made (by either player clicking on one of those buttons), then nothing happens; no new images are displayed or changed in any way onscreen because there is no need to do so since both players
  91. The code first sets up some variables to store information about the user’s choices.
  92. These variables are used later on in the code when it comes time to check who won the match.
  93. Next, the code checks to see if any of the buttons have been clicked.
  94. If one of the buttons has been clicked, then the appropriate action is taken.
  95. If no button has been clicked, then the code sets up three buttons and determines which one the user will choose by checking their choice variable.
  96. Once this decision is made, the appropriate rock image, paper image, or scissor image is set as the user’s label and counter value is decreased by 1.

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!