Python 使正方形不重叠的成功方法

Python 使正方形不重叠的成功方法,python,tkinter,Python,Tkinter,我是一个新手程序员,4个月前开始使用python。一段时间以来,我一直试图让我的方块不接触,但我没有足够的技巧知道如何…有人有任何关于这方面的建议吗 from tkinter import * from random import * root = Tk() ## Creates canvas that will be used to create squares canvas = Canvas(root, width=3000, height=3000) canvas.pack(fill=

我是一个新手程序员,4个月前开始使用python。一段时间以来,我一直试图让我的方块不接触,但我没有足够的技巧知道如何…有人有任何关于这方面的建议吗

from tkinter import *
from random import *

root = Tk()

## Creates canvas that will be used to create squares
canvas = Canvas(root, width=3000, height=3000)
canvas.pack(fill=BOTH)

#will keep square at a max size of 30
squareSize = 30
squareMAX = 200
square = 0
square2 = 0
## when squares are created, this array will allow them to randomly choose a color
arrayColors =["blue","green","yellow","red","white","black","cyan","magenta","purple","orange"]


#Coordinate plane
# we need an atleast one array

array = [square]


while square < squareMAX:
    ## REPRESENTS THE TOP LEFT CORNER OF THE SQUARE
    x = randrange(0, 1200)
    y = randrange(0, 650)
    i = array
    abs(squareSize)
    square = canvas.create_rectangle(x, y, x + squareSize, y + squareSize, fill=arrayColors[randrange(0, 8)])
    square = square + 1
## I need to find a way to store squares that way the newly generated squares won't overlap, perhaps using array. Append
## to store the remove squares that way we can put them back on the grid without touching.

root.mainloop()

##abs is use to compare the distance between two squares
从tkinter导入*
从随机导入*
root=Tk()
##创建将用于创建正方形的画布
画布=画布(根,宽度=3000,高度=3000)
canvas.pack(fill=BOTH)
#将保持最大尺寸为30的正方形
平方尺寸=30
最大平方=200
平方=0
平方2=0
##创建正方形时,此阵列将允许它们随机选择颜色
阵列颜色=[“蓝色”、“绿色”、“黄色”、“红色”、“白色”、“黑色”、“青色”、“洋红”、“紫色”、“橙色”]
#坐标平面
#我们需要至少一个阵列
数组=[平方]
当平方<平方最大值时:
##表示正方形的左上角
x=randrange(01200)
y=randrange(0650)
i=数组
abs(平方尺寸)
正方形=画布。创建矩形(x,y,x+squareSize,y+squareSize,fill=ArrayColor[randrange(0,8)])
平方=平方+1
##我需要找到一种方法来存储正方形,这样新生成的正方形就不会重叠,也许可以使用数组。追加
##为了存储删除的方块,我们可以将它们放回网格上,而无需触摸。
root.mainloop()
##abs用于比较两个正方形之间的距离
结果:

画布小部件有一个
查找重叠(x1,y1,x2,y2)
方法,该方法返回一个元组,其中包含与矩形(x1,y1,x2,y2)重叠的所有项。因此,每次绘制(x,y)坐标时,请检查新正方形是否与现有正方形重叠。如果是这样,只需重新绘制(x,y),直到没有重叠的正方形

这里是与创建正方形相对应的代码:

square = 0
while square < squareMAX:
    x = randrange(0, 1200)
    y = randrange(0, 650)
    while canvas.find_overlapping(x, y, x + squareSize, y + squareSize):
        x = randrange(0, 1200)
        y = randrange(0, 650)
    square = canvas.create_rectangle(x, y, x + squareSize, y + squareSize, fill=choice(arrayColors))
    square += 1
square=0
当平方<平方最大值时:
x=randrange(01200)
y=randrange(0650)
在画布上查找重叠(x,y,x+squareSize,y+squareSize):
x=randrange(01200)
y=randrange(0650)
正方形=画布。创建_矩形(x,y,x+squareSize,y+squareSize,fill=choice(阵列颜色))
平方+=1
备注:要随机选择列表中的项目,您可以使用模块
random
中的
choice
功能。所以
choice(arrayColors)
相当于
arrayColors[randrange(0,8)]