正方形不重叠的成功方法 [英] Successful way for squares to not overlap
问题描述
我是 4 个月前开始使用 Python 的新手程序员.一段时间以来,我一直试图让我的方块不接触,但是我不够熟练,不知道如何...有人对此有任何建议吗?
I am a novice programmer who started python 4 months ago. For awhile now I've been trying to get my squares not to touch, however I'm not skillful enough to know how...anyone have any suggestions on going about this?
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
结果:
推荐答案
Canvas 小部件有一个 find_overlapping(x1, y1, x2, y2)
方法,该方法返回一个元组,其中包含与矩形 (x1, y1, x2, y2).因此,每次绘制 (x,y) 坐标时,请检查新方块是否会与现有方块重叠.如果是这样,就重画(x,y),直到没有重叠的正方形.
The Canvas widget has a find_overlapping(x1, y1, x2, y2)
method that returns a tuple containing all items that overlap the rectangle (x1, y1, x2, y2). So each time you draw (x,y) coordinates, check whether the new square will overlap existing ones. If it is the case, just redraw (x,y) until there is no overlapping square.
这里是创建方块对应的代码:
Here the code corresponding to the creation of the squares:
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
备注:要随机选择列表中的一项,可以使用random
模块中的函数choice
.所以choice(arrayColors)
等价于arrayColors[randrange(0, 8)]
.
Remark: to randomly choose an item in a list, you can use the function choice
from the module random
. So choice(arrayColors)
is equivalent to arrayColors[randrange(0, 8)]
.
这篇关于正方形不重叠的成功方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!