By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
rocoderesrocoderes
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Notification Show More
Latest News
How to set the dropdown value by clicking on a table row
Javascript – How to set the dropdown value by clicking on a table row
JavaScript
Attempting to increase the counter, when the object's tag exist
Javascript – Attempting to increase the counter, when the object’s tag exist
JavaScript
Cycle2 JS center active slide
Javascript – Cycle2 JS center active slide
JavaScript
Can import all THREE.js post processing modules as ES6 modules except OutputPass
Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass
JavaScript
How to return closest match for an array in Google Sheets Appscript
Javascript – How to return closest match for an array in Google Sheets Appscript
JavaScript
Aa
Aa
rocoderesrocoderes
Search
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Follow US
High Quality Design Resources for Free.
rocoderes > Python > picture matching game using python
Python

picture matching game using python

Rohan750
Last updated: 2021/05/16 at 5:16 AM
Rohan750
Share
9 Min Read

Contents
What happens in picture matching gameHow Picture matching game works1.Create a new file2.Add modules 3.Set up the picture matching game GUI 4.Make some variables5.Add the symbols in picture matching game gui6.Shuffle the symbols7.Build the matchmaker grid8.Show the symbolsShow the number of moves
In picture matching game check How good is your memory? Check it out for your self a fun game where you have to get in pairs the same symbols. See how fast you can go find all 12 identical pairs.

What happens in picture matching game

While you run this program. It’s going to show a window grid of buttons. Click on them in pairs to reveal the hidden one’s symbols. If the two icons are identical, you have found a match. And icons are visible on the screen. else, both buttons are reset. Try to remember the location of each hidden symbol to quickly find all pairs.

picture matching game

How Picture matching game works

Here we use the Tkinter module to display the Button grid. Dickinter’s mainloop () function listens Pressing the button handles them with a special type Of function, called a lambda function, which reveals A code. If an unmatched symbol already existed Revealed, the program tests whether it is secondary In matches. The program stores buttons in a dictionary And symbols in a list.

1.Create a new file

Open IDLE. Create a new file and save it as “matchmaker.py

2.Add modules 

Now type this code at the top of your file to import the modules you need for this project. You’ll use random to shuffle the symbols, time to pause the program, and Tkinter to create the GUI.

import random
import time
from tkinter import Tk, Button, DISABLED, messagebox


3.Set up the picture matching game GUI

The root.resizable() function prevents the player from resizing the window. 


root = Tk()
root.title('Matchmaker')
root.resizable(width=False, height=False)

4.Make some variables

Add Variables required for the program, and Create a dictionary to store the buttons. For every attempt at a match. You have to note whether it is. First or the second match symbol. You should have too If you press the first button, you can Compare by pressing the second button.


# Make some variables
buttons = {}
first = True
previousX = 0
previousY = 0

The buttons variable is the dictionary. The first variable is used to check if the symbol is the first in the match. The previous x and previous y two variables. They keep track of the last button pressed.

5.Add the symbols in picture matching game gui

The next code below to add the symbols the game will use. the program uses Unicode characters. There are 12 pairs, making 24 pairs in total. Add this code under the variables added in symbols.


