python - 在 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):
...
解决方案
就像是:
# 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。您甚至可以返回空闲网格位置的方向以供以后使用(我想您将需要它!)。
使用您当前的设置进行这项工作应该是直截了当的。
希望这可以帮助!
推荐阅读
- php - 未找到 Mobile_WS_Controller
- javascript - 如何将新数据输入推送到列表顶部
- django - 如何在 Django 中正确设置 AJAX
- javascript - 使用快速路由显示 React 页面
- javascript - 我从 for 循环中获得的数组总和返回 NaN (Javascript)
- javascript - ReactJS — 创建 Refs 并访问 DOM 元素以使用 fullpage.js
- nestjs - 如果存在 uid 选项,则返回特定用户,否则返回整个用户列表
- glsl - OpenGL:将 RGBA 转换为浮点数
- swift - 从 Firestore 快照更新 ChatModel 字典中的现有项目
- python - 如何使用 python boto3 将文件和文件夹从一个 S3 存储桶复制到另一个 S3