0

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

Result: Picture of Squares

j_4321
  • 15,431
  • 3
  • 34
  • 61

1 Answers1

0

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

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

j_4321
  • 15,431
  • 3
  • 34
  • 61