Advertisement
TheCDC

circular_motion_tracing.py

Feb 1st, 2015
441
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.86 KB | None | 0 0
  1. # circular_motion_tracing.py
  2.  
  3.  
  4. # Draw Circles!
  5. # by Christopher Chen ([email protected])
  6. # Dependencies:
  7. #   Python 3
  8. #   Pygame
  9.  
  10.  
  11. # Bonus Features:
  12. #   Automatically adjusts fullscren window size to screen resolution
  13.  
  14. # Place this program 2 folders deep as it needs/will create a screenshot folder, i.e.
  15. # Awesome Program
  16. # |-source
  17. #   |-circular_motion_tracing.py
  18. # |-Masterpieces
  19. #   |-[screenshots]
  20.  
  21. # Controls:
  22.     # Move the mouse to draw circles.
  23.     # hold SHIFT to make drawing persistent
  24.     # hold SPACE to prevent the circles from filling
  25.     # press F12 to save a screenshot
  26.     # press q to quit
  27.  
  28.  
  29. #!/usr/bin/python3
  30. import pygame, time, sys, random, os, os.path, math, pygame.gfxdraw
  31. from pygame.locals import *
  32.  
  33. pygame.init()
  34.  
  35. # check command line options
  36. welcome_str = """Run with -nogfx to disable fancy graphics, which includes:
  37. - antialased lines/circles"""
  38. print(welcome_str)
  39.  
  40. if "-nogfx" in sys.argv:
  41.     FANCY_GRAPHICS = False
  42. else:
  43.     FANCY_GRAPHICS = True
  44.  
  45. infoObj = pygame.display.Info()
  46.  
  47. WIDTH = int(infoObj.current_w)
  48. HEIGHT = int(infoObj.current_h)
  49. SIZE  = (WIDTH,HEIGHT)
  50. DISPLAYSURF = pygame.display.set_mode((WIDTH,HEIGHT),pygame.FULLSCREEN)
  51.  
  52. RATE = 60
  53. FRAMEDELAY = 1/RATE
  54.  
  55. pos_hist = []
  56. # list of fading circle objects
  57. fading_circles = []
  58. # list of live circle objects
  59. live_circles = []
  60. framecount = 0
  61. trail_enabled = False
  62. max_hist = 12
  63. WHITE = (255,255,255)
  64. fade_enabled = True
  65. pygame.display.set_caption('Draw Circles!')
  66. key_dict = {}
  67. cam_background = False
  68.  
  69. paused = False
  70. #~ cam = pygame.camera.Camera(pygame.camera.list_cameras()[0], SIZE)
  71. #~ cam.start()
  72. #~ snapshot = pygame.surface.Surface((640,480), 0, DISPLAYSURF)
  73.  
  74. class FadingCircle:
  75.     def __init__(self,x,y,r):
  76.         self.x = x
  77.         self.y = y
  78.         self.r = r
  79.         self.killflag = False
  80.         if fade_enabled == True:
  81.             self.shrinkstep = (r/RATE)**2
  82.         else:
  83.             self.shrinkstep = r
  84.         self.RANDCOLOR = (random.randint(0,255),random.randint(0,255),random.randint(0,255))
  85.        
  86.     def update(self):
  87.         if self.r > 1 :
  88.             self.RANDCOLOR = (random.randint(0,255),random.randint(0,255),random.randint(0,255))
  89.             # check if circle coordinates, etc. are valid for aacircle
  90.             if FANCY_GRAPHICS and not (self.r < 1 or self.x > 32000 or self.y > 32000 or self.r > 1000):
  91.                 pygame.gfxdraw.aacircle(DISPLAYSURF, int(self.x), int(self.y), int(self.r), self.RANDCOLOR)
  92.             else:
  93.                 pygame.draw.circle(DISPLAYSURF, self.RANDCOLOR, (int(self.x), int(self.y)), int(self.r), int(1))
  94.         elif self.r <= 1:
  95.             self.killflag = True
  96.         self.r -= math.ceil(self.shrinkstep)
  97.         # print(self.r)
  98.        
  99.     def should_die(self):
  100.         return self.killflag
  101.  
  102.        
  103. class LiveCircle:
  104.     """
  105.     Expects two points.
  106.     """
  107.     def __init__(self,p1,p2):
  108.         self.x1,self.y1 = p1
  109.         self.x2,self.y2 = p2
  110.         try:
  111.             self.circle = find_circle([(self.x1,self.y1),(self.x2,self.y2),(pos_hist[-1],pos_hist[-2])])
  112.         except:
  113.             pass
  114.  
  115.     def update(self):
  116.         self.circle = find_circle([(self.x1,self.y1),(self.x2,self.y2),(pos_hist[-1],pos_hist[-2])])
  117.         self.x = self.circle['x']
  118.         self.y = self.circle['y']
  119.         self.z = self.circle['z']
  120.         self.RANDCOLOR(random.randint(0,255),random.randint(0,255),random.randint(0,255))
  121.         pygame.draw.circle(DISPLAYSURF,self.RANDCOLOR,(int(self.x),int(self.y)),int(self.r),1)
  122.  
  123. def update_pos():
  124.     pos_hist.append(pygame.mouse.get_pos())
  125.  
  126.     if len(pos_hist) >= max_hist + 1:
  127.         pos_hist.pop(0)
  128.     try:
  129.         # if pos_hist[-1] != pos_hist[-2] != pos_hist[-3] :
  130.                 # print(''.join([str(i) for i in pos_hist[-4:-1]]), ' '.join([i for i in dict(zip([key for key in circle.keys()],["{0:2f}".format(v) for v in circle.values()]))])
  131.             # print(''.join([str(i) for i in pos_hist[-4:-1]]),dict(zip([key for key in circle.keys()],["{0:.2f}".format(v) for v in circle.values()])))
  132.     # except IndexError:
  133.     #   print(None)
  134.         pass
  135.     except:
  136.         # print(None)
  137.         print(''.join([str(i) for i in pos_hist[-4:-1]]),None)
  138.  
  139. def find_circle(point_list):
  140.     try:
  141.         x1,x2,x3 = point_list[-1][0],point_list[-2][0],point_list[-3][0]
  142.         y1,y2,y3 = point_list[-1][1],point_list[-2][1],point_list[-3][1]
  143.         k = (-((y2**2-y1**2)*x3-(y3**2-y1**2+x3**2)*x2+x3*x2**2+(y3**2-y2**2+x3**2-x2**2)*x1-(x3-x2)*x1**2))/(2*(-((y2-y1)*x3-(y3-y1)*x2+(y3-y2)*x1)))
  144.         h = (-(y3**2*y2-y3*y2**2-(y3**2-y2**2)*y1+(y3-y2)*y1**2+(y2-y1)*x3**2-(y3-y1)*x2**2+(y3-y2)*x1**2))/(2*(-((y2-y1)*x3-(y3-y1)*x2+(y3-y2)*x1)))
  145.         r = ((x2-h)**2+(y2-k)**2)**(1/2)
  146.         # if r < 1:
  147.         #   r = 1
  148.         # return ((h,k),r)
  149.         return {'x':h,'y':k,'r':r}
  150.     except:
  151.         return None
  152.  
  153.  
  154. def update_key_dict():
  155.     for event in pygame.event.get():
  156.             #~ print(event)
  157.             if event.type == QUIT:
  158.                 pygame.mixer.quit()
  159.                 pygame.quit()
  160.                 sys.exit()
  161.             try:
  162.                 key_dict.update({event.key:event.type})
  163.             except AttributeError:
  164.                 pass
  165.  
  166.  
  167. def getkeystate(k):
  168.     try:
  169.         if key_dict[k] == KEYDOWN:
  170.             return True
  171.         elif key_dict[k] == KEYUP:
  172.             return False
  173.     except:
  174.         key_dict.update({k:KEYUP})
  175.         return False
  176.  
  177. def save_screenshot():
  178.     screeny_dir = os.path.join(os.curdir,"Masterpieces")
  179.     if not os.path.exists(os.path.join(os.curdir,"Masterpieces")):
  180.         os.makedirs(os.path.join(os.curdir,"Masterpieces"))
  181.     pygame.image.save(DISPLAYSURF,os.path.join(screeny_dir, "Masterpiece " + time.strftime("%Y%m%d %H%M%S")+".png"))
  182.  
  183. while True:
  184.     #~ main loop
  185.     #~ calculate circle
  186.  
  187.     update_pos()
  188.  
  189.     #~ handle events
  190.     update_key_dict()
  191.  
  192.     if getkeystate(K_LSHIFT):
  193.         paused = True
  194.     else:
  195.         paused = False
  196.  
  197.     if pygame.mouse.get_pressed()[2] == 1 or getkeystate(K_SPACE):
  198.         fade_enabled = False
  199.     else:
  200.         fade_enabled = True
  201.  
  202.     if not getkeystate(K_c) :
  203.         live_circles = []
  204.  
  205.     if not getkeystate(K_1):
  206.         pass
  207.  
  208.     if getkeystate(K_q) or getkeystate(K_ESCAPE):
  209.         sys.exit()
  210.  
  211.     if getkeystate(K_F12):
  212.         save_screenshot()
  213.  
  214.  
  215.  
  216.     RANDCOLOR = (random.randint(0,255),random.randint(0,255),random.randint(0,255))
  217.  
  218.     circle = find_circle(pos_hist[-1:-4:-1])
  219.  
  220.     try:
  221.         if framecount % 1 <= 1:
  222.             if paused == False:
  223.  
  224.                 DISPLAYSURF.fill((0,0,0))
  225.             fading_circles.append(FadingCircle(circle['x'],circle['y'],circle['r']))
  226.     except TypeError:
  227.         pass
  228.        
  229.     #~ handle list of fading circles
  230.     for index,item in enumerate(fading_circles):
  231.         RANDCOLOR = (random.randint(0,255),random.randint(0,255),random.randint(0,255))
  232.         if item.should_die():
  233.             del fading_circles[index]
  234.  
  235.         item.update()
  236.         #~ try:
  237.             #~ pygame.draw.line(DISPLAYSURF,WHITE,(item.x,item.y),(fading_circles[index+1].x,fading_circles[index+1].y),1)
  238.         #~ except:
  239.             #~ pass
  240.            
  241.     if trail_enabled:
  242.         for index,item in enumerate(pos_hist):
  243.             #~ RANDCOLOR = (random.randint(0,255),random.randint(0,255),random.randint(0,255))
  244.             if trail_enabled:
  245.                 try:
  246.                     # draw a mouse trail
  247.                     pygame.draw.line(DISPLAYSURF,RANDCOLOR,item,pos_hist[index+1],1)
  248.                     #~ pygame.draw.circle(DISPLAYSURF,RANDCOLOR,item,1)
  249.        
  250.                 except IndexError:
  251.                     pass
  252.    
  253.  
  254.     pygame.display.update()
  255.  
  256.     framecount += 1
  257.     #~ wait to draw next frame
  258.     time.sleep(FRAMEDELAY)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement