The Wayback Machine - https://web.archive.org/web/20241001184827/https://www.geeksforgeeks.org/flipping-tiles-memory-game-using-python3/
Open In App

Flipping Tiles (memory game) using Python3

Last Updated : 13 Sep, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Flipping tiles game can be played to test our memory. In this, we have a certain even number of tiles, in which each number/figure has a pair. The tiles are facing downwards, and we have to flip them to see them. In a turn, one flips 2 tiles, if the tiles match then they are removed. If not then they are flipped and placed back in the position. We keep on doing this until all the tiles have been matched and removed.

To simulate this game in Python, we will be using the turtle and random modules.

Approach:

  1. Import turtle and random module. Python offers the random module that can generate random numbers, and turtle module is being used in making different objects.
  2. Set the screen and also choose the background color of your output screen window.
  3. Define a function for making a square for the base of your game.
  4. Define a function to keep a check of the index number.
  5. Define a function to make your game user-friendly i.e user click.
  6. Write a function to draw tiles on the square base defined in step 3.
  7. Finally use the shuffle() function to shuffle the numbers placed on the square tiles in the square box.

Python3




# import modules
from random import *
from turtle import *
 
# set the screen
screen = Screen()
 
#choose background color
screen.bgcolor("yellow")
 
# define the function
# for creating a square section
# for the game
def Square(x, y):
    up()
    goto(x, y)
    down()
    color('white', 'green')
    begin_fill()
    for count in range(4):
        forward(50)
        left(90)
    end_fill()
 
