Advertisement
TheCDC

Lightning (Python3/Pygame)

Feb 1st, 2015
365
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.38 KB | None | 0 0
  1. #!/usr/bin/python3
  2. """
  3. Lightning
  4. by Christopher Chen (christoipher.chen@gmail.com)
  5.  
  6. Dependencies:
  7.     Python 3
  8.     Pygame
  9.  
  10. Controls:
  11.     SPACE or Click: create lightning at mouse cursor
  12.     r: create firework at random position
  13.     ESCAPE or q: quit
  14.     F12: take screenshot
  15.     Numpad number keys: create fireworks at coordinates corresponding to the positions of the numpad number keys. Nunmlock must be OFF.
  16.  
  17. Additional Notes:
  18.     This programm will automatically create a folder called 'Masterpieces' alongside the source py file.
  19.     This is the screenshot directory.
  20. """
  21.  
  22.  
  23.  
  24. FRAMERATE = 60
  25. FRAMEDELAY = 1/FRAMERATE
  26. key_dict = {}
  27. game_obj_list = []
  28. RANDCOLOR = (255,255,255)
  29.  
  30.  
  31.  
  32. class Streamer:
  33.     """A randomly turning projectile that draws its trail"""
  34.     def __init__(self, x, y, color, speed, lifetime, deviance):
  35.         self.x = x
  36.         self.y = y
  37.         self.color = color
  38.         # speed in pixels/second
  39.         self.speed = speed
  40.         self.angle = random.randint(1,360)
  41.         # self.framerate = framerate
  42.         self.killflag = False
  43.         self.lifetime = lifetime
  44.         self.pos_hist = [(self.x,self.y)]
  45.         self.deviance = deviance
  46.  
  47.     def update(self):
  48.         self.pos_hist.append((self.x,self.y))
  49.         self.x += self.speed*math.cos(math.radians(self.angle))
  50.         self.y += self.speed*math.sin(math.radians(self.angle))
  51.         self.angle += random.randint(int(-self.deviance/2),int(self.deviance/2))
  52.  
  53.         # pygame.draw.line(DISPLAYSURF,self.color,(self.prevx,self.prevy),(self.x,self.y),1)
  54.         if self.lifetime <= 0:
  55.             self.killflag = True
  56.         self.lifetime -= 1
  57.         # print("yes")
  58.  
  59.     def draw(self):
  60.         if FANCY_GRAPHICS:
  61.             pygame.draw.aalines(DISPLAYSURF, self.color, False, self.pos_hist, 1)
  62.         else:
  63.             for index,item in enumerate(self.pos_hist):
  64.                 try:
  65.                     pygame.draw.line(DISPLAYSURF,self.color,self.pos_hist[index+1],item,1)
  66.                 except IndexError:
  67.                     pass
  68.  
  69.     def should_die(self):
  70.         return self.killflag
  71.  
  72. class Firework:
  73.     """A parent for multiple streamers"""
  74.  
  75.     def __init__(self, n, x, y, color, speed, lifetime, deviance):
  76.         for i in range(n):
  77.             game_obj_list.append(Streamer(x,y,color,speed,lifetime,deviance))
  78.         self.killflag = True
  79.        
  80.     def should_die(self):
  81.         return True
  82.  
  83.     def update(self):
  84.         pass
  85.        
  86.     def draw(self):
  87.         pass
  88.  
  89. def create_firework_random(x,y):
  90.     color = (random.randint(0,255),random.randint(0,255),random.randint(0,255))
  91.     # color = (random.randint(1,16)*16-1,random.randint(1,16)*16-1,random.randint(1,16)*16-1)
  92.     #                    n,                            x,y,color,speed,                 lifetime,  deviance
  93.     game_obj_list.append(Firework(random.randint(2,15),x,y,color,random.randint(10,80),random.randint(2,10),random.randint(10,180)))
  94.  
  95. def getkeystate(k):
  96.     try:
  97.         if key_dict[k] == KEYDOWN:
  98.             return True
  99.         elif key_dict[k] == KEYUP:
  100.             return False
  101.     except:
  102.         key_dict.update({k:KEYUP})
  103.         return False
  104.  
  105. def update_key_dict():
  106.     for event in pygame.event.get():
  107.             #~ print(event)
  108.             if event.type == QUIT:
  109.                 pygame.quit()
  110.                 sys.exit()
  111.  
  112.             try:
  113.                 key_dict.update({event.key:event.type})
  114.             except AttributeError:
  115.                 pass
  116.  
  117.    
  118. def save_screenshot():
  119.     screeny_dir = os.path.join(os.curdir,"Masterpieces")
  120.     if not os.path.exists(os.path.join(os.curdir,"Masterpieces")):
  121.         os.makedirs(os.path.join(os.curdir,"Masterpieces"))
  122.     pygame.image.save(DISPLAYSURF,os.path.join(screeny_dir, "Masterpiece " + time.strftime("%Y%m%d %H%M%S")+".png"))
  123.  
  124. def main():
  125.     while True:
  126.         # get a random color
  127.         RANDCOLOR = (random.randint(0,255),random.randint(0,255),random.randint(0,255))
  128.        
  129.         #~ handle events and update dictionary of key states
  130.         update_key_dict()
  131.  
  132.         # get the mouse position
  133.         mouse_pos = {'x':pygame.mouse.get_pos()[0],'y':pygame.mouse.get_pos()[1]}
  134.         # print(mouse_pos)
  135.  
  136.         # game_obj_list.append(Streamer(mouse_pos['x'],mouse_pos['y'],(255,255,255),10,50,45))
  137.         #create firework
  138.         if getkeystate(K_SPACE) or pygame.mouse.get_pressed()[0] == 1:
  139.             create_firework_random(mouse_pos['x'],mouse_pos['y'])
  140.         #create firewok at random position
  141.         if getkeystate(K_r):
  142.             create_firework_random(random.randint(0,WIDTH-1),random.randint(0,HEIGHT-1))
  143.  
  144.         #quit
  145.         if getkeystate(K_q) or getkeystate(K_ESCAPE):
  146.             sys.exit()
  147.  
  148.         #screenshot
  149.         if getkeystate(K_F12):
  150.             save_screenshot()
  151.  
  152.         for key in numpad_keys:
  153.             if getkeystate(key):
  154.                 create_firework_random(WIDTH/2 + (WIDTH/3) * numpad_coords[key][0],HEIGHT/2 - (HEIGHT/3) * numpad_coords[key][1])
  155.  
  156.  
  157.         if pygame.mouse.get_pressed()[2] == 0 and not getkeystate(K_LSHIFT):
  158.             DISPLAYSURF.fill((0,0,0))
  159.         time.sleep(FRAMEDELAY)
  160.  
  161.  
  162.         # update all items in the main list of game objects
  163.         for index,item in enumerate(game_obj_list):
  164.             if item.should_die():
  165.                 del game_obj_list[index]
  166.             item.update()
  167.             item.draw()
  168.  
  169.         pygame.display.update()
  170.  
  171. if __name__ == '__main__':
  172.     import random, pygame, math, time, sys, os
  173.     from pygame.locals import *
  174.  
  175.     pygame.init()
  176.     infoObj = pygame.display.Info()
  177.     WIDTH = int(infoObj.current_w)
  178.     HEIGHT = int(infoObj.current_h)
  179.     SIZE  = (WIDTH,HEIGHT)
  180.     DISPLAYSURF = pygame.display.set_mode((WIDTH,HEIGHT),pygame.FULLSCREEN)
  181.  
  182.     #numpad_keys = [K_KP1,K_KP2,K_KP3,K_KP4,K_KP5,K_KP6,K_KP7,K_KP8,K_KP9]
  183.     numpad_coords = {K_KP7:(-1,1),K_KP8:(0,1),K_KP9:(1,1),
  184.     K_KP4:(-1,0),K_KP5:(0,0),K_KP6:(1,0),
  185.     K_KP1:(-1,-1),K_KP2:(0,-1),K_KP3:(1,-1)}
  186.  
  187.     numpad_keys = numpad_coords.keys()
  188.  
  189.     print("Run with -nogfx to disable fancy graphics")
  190.     if "-nogfx" in sys.argv:
  191.         FANCY_GRAPHICS = False
  192.     else:
  193.         FANCY_GRAPHICS = True
  194.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement