Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Tk_CircleVsCircle_Collision.py
- from Tkinter import *
- from PIL import Image, ImageTk, ImageDraw
- import random
- import math
- imgx = 800
- imgy = 600
- root = Tk()
- root.title("Tk CircleVsCircle Collision")
- root.geometry("%dx%d+0+0"%(imgx,imgy))
- canvas = Canvas(root, width=imgx, height=imgy)
- canvas.grid()
- pic = Image.new("RGB", (imgx, imgy))
- draw = ImageDraw.Draw(pic)
- n = 12
- p = 20
- crMax = int(min(imgx - 1, imgy - 1) / 4) # max circle radius
- crMin = 40 # min circle radius
- # create circular obstacle(s)
- cxList = []
- cyList = []
- crList = []
- for i in range(n):
- while(True): # circle(s) must not overlap
- cr = random.randint(crMin, crMax) # circle radius
- cx = random.randint(cr + p, imgx - p - cr) # circle center x
- cy = random.randint(cr + p, imgy - p - cr) # circle center y
- flag = True
- if i > 0:
- for j in range(i):
- if math.hypot(cx - cxList[j], cy - cyList[j]) < cr + crList[j] + 30:
- flag = False
- break
- if flag == True:
- break
- draw.ellipse((cx - cr, cy - cr, cx + cr, cy + cr), fill='green')
- cxList.append(cx)
- cyList.append(cy)
- crList.append(cr)
- # initial location of the ball must be outside of the circle(s)
- while(True):
- x = float(random.randint(0, imgx - 1))
- y = float(random.randint(0, imgy - 1))
- flag = False
- for i in range(n):
- if math.hypot(x - cxList[i], y - cyList[i]) <= crList[i]:
- flag = True
- break
- if flag == False:
- break
- # initial direction of the ball
- a = 2.0 * math.pi * random.random()
- s = math.sin(a)
- c = math.cos(a)
- while 1:
- pic.putpixel((int(x), int(y)), (255, 255, 255))
- xnew = x + c
- ynew = y + s
- # reflection from the walls
- if xnew < 0 or xnew > imgx - 1:
- c = -c
- xnew = x
- if ynew < 0 or ynew > imgy - 1:
- s = -s
- ynew = y
- # reflection from the circle(s)
- for i in range(n):
- if math.hypot(xnew - cxList[i], ynew - cyList[i]) <= crList[i]:
- # angle of the circle point
- ca = math.atan2(ynew - cyList[i], xnew - cxList[i])
- # reversed collision angle of the ball
- rca = math.atan2(-s, -c)
- # reflection angle of the ball
- rab = rca + (ca - rca) * 2
- s = math.sin(rab)
- c = math.cos(rab)
- xnew = x
- ynew = y
- x = xnew
- y = ynew
- imgTk = ImageTk.PhotoImage(pic)
- canvas.create_image(0, 0, anchor=NW, image=imgTk)
- canvas.update()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement