Advertisement
here2share

# Tk_Random_Island.py

Nov 14th, 2020
1,527
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.75 KB | None | 0 0
  1. # Tk_Random_Island.py
  2.  
  3. from Tkinter import *
  4. from PIL import Image, ImageTk
  5. import random
  6. import math
  7. import time
  8. ww = 600
  9. hh = 600
  10. ww2 = ww/2
  11. hh2 = hh/2
  12.  
  13. root = Tk()
  14. root.title("Tk Random Island")
  15. root.geometry("%dx%d+-10+0"%(ww,hh))
  16. canvas = Canvas(root, width=ww, height=hh, bg='royal blue')
  17. canvas.pack()
  18.  
  19. def draw_line(x1,y1,x2,y2): # function to draw line
  20.     xy.append((ww2+x2,hh2+y2))
  21.  
  22. def dist(p1,p2): # Euclidean distance betwen p1 and p2
  23.     return ((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2)**0.5
  24.  
  25. def shoreline(x1,y1,x2,y2,ratio): # recurisve function to draw the shoreline
  26.     L = dist((x1,y1),(x2,y2))
  27.     if L <= 1: # distance is short enough, directly draw the line
  28.         draw_line(x1,y1,x2,y2)
  29.         return
  30.     rs = ratio + random.uniform(-0.1,0.1) # let ratio flucuate slightly around the chosen value
  31.     rs = max(0.5,rs) # make sure ratio stays at least half of the length
  32.     midx = (x1+x2)/2 # center of ellipse
  33.     midy = (y1+y2)/2    
  34.     rx = L/2 + (2*rs-1)/2*L # width of ellipse
  35.     ry = ((L*rs)**2 - (L/2)**2)**0.5 # height of ellipse
  36.     theta = math.atan2(y2-y1,x2-x1) # the tilt angle of ellipse
  37.     alpha = random.uniform(math.pi*0.3,math.pi*0.7) # flucuate around math.pi/2
  38.     x3 = rx*math.cos(alpha)*math.cos(theta) - ry*math.sin(alpha)*math.sin(theta) + midx # parametric equation for ellipse
  39.     y3 = rx*math.cos(alpha)*math.sin(theta) + ry*math.sin(alpha)*math.cos(theta) + midy
  40.     shoreline(x1,y1,x3,y3,ratio) # do this recursively on each segment
  41.     shoreline(x3,y3,x2,y2,ratio)
  42.  
  43. while 1:
  44.     xy = []
  45.     canvas.delete('all')
  46.     shoreline(-200,0,200,0,0.55) # call recursion
  47.     shoreline(200,0,-200,0,0.55) # call recursion
  48.  
  49.     canvas.create_polygon(xy, fill="forest green", outline="tan", width=5)
  50.     canvas.update()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement