Skip to content Skip to sidebar Skip to footer

Successful Way For Squares To Not Overlap

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

Solution 1:

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=0whilesquare<squareMAX:x=randrange(0,1200)y=randrange(0,650)whilecanvas.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

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)].

Post a Comment for "Successful Way For Squares To Not Overlap"