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 to the 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:
- The code starts by creating a new class, Window.
- This class will be the main window for our application.
- Next, the __init__() method is called.
- In this method, we set the title of the window and configure its geometry.
- We also call UiComponents(), which is a special method that will show all of our widgets in the window.
- Now let’s take a look at what happens when we run this code.
- First, we create an instance of Window and set its title to “Python”.
- 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).
- Figure 1-1: The Python Window with Its Geometry Configured Next, we call UiComponents().
- This method will show all of our widgets in the window (see Figure 1-2).
- 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.
- However, you can add as many widgets
- The code creates a new window and sets its title to “Python”.
- It then sets the window’s geometry to (100, 100, 320, 400).
- Finally, it calls the UiComponents() method on the window object.
- The UiComponents() method is responsible for displaying all of the widgets in the window.
- The code first shows all of the widgets by calling show().
- After showing all of the widgets, the code calls a method called updateWidget().
- This method is responsible for updating each widget in the window.
- The code starts by creating a QLabel object and setting its geometry to 20, 10, and 280 pixels wide by 60 pixels high.
- The label’s font is then set to Times New Roman with bold and italic settings enabled, and underline enabled.
- Finally, the head’s alignment is set to Qt.AlignCenter.
- Next, the code creates a choice variable and sets it to 0.
- The choice variable will store the user’s selection between rock (0) and paper (1).
- The next line of code creates a head label object and sets its geometry to 20, 10, 280 pixels wide by 60 pixels high.
- The label’s font is then set to Times New Roman with bold and italic settings enabled, as well as underline disabled.
- Finally, the head’s alignment is set to Qt.AlignLeftJustified.
- Next , we create two buttons using QPushButton objects .
- One button will be used for selecting rock or paper , while the other will be used for cancelling out of the game .
- We first create a QPushButton object named “rock” .
- This button will be used for selecting whether or not the player wants to play with rocks .
- The code creates a QLabel object and sets its geometry to 20 x 10 pixels, with the top-left corner at (280, 60) pixels.
- The font is then set to Times New Roman font with the bold, italic, and underline properties set to True.
- Finally, the head’s alignment is set to Qt.AlignCenter.
- The code starts by creating a new QGraphicsItem, which is the head of the user interface.
- The head object has a GraphicsEffect property that can be set to one of several color effects.
- In this example, we use the QGraphicsColorizeEffect class to change the color of the head object to dark cyan.
- 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.
- We also set its font properties to underline (false) and italic (false), so that it will not display any text.
- 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.
- 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)
- The code will create a QGraphicsItem object called head, and set the graphics effect to colorize.
- The head will also have a QLabel object created and assigned as its parent.
- The label will be given a geometry of 150 x 110 pixels, with a width of 30 pixels and a height of 50 pixels.
- Next, the font for the label will be set to italic and underline disabled.
- Finally, the user QLabel object will be created with the same dimensions as head.
- The code starts by creating a user interface.
- The user interface consists of three labels, a computer choice label, and three push buttons.
- 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.
- 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.
- 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.
- Next, the code sets up actions for each of the buttons.
- For the rock button, the code connects it to an action that prints “Rock” onscreen when it is clicked.
- For the paper button, the code connects it to an action that prints “Paper” onscreen when it is clicked.
- For the scissors button, the code connects it to an action that prints “Scissors” onscreen when it is clicked.
- The code creates a user interface with three push buttons.
- The first push button, Rock, is configured to have the following geometry: 30 x 270 x 80 pixels.
- The second push button, Paper, is configured to have the following geometry: 120 x 270 x 80 pixels.
- The third push button, Scissor, is configured to have the following geometry: 210 x 270 x 80 pixels.
- Each of the buttons has an action associated with it.
- The rock button’s action is connected to the rock_action function and will be executed when it is clicked.
- The paper button’s action is connected to the paper_action function and will be executed when it is clicked.
- The scissor button’s action is connected to the sc
- The code starts by creating a QPushButton object named game_reset.
- 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().
- The coordinates are (100, 320, 120, 50).
- The size of the button is also specified (it will be 100×32 pixels).
- Finally, a color effect is added to the button with setGraphicsEffect().
- This effect uses Qt’s red color as its base color.
- The next step is to create an action handler for the game_reset button.
- This handler will be called when someone clicks on it.
- The code creates a QTimer object and attaches an action to it called timeout().
- This action will cause the timer to run for 1000 milliseconds (1 second).
- After that time has elapsed, the showTime() function will be executed.
- This function simply displays a message onscreen saying “timer started.”
- 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.
- It also sets the button’s color to red.
- Next, the code creates a QGraphicsColorizeEffect object and sets its color to Qt.red.
- Finally, the code adds an action to the game_reset button called clicked, which connects it to the self.reset_action function.
- This function will be executed when the user clicks on the game_reset button.
- 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.
- This function will
- The code starts by initializing some variables.
- The first variable is self.counter, which will keep track of the number of times the rock, paper, and scissor buttons have been clicked.
- Next, the code sets up three buttons (rock, paper, and scissor) and defines their respective actions.
- 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.
- 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.
- Finally, when a user clicks on the scissor button, the code sets self.choice to 3 and sets the border image fortheuser’slabeltoScissor.png .
- Next comes some logic that checks who won each match between users Rock vs Paper , Rock vs Scissor , and Paper vs Scissor .
- 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
- The code first sets up some variables to store information about the user’s choices.
- These variables are used later on in the code when it comes time to check who won the match.
- Next, the code checks to see if any of the buttons have been clicked.
- If one of the buttons has been clicked, then the appropriate action is taken.
- 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.
- 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.