首页 > 解决方案 > 在 tkinter 中确定网格空间是否为空

问题描述

我有一个 tkinter 项目,我正在尝试编写滑动益智游戏,所以 9 个正方形,8 个编号和 1 个空,如果你点击一个带有数字的,如果它可以移动到空白空间。我使用了 lambda,所以我有坐标,但我不知道如何找到相邻的正方形是否空闲,有没有办法可以做到这一点?任何帮助是极大的赞赏。

def create_grid(event):
    side = int(math.sqrt(int(size.get())))
    for row in range(side):
        for col in range(side):
            button = Button(window, text = number, command=lambda row=row, col=col: click(row, col))
        button.grid(row=row, column=col)

def click(row, col):
...

标签: pythonpython-3.xtkinter

解决方案


就像是:

# create the grid
size = 3
grid = [[i for i in range(j*size, (j + 1) * size)] for j in range(size)]
# check if a there is a free location next to a given coordinate
def is_free(x,y):
    assert x >= 0
    assert y >= 0
    assert x < size
    assert y < size
    up = grid[y-1][x]    if y-1 >= 0 else -1
    down = grid[y+1][x]  if y+1 < size else -1
    left = grid[y][x-1]  if x-1 >= 0 else -1
    right = grid[y][x+1] if x+1 < size else -1
    return not up or not down or not left or not right

首先我们创建一个网格,使用 0 作为空方格。获取当前 x,y 坐标旁边的值(我想在单击时),最后返回我们是否找到任何 0。您甚至可以返回空闲网格位置的方向以供以后使用(我想您将需要它!)。

使用您当前的设置进行这项工作应该是直截了当的。

希望这可以帮助!


推荐阅读