Advertisement
here2share

# Tk_Gravity.py

Oct 19th, 2016
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.46 KB | None | 0 0
  1. # Tk_Gravity.py
  2.  
  3. from Tkinter import *
  4. import random
  5. import time
  6.  
  7. root = Tk()
  8. root.resizable(0,0)
  9.  
  10. ww = 500
  11. hh = 400
  12.  
  13. canvas = Canvas(root, width=ww, height=hh)
  14.  
  15. def ready():
  16.     canvas.create_text(ww/2, hh/2-60, text='Click Here', font=("Helvetica", "32"),
  17.         anchor=CENTER, fill='red')
  18. ready()
  19. canvas.pack()
  20.  
  21. root.wm_title("Gravity")
  22.  
  23. n = 120
  24. x = [None]*n
  25. y = [None]*n
  26. vy = [None]*n
  27. vx = [None]*n
  28. id = [None]*n
  29. g = 0.05
  30. cor = 0.7
  31. fr = 0.95
  32. r = 16
  33. xx = 300
  34. yy = 100
  35.  
  36. def init():
  37.     canvas.delete(ALL)
  38.     for i in range(n):
  39.         # canvas.delete(id[i])
  40.         x[i] = xx
  41.         y[i] = yy
  42.         vx[i] = 16*(random.random()-.5)
  43.         vy[i] = 2*(random.random()-.5)
  44.         id[i] = canvas.create_oval(300-8, 25, 300+8, 25+16, fill="red")
  45.  
  46. def updateY(i):
  47.     if ((y[i]+r) < hh):
  48.         vy[i] += g
  49.     else:
  50.         vy[i] = -vy[i]*cor
  51.         vx[i] *= fr
  52.     y[i] += vy[i]
  53.     if ((y[i]+r) > hh):
  54.         y[i] = hh-r
  55. #
  56. def updateX(i):
  57.     if x[i]+r >= ww or x[i]-r <= 0:
  58.         vx[i] = -vx[i]*cor
  59.     x[i] += vx[i]
  60.     if x[i]+r > ww:
  61.         x[i] = ww-r
  62.     elif x[i]-r < 0:
  63.         x[i] = r
  64. #
  65. def on_canvas_click(ev):
  66.     global action
  67.     init()
  68.     action=1
  69. #
  70. canvas.bind('<Button-1>', on_canvas_click)
  71.  
  72. start=time.time()
  73. go=1
  74. action=0
  75. while go:
  76.     if action:
  77.         inMotion=''
  78.         if time.time() > start + 0.015:
  79.             start=time.time()
  80.             for i in range(n):
  81.                 updateX(i)
  82.                 updateY(i)
  83.                 if abs(vx[i])+abs(vy[i]) > 0.2:
  84.                     canvas.move(id[i], vx[i], vy[i])
  85.                     inMotion=True
  86.             if not inMotion: ready()
  87.                
  88.     root.update()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement