简体   繁体   English

如何使用tkinter在Python中检测彼此相邻的矩形

[英]How to detect rectangles next to each other in Python using tkinter

I am new to tkinter but am trying to make a program where a rectangle AI will navigate a maze of other rectangles, however I'm not sure what is the best way to detect the rectangles around my AI so it can find openings and figure out where to go (like look left and right to see if there are rectangles) 我是tkinter的新手,但是我正在尝试创建一个程序,其中矩形AI会在其他矩形的迷宫中导航,但是我不确定检测AI周围矩形的最佳方法是什么,以便能找到开口并找出去哪儿(就像左右看看是否有矩形)

I tried making collisions but I could not get that to work very well, but I'm also not making each maze wall into it's own variable so I don't know how to check if it's coordinates relate to the AI's. 我尝试进行碰撞,但是无法使其正常工作,但是我也没有将每个迷宫墙都变成它自己的变量,所以我不知道如何检查它的坐标是否与AI有关。 So maybe see if there is anything "AIPossition_x + 5" or something similar? 因此,也许看看是否有任何“ AIPossition_x + 5”或类似的东西?

This is the code I'm using now 这是我现在使用的代码

maze_create_x = 25
maze_create_y = 25

for char in maze:
    if char == "+":
        canvas.create_rectangle(maze_create_x, maze_create_y, maze_create_x + 25, maze_create_y + 25, fill="black")
    elif char == "/":
        maze_create_y += 25
        maze_create_x = 0
    maze_create_x += 25


robot = canvas.create_rectangle(80, 55, 95, 70, fill="blue")

I want the "robot" AI to be able to see if there is a rectangle in front, left, or right of it but I'm not sure where to even start. 我希望“机器人” AI能够看到它的前面,左边或右边是否有矩形,但是我不确定从哪里开始。 Thanks for all the help! 感谢您的所有帮助!

You can use canvas.find_overlapping(x1, y1, x2, y2) were (x1, y1, x2, y2) are the coordinates of rectangle in which you want to know if there are items. 您可以使用canvas.find_overlapping(x1, y1, x2, y2)是(x1,y1,x2,y2)是矩形的坐标,您想知道其中是否有项目。 The tuple of the ids of the items overlapping this rectangle is returned. 返回与该矩形重叠的项的id的元组。

For example, to check on the right of the AI: 例如,要检查AI的右侧:

x1, y1, x2, y2 = canvas.coords(robot)
if canvas.find_overlapping(x1 + 25, y1, x2 + 25, y2):
    print('There is a wall on the right')
else:
    print('The way is clear on the right')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM