Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # circular_motion_tracing.py
- # Draw Circles!
- # by Christopher Chen ([email protected])
- # Dependencies:
- # Python 3
- # Pygame
- # Bonus Features:
- # Automatically adjusts fullscren window size to screen resolution
- # Place this program 2 folders deep as it needs/will create a screenshot folder, i.e.
- # Awesome Program
- # |-source
- # |-circular_motion_tracing.py
- # |-Masterpieces
- # |-[screenshots]
- # Controls:
- # Move the mouse to draw circles.
- # hold SHIFT to make drawing persistent
- # hold SPACE to prevent the circles from filling
- # press F12 to save a screenshot
- # press q to quit
- #!/usr/bin/python3
- import pygame, time, sys, random, os, os.path, math, pygame.gfxdraw
- from pygame.locals import *
- pygame.init()
- # check command line options
- welcome_str = """Run with -nogfx to disable fancy graphics, which includes:
- - antialased lines/circles"""
- print(welcome_str)
- if "-nogfx" in sys.argv:
- FANCY_GRAPHICS = False
- else:
- FANCY_GRAPHICS = True
- infoObj = pygame.display.Info()
- WIDTH = int(infoObj.current_w)
- HEIGHT = int(infoObj.current_h)
- SIZE = (WIDTH,HEIGHT)
- DISPLAYSURF = pygame.display.set_mode((WIDTH,HEIGHT),pygame.FULLSCREEN)
- RATE = 60
- FRAMEDELAY = 1/RATE
- pos_hist = []
- # list of fading circle objects
- fading_circles = []
- # list of live circle objects
- live_circles = []
- framecount = 0
- trail_enabled = False
- max_hist = 12
- WHITE = (255,255,255)
- fade_enabled = True
- pygame.display.set_caption('Draw Circles!')
- key_dict = {}
- cam_background = False
- paused = False
- #~ cam = pygame.camera.Camera(pygame.camera.list_cameras()[0], SIZE)
- #~ cam.start()
- #~ snapshot = pygame.surface.Surface((640,480), 0, DISPLAYSURF)
- class FadingCircle:
- def __init__(self,x,y,r):
- self.x = x
- self.y = y
- self.r = r
- self.killflag = False
- if fade_enabled == True:
- self.shrinkstep = (r/RATE)**2
- else:
- self.shrinkstep = r
- self.RANDCOLOR = (random.randint(0,255),random.randint(0,255),random.randint(0,255))
- def update(self):
- if self.r > 1 :
- self.RANDCOLOR = (random.randint(0,255),random.randint(0,255),random.randint(0,255))
- # check if circle coordinates, etc. are valid for aacircle
- if FANCY_GRAPHICS and not (self.r < 1 or self.x > 32000 or self.y > 32000 or self.r > 1000):
- pygame.gfxdraw.aacircle(DISPLAYSURF, int(self.x), int(self.y), int(self.r), self.RANDCOLOR)
- else:
- pygame.draw.circle(DISPLAYSURF, self.RANDCOLOR, (int(self.x), int(self.y)), int(self.r), int(1))
- elif self.r <= 1:
- self.killflag = True
- self.r -= math.ceil(self.shrinkstep)
- # print(self.r)
- def should_die(self):
- return self.killflag
- class LiveCircle:
- """
- Expects two points.
- """
- def __init__(self,p1,p2):
- self.x1,self.y1 = p1
- self.x2,self.y2 = p2
- try:
- self.circle = find_circle([(self.x1,self.y1),(self.x2,self.y2),(pos_hist[-1],pos_hist[-2])])
- except:
- pass
- def update(self):
- self.circle = find_circle([(self.x1,self.y1),(self.x2,self.y2),(pos_hist[-1],pos_hist[-2])])
- self.x = self.circle['x']
- self.y = self.circle['y']
- self.z = self.circle['z']
- self.RANDCOLOR(random.randint(0,255),random.randint(0,255),random.randint(0,255))
- pygame.draw.circle(DISPLAYSURF,self.RANDCOLOR,(int(self.x),int(self.y)),int(self.r),1)
- def update_pos():
- pos_hist.append(pygame.mouse.get_pos())
- if len(pos_hist) >= max_hist + 1:
- pos_hist.pop(0)
- try:
- # if pos_hist[-1] != pos_hist[-2] != pos_hist[-3] :
- # 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()]))])
- # 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()])))
- # except IndexError:
- # print(None)
- pass
- except:
- # print(None)
- print(''.join([str(i) for i in pos_hist[-4:-1]]),None)
- def find_circle(point_list):
- try:
- x1,x2,x3 = point_list[-1][0],point_list[-2][0],point_list[-3][0]
- y1,y2,y3 = point_list[-1][1],point_list[-2][1],point_list[-3][1]
- 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)))
- 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)))
- r = ((x2-h)**2+(y2-k)**2)**(1/2)
- # if r < 1:
- # r = 1
- # return ((h,k),r)
- return {'x':h,'y':k,'r':r}
- except:
- return None
- def update_key_dict():
- for event in pygame.event.get():
- #~ print(event)
- if event.type == QUIT:
- pygame.mixer.quit()
- pygame.quit()
- sys.exit()
- try:
- key_dict.update({event.key:event.type})
- except AttributeError:
- pass
- def getkeystate(k):
- try:
- if key_dict[k] == KEYDOWN:
- return True
- elif key_dict[k] == KEYUP:
- return False
- except:
- key_dict.update({k:KEYUP})
- return False
- def save_screenshot():
- screeny_dir = os.path.join(os.curdir,"Masterpieces")
- if not os.path.exists(os.path.join(os.curdir,"Masterpieces")):
- os.makedirs(os.path.join(os.curdir,"Masterpieces"))
- pygame.image.save(DISPLAYSURF,os.path.join(screeny_dir, "Masterpiece " + time.strftime("%Y%m%d %H%M%S")+".png"))
- while True:
- #~ main loop
- #~ calculate circle
- update_pos()
- #~ handle events
- update_key_dict()
- if getkeystate(K_LSHIFT):
- paused = True
- else:
- paused = False
- if pygame.mouse.get_pressed()[2] == 1 or getkeystate(K_SPACE):
- fade_enabled = False
- else:
- fade_enabled = True
- if not getkeystate(K_c) :
- live_circles = []
- if not getkeystate(K_1):
- pass
- if getkeystate(K_q) or getkeystate(K_ESCAPE):
- sys.exit()
- if getkeystate(K_F12):
- save_screenshot()
- RANDCOLOR = (random.randint(0,255),random.randint(0,255),random.randint(0,255))
- circle = find_circle(pos_hist[-1:-4:-1])
- try:
- if framecount % 1 <= 1:
- if paused == False:
- DISPLAYSURF.fill((0,0,0))
- fading_circles.append(FadingCircle(circle['x'],circle['y'],circle['r']))
- except TypeError:
- pass
- #~ handle list of fading circles
- for index,item in enumerate(fading_circles):
- RANDCOLOR = (random.randint(0,255),random.randint(0,255),random.randint(0,255))
- if item.should_die():
- del fading_circles[index]
- item.update()
- #~ try:
- #~ pygame.draw.line(DISPLAYSURF,WHITE,(item.x,item.y),(fading_circles[index+1].x,fading_circles[index+1].y),1)
- #~ except:
- #~ pass
- if trail_enabled:
- for index,item in enumerate(pos_hist):
- #~ RANDCOLOR = (random.randint(0,255),random.randint(0,255),random.randint(0,255))
- if trail_enabled:
- try:
- # draw a mouse trail
- pygame.draw.line(DISPLAYSURF,RANDCOLOR,item,pos_hist[index+1],1)
- #~ pygame.draw.circle(DISPLAYSURF,RANDCOLOR,item,1)
- except IndexError:
- pass
- pygame.display.update()
- framecount += 1
- #~ wait to draw next frame
- time.sleep(FRAMEDELAY)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement