方块不重叠的成功方法

时间:2017-04-30 02:30:38

标签: 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=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

结果: Picture of Squares

1 个答案:

答案 0 :(得分:0)

Canvas小部件有一个find_overlapping(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

备注:要随机选择列表中的项目,您可以使用模块choice中的random函数。因此choice(arrayColors)相当于arrayColors[randrange(0, 8)]