Advertisement
cookertron

Basic Shooter (with images)

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