# Add the symbols
button_symbols = {}
symbols = [u'u2702', u'u2702', u'u2705', u'u2705', u'u2708', u'u2708',
           u'u2709', u'u2709', u'u270A', u'u270A', u'u270B', u'u270B',
           u'u270C', u'u270C', u'u270F', u'u270F', u'u2712', u'u2712',
           u'u2714', u'u2714', u'u2716', u'u2716', u'u2728', u'u2728',

the button_symbols use for each button is stored in this dictionary.symbols list stores the 12 pairs of symbols that will be used in the game.

6.Shuffle the symbols

You don’t want the symbols to appear in the same place every time. After several games, the player will remember their positions and be able to match everything on their first attempt each time. To prevent this, You must change the symbols. Before each game starts.


# Shuffle the symbols
random.shuffle(symbols)

The shuffle() function from the random module mixes up the shapes.

7.Build the matchmaker grid

The grid consists of 24 buttons in four rows of six. To set the grid, you will use the built-in loops. The outer x loop works from left to right Six columns, the inner y loop will work from above Below each column. Once the loops are available to run. Each button will be given a pair of x and y coordinates. That set its position on the grid. Put this block of code after the shuffle command.



# Build the grid
for x in range(6):
    for y in range(4):
        button = Button(command=lambda x=x, y=y: show_symbol(x, y), width=5, height=3, border=2)
        button.grid(column=x, row=y,padx=15,pady=20)
        buttons[x, y] = button
        button_symbols[x, y] = symbols.pop()

show_symbol function creates each button and sets its size and action when pressed.buttons[x, y] saves each button in the buttons dictionary.

8.Show the symbols

you need to create the function of handling button presses. The function will always display symbols. But it depends on how it works. This is the first or second attempt at matching. For the first time, the Remember which button was pressed. If it is second In return, check if the symbol matches. unmatched symbols are hidden. Match symbols are displayed and their buttons are disabled.



def show_symbol(x, y):
    global first
    global previousX, previousY
    buttons[x, y]['text'] = button_symbols[x, y]
    buttons[x, y].update_idletasks()
    if first:
        previousX = x
        previousY = y
        first = False
    elif previousX != x or previousY != y:
        if buttons[previousX, previousY]['text'] != buttons[x, y]['text']:
            time.sleep(0.5)
            buttons[previousX, previousY]['text'] = ''
            buttons[x, y]['text'] = ''
        else:
            buttons[previousX, previousY]['command'] = DISABLED
            buttons[x, y]['command'] = DISABLED
        first = True

show_symbol(x, y) in The x and y values tell the function which button has been pressed.


buttons[x, y]['text'] = button_symbols[x, y]
buttons[x, y].update_idletasks()

These lines show the symbol.

if first:
        previousX = x
        previousY = y

first = False

If it’s the first turn, the code remembers the button press by storing the x and y coordinates.


#Second turn. This line includes a check to stop the player cheating by pressing every button twice!
    elif previousX != x or previousY != y:  
        if buttons[previousX, previousY]['text'] != buttons[x, y]['text']: #If the symbols don’t match...
            # Wait 0.5 seconds to give the player time to see the symbols, then hide them.
            time.sleep(0.5)
            buttons[previousX, previousY]['text'] = ''
            buttons[x, y]['text'] = ''
        else:                               #If the symbols match...
            #Disable the pair of matching buttons so the player can’t press them again.
            buttons[previousX, previousY]['command'] = DISABLED
            buttons[x, y]['command'] = DISABLED
        first = True #This line gets the function ready for the first button press of the next attempt.

Show the number of moves

At the moment, the player has no of knowing how well they’ve done or If they’ve done. Any better than their friends. Here we make the game more competitive. Let’s add a variable to count how many turns a player takes to finish the game. Then players can compare to see who gets the lowest score.

1.Add a new module

You will need to import the Tikinter’s message box widget to display the number of moves at the end of the game.

2.Make new variables

You’ll have to make two extra variables. Tracking a variable number. The moves the player makes another. Remember how many pairs they found. Give Both of these have a starting value of 0.


previousY = 0
moves = 0
pairs = 0

3.Declare them global

In the show_symbol() function  moves and pairs variables are declared global variables

def show_symbol(x, y):
    global first
    global previousX, previousY
    global moves
    global pairs

4.Count the moves.

Add 1 to the moves variable. When the show_symbol() function is called


if first:
        previousX = x
        previousY = y
        first = False
        moves = moves + 1

5.Display a message.

Add 1 to the number of pairs found. If all the pairs have been found, run the code under this line. 


buttons[x, y]['command'] = DISABLED
            pairs = pairs + 1
            if pairs == len(buttons) / 2:
                messagebox.showinfo('Matching', 'Number of moves: ' + str(moves))
        first = True #This line gets the function ready for the first button pres

full source code:

https://github.com/patelrohan750/python_projects

Related

Subscribe to Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Share this Article
Facebook Twitter Email Print
What do you think?
Love0
Sad0
Happy0
Sleepy0
Angry0
Dead0
Wink0
Previous Article Hangman in Python
Next Article Bookmarker Application in javascript
14 Comments 14 Comments
  • GujjuCamper says:
    October 7, 2020 at 4:03 am

    This comment has been removed by the author.

    Reply
  • GujjuCamper says:
    October 7, 2020 at 4:05 am

    Shu vaat chokra
    Jalso padi gyo

    Reply
  • Nickolas says:
    November 16, 2021 at 11:31 pm

    I was more than happy to find this page. I want to to thank
    you for ones time just for this fantastic read!!
    I definitely really liked every part of it and i also have you bookmarked
    to see new information on your site.

    Reply
  • Lacey says:
    November 18, 2021 at 10:53 pm

    Right here is the right website for anyone who would
    like to find out about this topic. You understand so much its almost tough to argue with you (not that I really would want
    to…HaHa). You certainly put a brand new spin on a
    topic that has been discussed for a long time.

    Wonderful stuff, just great!

    Reply
  • Octavio says:
    November 22, 2021 at 5:44 pm

    Hello friends, how is everything, and what you would like to
    say regarding this piece of writing, in my view its actually
    remarkable in favor of me.

    Reply
  • gralion torile says:
    March 3, 2022 at 10:17 am

    Absolutely pent articles, Really enjoyed reading through.

    Reply
  • tinyurl.com says:
    March 23, 2022 at 3:07 am

    Hello just wanted to give you a quick heads up and let you know a few of the pictures aren’t loading
    correctly. I’m not sure why but I think its a linking issue.
    I’ve tried it in two different browsers and both show the
    same outcome.

    Reply
  • bit.ly says:
    March 23, 2022 at 3:20 pm

    Hey there just wanted to give you a quick heads up.
    The words in your content seem to be running off the screen in Safari.
    I’m not sure if this is a format issue or something
    to do with web browser compatibility but I thought
    I’d post to let you know. The layout look great though!
    Hope you get the issue resolved soon. Cheers

    Reply
  • bit.ly says:
    March 24, 2022 at 1:12 am

    Howdy! This post couldn’t be written any better! Looking at this article reminds me of my previous roommate!
    He constantly kept talking about this. I’ll send this post
    to him. Fairly certain he’s going to have a very good read.
    Many thanks for sharing!

    Reply
  • http://tinyurl.com says:
    March 24, 2022 at 2:56 pm

    Howdy superb website! Does running a blog similar to this require a great
    deal of work? I’ve very little knowledge of programming but I was hoping to start my own blog soon. Anyways, if you have any suggestions or tips for new blog owners please share.
    I understand this is off topic but I simply wanted to ask.

    Many thanks!

    Reply
  • zoritoler imol says:
    April 4, 2022 at 1:45 pm

    I’ll immediately grasp your rss as I can not to find your email subscription link or newsletter service. Do you’ve any? Kindly permit me realize in order that I could subscribe. Thanks.

    Reply
  • houston junk car buyer says:
    May 5, 2022 at 12:57 pm

    Hi there it’s me, I am also visiting this site regularly,
    this site is actually good and the people are actually sharing good thoughts.

    Reply
    • Admin says:
      May 8, 2022 at 7:20 am

      thanks

      Reply
  • Pingback: How To Make Python QR Code Generator - rocoderes

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

- Advertisement -

You Might Also Like

Rock Paper Scissors Python

How To Make Rock Paper Scissors Python Game 2022

November 26, 2022
python QR code generator

How To Make Python QR Code Generator

November 25, 2022
Countdown Calendar using Python Tkinter

How to Make Countdown Calendar using Python Tkinter

November 24, 2022
binary search algorithm in python

What is Binary Search Algorithm in python?

November 23, 2022
rocoderesrocoderes
Follow US

Copyright © 2022 All Right Reserved By Rocoderes

  • Home
  • About us
  • Contact us
  • Disclaimer
Join Us!

Subscribe to our newsletter and never miss our latest news, podcasts etc.

Zero spam, Unsubscribe at any time.
Welcome Back!

Sign in to your account

Lost your password?