cookertron

Basic Shooter

Jan 24th, 2020
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.88 KB | None | 0 0
  1. import pygame
  2.  
  3. BLACK = [0, 0, 0]
  4. WHITE = [255, 255, 255]
  5.  
  6. W, H = 800, 600
  7. HH = int(H / 2)
  8.  
  9. pygame.init()
  10. DS = pygame.display.set_mode((W, H))
  11.  
  12. # player starting position
  13. playerY = HH
  14. playerX = 5
  15. playerSize = 25
  16.  
  17. # bullet list and speed
  18. bullets = []
  19. bulletSpeed = 20
  20.  
  21. # fire button pressed toggle
  22. fireButtonPressed = False
  23.  
  24. # main program loop
  25. while True:
  26.     e = pygame.event.get() # read events but do nothing
  27.    
  28.     DS.fill(BLACK)
  29.     pygame.draw.rect(DS, WHITE, [playerX, playerY, playerSize, playerSize]) # draw a rectangle as the player
  30.  
  31.     # press escape to quit, window controls don't work
  32.     k = pygame.key.get_pressed()
  33.     if k[pygame.K_ESCAPE]: break
  34.  
  35.     # use the arrow keys UP and DOWN
  36.     if k[pygame.K_UP]:
  37.         playerY -= 10
  38.     elif k[pygame.K_DOWN]:
  39.         playerY += 10
  40.  
  41.     # space bar fires bullets
  42.     # add player x, y to bullet list
  43.     if k[pygame.K_SPACE] and not fireButtonPressed:
  44.         fireButtonPressed = True
  45.         bullets.append([playerX + int(playerSize / 2), playerY + int(playerSize / 2)]) # add new bullet to the list
  46.     elif not k[pygame.K_SPACE] and fireButtonPressed:
  47.         fireButtonPressed = False
  48.  
  49.     deleteBullets = [] # you shouldn't delete bullets as you're cycling through a list. delete afterwards
  50.     # cycle through the active bullets
  51.     for b in bullets:
  52.         pygame.draw.circle(DS, WHITE, b, 10) # draw the bullet as a circle
  53.         b[0] += bulletSpeed # add bullet speed to the bullets x position
  54.         if b[0] > W: # if bullet exits the right side of the screen
  55.             deleteBullets.append(b) # add to bullet delete list
  56.    
  57.     # delete all the "dead" bullets
  58.     for db in deleteBullets:
  59.         bullets.remove(db) # remove it from the bullet list
  60.    
  61.     pygame.display.update() # update the display
  62.     pygame.time.Clock().tick(27) # limit the frame rate to 27 fps
  63.  
  64. pygame.quit()
Add Comment
Please, Sign In to add comment