# define function to
# keep a check of index number
def Numbering(x, y):
    return int((x + 200) // 50 + ((y + 200) // 50) * 8)
 
# define function
def Coordinates(count):
    return (count % 8) * 50 - 200, (count // 8) * 50 - 200
 
# define function
# to make it interactive
# user click
def click(x, y):
    spot = Numbering(x, y)
    mark = state['mark']
 
    if mark is None or mark == spot or tiles[mark] != tiles[spot]:
        state['mark'] = spot
    else:
        hide[spot] = False
        hide[mark] = False
        state['mark'] = None
 
def draw():
    clear()
    goto(0, 0)
    stamp()
 
    for count in range(64):
        if hide[count]:
            x, y = Coordinates(count)
            Square(x, y)
 
    mark = state['mark']
 
    if mark is not None and hide[mark]:
        x, y = Coordinates(mark)
        up()
        goto(x + 2, y)
        color('black')
        write(tiles[mark], font=('Arial', 30, 'normal'))
 
    update()
    ontimer(draw, 10)
 
tiles = list(range(32)) * 2
state = {'mark': None}
hide = [True] * 64
 
# for shuffling the
# numbers placed inside
# the square tiles
shuffle(tiles)
tracer(False)
onscreenclick(click)
draw()
done()


Output:



Previous Article
Next Article

Similar Reads

Create a Memory Puzzle Game Using Pygame
Playing memory puzzle games provides entertainment and boosts mental abilities such as focus and memory recall. This article guides you through the steps to create a straightforward memory puzzle game using the Python Pygame Library. After completing the article, you will have a fully functioning game where players try to match pairs of game pieces
10 min read
How to show a timer on screen using arcade in Python3?
Prerequisite: Arcade library Arcade is a modern framework, which is used to make 2D video games. In this, article, you will learn how to show an on-screen timer using the arcade module of Python. Displaying a timer on screen is not tough job, just follow the below steps:- Step 1: First of all import the arcade module of Python C/C++ Code Step 2: De
2 min read
Making an object jump with gravity using arcade module in Python3
The Arcade library is a modern Python Module used widely for developing 2D video games with compelling graphics and sound. Arcade is an object-oriented library. It can be installed like any other Python Package. Now, it’s up to the necessity of the developer, what type of game, graphics, and sound he/she wants to use using this toolkit. So, in this
4 min read
Draw a parabola using Arcade in Python3
Arcade is a Python library which is used for developing 2Dimensional Games. Arcade needs support for OpenGL 3.3+. In arcade, basic drawing does not require knowledge on how to define functions or classes or how to do loops, simply we have inbuilt functions for drawing primitives. Arcade inbuilt function for drawing parabola:- 1. arcade.draw_parabol
3 min read
Draw a circle using Arcade in Python3
The arcade library is a high-tech Python Package with advanced set of tools for making 2D games with gripping graphics and sound. It is Object-oriented and is especially built for Python 3.6 and above versions. Arcade inbuilt functions to draw circle :- 1. arcade.draw_circle_outline( ) : This function is used to draw the outline of a circle. Syntax
3 min read
PYGLET – Flipping Window Buffer
In this article we will see how we can flip the window buffer in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a "heavyweight" object occupying operating system resources. Windows may appear as floating regions or can be set to fill an entire
2 min read
Python program for biased coin flipping simulation
Flipping a biased coin is an interesting exercise that combines probability theory with programming. There is a fixed probability of getting Head and Tails on a Biased coin, though it is not a 50/50 chance. In this article, we will show you the Python program to simulate flipping a biased coin. Python Program for biased coin-flipping simulationStep
2 min read
Flipping the boolean values in a Python list
Flipping boolean values in a list involves changing True to False and False to True. This operation is straightforward in Python and can be accomplished using various methods. In this article, we'll explore different techniques to flip boolean values in a list in Python. 1. Using List ComprehensionList comprehension is a concise way to create lists
3 min read
Arcade inbuilt functions to draw polygon in Python3
The arcade library is a high-tech Python Package with advanced set of tools for making 2D games with gripping graphics and sound. It is Object-oriented and is especially built for Python 3.6 and above versions. Arcade has two inbuilt functions for drawing a polygon: 1. arcade.draw_polygon_outline( ) : This function is used to draw the outline of th
2 min read
How to write Comments in Python3?
Comments are text notes added to the program to provide explanatory information about the source code. They are used in a programming language to document the program and remind programmers of what tricky things they just did with the code and also help the later generation for understanding and maintenance of code. The compiler considers these as
4 min read
Python2 vs Python3 | Syntax and performance Comparison
Python 2.x has been the most popular version for over a decade and a half. But now more and more people are switching to Python 3.x. Python3 is a lot better than Python2 and comes with many additional features. Also, Python 2.x is becoming obsolete this year. So, it is now recommended to start using Python 3.x from now-onwards. Still in dilemma? Ev
4 min read
How to install Python3 and PIP on Godaddy Server?
GoDaddy VPS is a shared server that provides computational services, databases, storage space, automated weekly backups, 99% uptime, and much more. It’s a cheaper alternative to some other popular cloud-based services such as AWS, GPC, and Azure. Python is an open-source, cross-platform, high-level, general-purpose programming language created by G
2 min read
Automate the Conversion from Python2 to Python3
We can convert Python2 scripts to Python3 scripts by using 2to3 module. It changes Python2 syntax to Python3 syntax. We can change all the files in a particular folder from python2 to python3. Installation This module does not come built-in with Python. To install this type the below command in the terminal. pip install 2to3 Syntax: 2to3 [file or f
1 min read
Convert String to Double in Python3
Given a string and our task is to convert it in double. Since double datatype allows a number to have non -integer values. So conversion of string to double is the same as the conversion of string to float This can be implemented in these two ways 1) Using float() method C/C++ Code str1 = "9.02" print("This is the initial string:
2 min read
Introduction to Python3
Python is a high-level general-purpose programming language. Python programs generally are smaller than other programming languages like Java. Programmers have to type relatively less and indentation requirements of the language make them readable all the time. Note: For more information, refer to Python Programming Language Learn Python 3 from beg
3 min read
Why PyPy3 is preferred over Python3?
"If you want your code to run faster, you should probably just use PyPy." -- Guido van Rossum (creator of Python) If you have ever coded in Python, you know how much slower it is compared to some of the other popular programming languages. In most of the online code judges, the time limit of Python is as much a 5 times more than that of C and more
3 min read
How to Install Python3 on AWS EC2?
AWS or Amazon web services is a cloud service platform that provides on-demand computational services, databases, storage space, and many more services. EC2 or Elastic Compute Cloud is a scalable computing service launched on the AWS cloud platform. In simpler words, EC2 is nothing but a virtual computer on which we can perform all our tasks and we
3 min read
Different Input and Output Techniques in Python3
An article describing basic Input and output techniques that we use while coding in python. Input Techniques 1. Taking input using input() function -> this function by default takes string as input. Example: C/C++ Code #For string str = input() # For integers n = int(input()) # For floating or decimal numbers n = float(input()) 2. Taking Multipl
3 min read
New '=' Operator in Python3.8 f-string
Python have introduced the new = operator in f-string for self documenting the strings in Python 3.8.2 version. Now with the help of this expression we can specify names in the string to get the exact value in the strings despite the position of the variable. Now f-string can be defined as f'{expr=}' expression. We can specify any required name in
1 min read
Positional-only Parameter in Python3.8
Python introduces the new function syntax in Python3.8.2 Version, Where we can introduce the / forward slash to compare the positional only parameter which comes before the / slash and parameters that comes after * is keyword only arguments. Rest of the arguments that are come between / and * can be either positional or keyword type of argument. Th
2 min read
Itertools in Python3
Itertools is a module in Python, it is used to iterate over data structures that can be stepped over using a for-loop. Such data structures are also known as iterables. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra. Why to use ? This module incorporates functions that
3 min read
Setting python3 as Default in Linux
Python 2 support ended on 1-January-2020, and many major projects already signed the Python 3 Statement that declares that they will remove Python 2 support. However many of us prefer to code on python interpreter for tiny code snippets, instead of making .py files. And when we fire command 'python' on the terminal, interpreter of python2 gets laun
1 min read
How to print spaces in Python3?
In this article, we will learn about how to print space or multiple spaces in the Python programming language. Spacing in Python language is quite simple than other programming language. In C languages, to print 10 spaces a loop is used while in python no loop is used to print number of spaces. Following are the example of the print spaces: Example
2 min read
How to use Variables in Python3?
Variable is a name for a location in memory. It can be used to hold a value and reference that stored value within a computer program. the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to the variables, you can store integers, strings, decimals, complex in these vari
3 min read
What is Three dots(...) or Ellipsis in Python3
Ellipsis is a Python Object. It has no Methods. It is a singleton Object i.e. , provides easy access to single instances. Various Use Cases of Ellipsis (...): Default Secondary Prompt in Python interpreter.Accessing and slicing multidimensional Arrays/NumPy indexing.In type hinting.Used as Pass Statement inside Functions.Default Secondary Prompt in
3 min read
How to create an instance of a Metaclass that run on both Python2 and Python3?
Metaclasses are classes that generate other classes. It is an efficient tool for class verification, to prevent sub class from inheriting certain class function, and dynamic generation of classes. Here we will discuss how to create an instance of a Metaclass that runs on both Python 2 and Python 3. Before delving into it, let's go through the code
3 min read
Arcade inbuilt functions to draw point(s) in Python3
The Arcade library is a modern Python Module used widely for developing 2D video games with compelling graphics and sound. Arcade is an object-oriented library. It can be installed like any other Python Package. In this article, we will learn what are the arcade inbuilt functions to draw point. Arcade library is a modern framework, which makes draw
3 min read
How to copy file in Python3?
Prerequisites: Shutil When we require a backup of data, we usually make a copy of that file. Python supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files. Here we will learn how to copy a file using Python3. Method 1 : Using shutil library shutil libra
2 min read
How to Install Pytest For Python3 On MacOS?
The pytest framework is used to write small tests simple, but it can also handle complex functional testing for applications and libraries. The tests are expressive and readable. Or we can say that this framework is used to write test codes with the help of Python language. It is generally used to write test codes for APIs. Some of the features of
2 min read
How to Install Pytest For Python3 On Linux?
The pytest module in Python or a testing framework. It is used to write small and simple tests cases for databases, APIs, etc, but it can also handle complex functional testing for applications and libraries. The tests are definitive and legible. Or we can say that this module is used to write test codes with the help of Python language. Some impor
2 min read
Practice Tags :