Advertisement
Geometrian

Event Timer Example

Jun 16th, 2018
240
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.83 KB | None | 0 0
  1. import pygame
  2. from pygame.locals import *
  3. import sys, os, traceback
  4. if sys.platform in ["win32","win64"]: os.environ["SDL_VIDEO_CENTERED"]="1"
  5. pygame.display.init()
  6. pygame.font.init()
  7.  
  8. screen_size = [800,600]
  9. icon = pygame.Surface((1,1)); icon.set_alpha(0); pygame.display.set_icon(icon)
  10. pygame.display.set_caption("Event Timer Sample - Ian Mallett - 2018")
  11. surface = pygame.display.set_mode(screen_size)
  12.  
  13. cooldown = 0.0
  14.  
  15. class Bullet(object):
  16.     def __init__(self,x,y,t):
  17.         self.x=x; self.y=y; self.t=t
  18. bullets = []
  19.  
  20. def get_input():
  21.     global cooldown
  22.     keys_pressed = pygame.key.get_pressed()
  23.     mouse_buttons = pygame.mouse.get_pressed()
  24.     mouse_position = pygame.mouse.get_pos()
  25.     mouse_rel = pygame.mouse.get_rel()
  26.     for event in pygame.event.get():
  27.         if   event.type == QUIT: return False
  28.         elif event.type == KEYDOWN:
  29.             if   event.key == K_ESCAPE: return False
  30.  
  31.     if keys_pressed[K_RETURN] and cooldown==0.0:
  32.         cooldown = 0.2
  33.         bullets.append(Bullet(400,300, 0))
  34.  
  35.     return True
  36.  
  37. def update(dt):
  38.     global cooldown, bullets
  39.  
  40.     if cooldown > 0.0:
  41.         cooldown -= dt
  42.     else:
  43.         cooldown = 0.0
  44.  
  45.     for bullet in bullets:
  46.         bullet.x += 5
  47.         bullet.t += dt
  48.  
  49.     bullets = [
  50.         bullet for bullet in bullets if bullet.t<1.0
  51.     ]
  52.  
  53. def draw():
  54.     surface.fill((255,255,255))
  55.  
  56.     for bullet in bullets:
  57.         pygame.draw.circle(surface,(255,0,0),(bullet.x,bullet.y),5,0)
  58.    
  59.     pygame.display.flip()
  60.  
  61. def main():
  62.     clock = pygame.time.Clock()
  63.     while True:
  64.         if not get_input(): break
  65.         update(1.0/60.0)
  66.         draw()
  67.         clock.tick(60)
  68.     pygame.quit()
  69. if __name__ == "__main__":
  70.     try:
  71.         main()
  72.     except:
  73.         traceback.print_exc()
  74.         pygame.quit()
  75.         input()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement