Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from tkinter import *
- from random import randrange as rnd, choice
- root = Tk()
- root.geometry('600x600')
- canv = Canvas(bg='white')
- canv.pack(fill=BOTH,expand=1)
- colors = ('green','red','orange','blue')
- class Rectangle():
- def __init__(self,x,y,w,h):
- self.x1 = x
- self.y1 = y
- self.w = w
- self.h = h
- self.x2 = self.x1+w
- self.y2 = self.y1+h
- self.img = canv.create_rectangle(self.x1,self.y1,self.x2,self.y2)
- self.color = ''
- def intersection(self,other):
- inter = rectanglesintersection(self,other)
- if inter:
- try:
- x1,x2 = inter[0]
- y1,y2 = inter[1]
- canv.create_rectangle(x1,y1,x2,y2,fill='orange',tag='temp')
- return inter
- except:
- return None
- def move(self,x,y):
- self.x1 = x
- self.y1 = y
- self.x2 = x+self.w
- self.y2 = y+self.h
- canv.coords(self.img,self.x1,self.y1,self.x2,self.y2)
- canv.itemconfig(self.img,fill=self.color)
- def pointinline(x,x1,x2):
- return x1 < x < x2
- def linesintersection(x1,x2,xx1,xx2):
- res = []
- if pointinline(x1,xx1-1,xx2+1):
- res.append(x1)
- if pointinline(x2,xx1-1,xx2+1):
- res.append(x2)
- if pointinline(xx1,x1,x2):
- res.append(xx1)
- if pointinline(xx2,x1,x2):
- res.append(xx2)
- return res
- def rectanglesintersection(r1,r2):
- res_x = linesintersection(r1.x1,r1.x2,r2.x1,r2.x2)
- res_y = linesintersection(r1.y1,r1.y2,r2.y1,r2.y2)
- if res_x and res_y:
- return res_x, res_y
- r1 = Rectangle(300,300,130,80)
- r2 = Rectangle(200,200,80,100)
- def mouse_move(event):
- canv.delete('temp')
- r2.move(event.x,event.y)
- print(r2.intersection(r1))
- root.bind('<Motion>',mouse_move)
- mainloop()
Add Comment
Please, Sign In to add comment