Create GUIs with Python: Emoji Match
Create a fun picture-matching game
You are going to build an emoji picture-matching game (Figure 1). The object of the game is to spot the one emoji that appears in two different sets. You get a point for each correct match and lose a point for an incorrect match.
Loading emojis
To create the game, you will need some emojis. You can use the emojis created for Twitter (twemoji.twitter.com). Download the emojis.zip file from magpi.cc/guizeroemojis, open the zip file, and copy the emojis folder to the folder where you save your code. The game will need to choose nine emojis at random and arrange them into a grid. A simple way to do this is to put all of the emojis into a list and randomly shuffle them. Create a new program with the usual commented lines for different sections (Imports, Variables, Functions, App), as we’ve done in previous instalments. Under imports, add: import os from random import shuffle Then, under variables, enter this code which creates a shuffled list of emojis, each in the form path/emoji_file_name. # set the path to the emoji folder on your computer emojis_dir = "emojis" emojis = [os.path.join(emojis_dir, f) for f in os.listdir(emojis_dir)] shuffle(emojis) The emojis_dir variable is the path of the emojis on your computer; it will tell the code that loads the emojis where to find them. Test your program. Try printing the emojis list to the screen with print(emojis). You should see a long list of file names. The list should be in a different order each time you run it.
Displaying the emojis
Next, the code needs to create two 3×3 grids of Picture and PushButton widgets which will show the emojis. Modify your program to create a guizero app and a Box to hold the picture widgets using a "grid" layout. In the imports section, add this line to import the required widgets: from guizero import App, Box In the app section, add the following code: app = App("emoji match") pictures_box = Box(app, layout="grid") The Box widget is really useful for laying out your GUI. It’s an invisible area of your GUI where you can group widgets together. A Box can have its own
layout, size, and bg (background). They can also be hidden or shown, meaning you can easily make a collection of widgets invisible. If you wish to see the Box, you can add a border by setting the parameter to True.
``` pictures_box = Box(app, layout="grid", border=True) ```
Now, add the Picture widget to your imports:
``` from guizero import App, Box, Picture ```
In the app section, add in the code to create the Picture widgets and add them to a list.
``` pictures = [] for x in range(0,3): for y in range(0,3): picture = Picture(pictures_box, grid=[x,y]) pictures.append(picture) ```
The widgets are appended to a list so they can be referenced later in the game
To assign co-ordinates to each Picture widget, two for loops are used. They both run through the range 0–2; one assigns its value to the variable **x** and the other to the variable **y**. The grid position of each widget is set using the **x** and **y** values. The widgets are appended to a list so they can be referenced later in the game.
Do the same for PushButton widgets to create the second 3×3 grid. First, add the widget to your imports:
``` from guizero import App, Box, Picture, PushButton ```
In the app section, add lines so it looks like this:
``` app = App("emoji match") pictures_box = Box(app, layout="grid") buttons_box = Box(app, layout="grid") pictures = [] buttons = [] for x in range(0,3): for y in range(0,3): picture = Picture(pictures_box, grid=[x,y]) pictures.append(picture) ```
``` grid=[x,y]) buttons.append(button) ```
In the functions section, create a function to set up each round of the game.
``` def setup_round(): for picture in pictures: picture.image = emojis.pop() for button in buttons: button.image = emojis.pop() ```
To assign each picture and button widget an emoji, the image property is set to an item from the emojis list. Emojis are selected using pop(), which chooses the last item in a list and then removes it from the list. We’ve used this function because it will prevent any emoji appearing in the game more than once. At the bottom of your program, call the setup_round function and display the app.
``` setup_round() app.display() ```
Your program should now resemble emoji1.py (see previous page). Test it and you should see two grids of nine emojis.
Matching emojis
At the moment, all of the emojis in your app will be different (Figure 2). In the next step, you will pick another emoji to match, and update one picture and one button so they have the same matching emoji.
Add randint to your random import line. This is used to obtain a number from 0 to 8 for each picture and button.
``` from random import shuffle, randint ```
Then add this code (indented) to the bottom of the setup_round function to pop another emoji from the list and set it to be the image of a random picture and button.
``` matched_emoji = emojis.pop() random_picture = randint(0,8) pictures[random_picture].image = matched_emoji random_button = randint(0,8) buttons[random_button].image = matched_emoji ```
Your code should now look like emoji2.py. Run your program now, one of the emojis should match. Look carefully – the matching emoji can be hard to spot.
Check the guess
Each time one of the PushButtons is pressed, it will need to check if this is the matching emoji and put the result ‘correct’ or ‘incorrect’ on the screen. After the player’s guess, a new round will be set up and different set of emojis displayed.
Your app will need a Text widget display the result. Add it to your imports:
``` from guizero import App, Box, Picture, PushButton, Text ```
Add this line in your app section:
Create a new function which will be called when one of the emoji buttons is pressed. It will display ‘correct’ or ‘incorrect’ and call setup_round to create the next set of emojis.
``` def match_emoji(matched): if matched: result.value = "correct" else: result.value = "incorrect" setup_round() ```
The incorrect emoji buttons will pass False to the match_emoji function; the matching emoji will pass True.
Update the setup_round function so that all the ‘incorrect’ buttons call the match_emoji function.
``` for button in buttons: button.image = emojis.pop() button.update_command(match_emoji, args=[False]) ```
The update_command method sets the function which will be called when the button is pressed. The args list [False] will be used as the parameters to the match_emoji function.
Finally, update the command for the matching button so it calls match_emoji, but this time passes True as the argument.
``` buttons[random_button].update_ command(match_emoji, [True]) ```
Your code should now resemble emoji3.py (previous page). Play the game. In each round there will be a matching emoji – press the matching picture button. Did you get it right?
Adding a score and timer
At the moment, the game continues forever (or until you run out of emojis in the list). Add a score and a timer which counts down to the end of the game to give a challenge.
In the app section, create two Text widgets to show the score and the timer.
The timer is set to "30", which will be the number of seconds in each round. Modify the match_emoji function to either add or subtract 1 to/from the player’s score.
To create the timer, you will use a feature of guizero which allows you to ask the application to continuously call a function every 1 second. Create a function which will reduce the value of the timer by 1.
Before the app is displayed, use the app.repeat() function to call the reduce_time function every second (1000 milliseconds).
Running your game now, you will notice that the timer counts down from 30. Unfortunately, it will continue counting down past 0 and never stop. Update the reduce_time function to check if the timer is less than zero and then stop the game.
``` def reduce_time(): timer.value = int(timer.value) - 1 # is it game over? if int(timer.value) < 0: result.value = "Game over! Score = " + score.value # hide the game pictures_box.hide() buttons_box.hide() timer.hide() score.hide() ```
When the timer is less than 0, the message ‘game over’ is displayed and the game's widgets are hidden so the user can no longer play. See emoji4.py to get an idea of how your code should now look. Run it and play the emoji match game. Challenge a friend or family member to a game.
You may want to put the score and timer widgets into a Box so they can be laid out better (Figure 3, previous page) – see the complete 09-emoji-match.py listing for how to do this.