📜  使用 Python3 翻转瓷砖(记忆游戏)

📅  最后修改于: 2022-05-13 01:54:53.026000             🧑  作者: Mango

使用 Python3 翻转瓷砖(记忆游戏)

可以玩翻转瓷砖游戏来测试我们的记忆力。在这里,我们有一定数量的瓷砖,其中每个数字/图形都有一对。瓷砖朝下,我们必须翻转它们才能看到它们。一回合,一个人翻转 2 个瓷砖,如果瓷砖匹配,则将它们移除。如果没有,则将它们翻转并放回原位。我们一直这样做,直到所有的图块都被匹配并移除。

为了用Python模拟这个游戏,我们将使用乌龟和随机模块

方法:

  1. 导入海龟和随机模块。 Python提供了可以生成随机数的 random 模块,turtle 模块被用于制作不同的对象。
  2. 设置屏幕并选择输出屏幕窗口的背景颜色。
  3. 定义一个函数,用于为您的游戏底部制作一个正方形。
  4. 定义一个函数来检查索引号。
  5. 定义一个函数,使您的游戏用户友好,即用户点击。
  6. 编写一个函数,在步骤 3 中定义的方形底座上绘制瓷砖。
  7. 最后使用 shuffle()函数将放置在方块中方块上的数字打乱。
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()


输出: