Advertisement
shh_algo_PY

Shooter Game - with lives and collisions

Nov 5th, 2022
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.68 KB | None | 0 0
  1. from pygame import *
  2. from random import randint
  3.  
  4. # ✨(1) import the timing function so that the interpreter doesn’t need to look for this function in the pygame module time, give it a different name ourselves
  5. from time import time as timer
  6.  
  7. # Background music
  8. mixer.init()
  9. mixer.music.load('rickastley.ogg')
  10. mixer.music.play()
  11. fire_sound = mixer.Sound('laser.wav')
  12.  
  13. # ✨(2) Load images --- ADD ASTEROID!
  14. img_back = "mountains.jpg" #game background
  15. img_bullet = "fire.png" #bullet
  16. img_hero = "cat.png" #hero
  17. img_enemy = "taco.png" #enemy
  18. img_ast = "piggybank.png" #asteroid
  19.  
  20. # Create a window
  21. win_width = 700
  22. win_height = 500
  23. display.set_caption("Shooter")
  24. window = display.set_mode((win_width, win_height))
  25. background = transform.scale(image.load(img_back), (win_width, win_height))
  26.  
  27. # Fonts and captions
  28. font.init()
  29. # WINNING FONT
  30. font1 = font.SysFont('Comic Sans MS', 80)
  31. # SCORE FONT
  32. font2 = font.SysFont('Comic Sans MS', 30)
  33. # Captions
  34. win = font1.render('YOU WIN!', True, (255, 255, 255))
  35. lose = font1.render('YOU LOSE!', True, (180, 0, 0))
  36.  
  37. score = 0 #ships destroyed
  38. lost = 0 #ships missed
  39.  
  40. max_lost = 3 #how many ships you can lose
  41.  
  42. goal = 10 #how many ships need to be shot down to win
  43.  
  44. # ✨(3) ADD LIVES
  45. life = 3  #lives!
  46.  
  47. # GameSprite class - inheriting from class Sprite
  48. class GameSprite(sprite.Sprite):
  49.     def __init__(self, player_image, player_x, player_y, size_x, size_y, player_speed):
  50.         # Call for the class (Sprite) constructor:
  51.         sprite.Sprite.__init__(self)
  52.  
  53.         # Every sprite must store the image property
  54.         self.image = transform.scale(image.load(player_image), (size_x, size_y))
  55.         self.speed = player_speed
  56.  
  57.         # Every sprite must have the rect property – the rectangle it is fitted in
  58.         self.rect = self.image.get_rect()
  59.         self.rect.x = player_x
  60.         self.rect.y = player_y
  61.    
  62.     # Puts the character in the window
  63.     def reset(self):
  64.         window.blit(self.image, (self.rect.x, self.rect.y))
  65.  
  66. #main player class
  67. class Player(GameSprite):
  68.     # Function to control the sprite with arrow keys - only LEFT and RIGHT needed
  69.     def update(self):
  70.         keys = key.get_pressed()
  71.         if keys[K_LEFT] and self.rect.x > 5:
  72.             self.rect.x -= self.speed
  73.         if keys[K_RIGHT] and self.rect.x < win_width - 80:
  74.             self.rect.x += self.speed
  75.    
  76.     # Function to "shoot" (use the player position to create a bullet there)
  77.     def fire(self):
  78.         bullet = Bullet(img_bullet, self.rect.centerx, self.rect.top, 15, 20, -15)
  79.         bullets.add(bullet)
  80.    
  81. class Enemy(GameSprite):
  82.     # Enemy movement
  83.     def update(self):
  84.         self.rect.y += self.speed
  85.         global lost
  86.         # Disappears upon reaching the screen edge
  87.         if self.rect.y > win_height:
  88.             self.rect.x = randint(80, win_width - 80)
  89.             self.rect.y = 0
  90.             lost = lost + 1
  91.  
  92. # Bullet sprite class  
  93. class Bullet(GameSprite):
  94.     def update(self):
  95.         self.rect.y += self.speed
  96.         # Disappears upon reaching the screen edge
  97.         if self.rect.y < 0:
  98.             self.kill()
  99.  
  100. #create sprites
  101. ship = Player(img_hero, 5, win_height - 100, 80, 100, 10)
  102.  
  103. #creating a group of enemy sprites
  104. monsters = sprite.Group()
  105. for i in range(1, 6):
  106.    monster = Enemy(img_enemy, randint(80, win_width - 80), -40, 80, 50, randint(1, 5))
  107.    monsters.add(monster)
  108.  
  109. bullets = sprite.Group()
  110.  
  111. #------------------------------------#
  112. # ✨(4) Asteroid sprites
  113.  
  114. asteroids = sprite.Group()
  115.  
  116. for i in range(1, 3):
  117.    asteroid = Enemy(img_ast, randint(30, win_width - 30), -40, 80, 50, randint(1, 7))
  118.    asteroids.add(asteroid)
  119. #------------------------------------#
  120.  
  121. # The "game is over" variable
  122. # As soon as it becomes True, all sprites stop working in the main loop
  123. finish = False
  124.  
  125. # Main game loop
  126. # The game is reset by the window close button
  127. run = True
  128.  
  129. #------------------------------------#
  130. #✨(5) Variables - reload, shots fired
  131.  
  132. # Reload time
  133. rel_time = False
  134.  
  135. # Count shots fired
  136. num_fire = 0  
  137. #------------------------------------#
  138.  
  139. #✨(6) Update the game loop
  140.  
  141. while run:
  142.     # "Close" button press event ✅
  143.     for e in event.get():
  144.         if e.type == QUIT:
  145.             run = False
  146.        #event of pressing the spacebar - the sprite shoots ✅
  147.         elif e.type == KEYDOWN:
  148.             if e.key == K_SPACE:
  149.                 # Check how many shots have been fired (151 - 158 : NEW!)
  150.                 # And whether reload is in progress
  151.                 # Replace the old firing!
  152.                 if num_fire < 5 and rel_time == False:
  153.                     num_fire = num_fire + 1
  154.                     fire_sound.play()
  155.                     ship.fire()
  156.                      
  157.                     if num_fire  >= 5 and rel_time == False :
  158.                         last_time = timer() #record time when this happened
  159.                         rel_time = True #set the reload flag
  160.              
  161.     if not finish:
  162.         # Don't forget your asteroids!
  163.         # Update the background
  164.         window.blit(background,(0,0))
  165.    
  166.         # Launch sprite movements
  167.         ship.update()
  168.         monsters.update()
  169.         bullets.update()
  170.         asteroids.update() # THIS ONE
  171.    
  172.         # Update them in a new location in each loop iteration
  173.         ship.reset()
  174.         monsters.draw(window)
  175.         bullets.draw(window)
  176.         asteroids.draw(window) # THIS ONE
  177.  
  178.         # Reload mechanism
  179.         if rel_time == True:
  180.             now_time = timer()
  181.  
  182.             # Before 3 seconds are over, display reload message
  183.             if now_time - last_time < 3:
  184.                 reload = font2.render('Wait, reload...', 1, (150, 0, 0))
  185.                 window.blit(reload, (260, 460))
  186.             else:
  187.                 # Reset time!
  188.                 num_fire = 0  
  189.                 rel_time = False
  190.  
  191.         # Check for a collision between a bullet and monsters (both monster and bullet disappear upon a touch)
  192.  
  193.         collides = sprite.groupcollide(monsters, bullets, True, True)
  194.        
  195.         for c in collides:
  196.             #this loop will repeat as many times as the number of monsters hit
  197.             # Score +1
  198.             score = score + 1
  199.             # Respawn
  200.             monster = Enemy(img_enemy, randint(80, win_width - 80), -40, 80, 50, randint(1, 5))
  201.             # Adding it to the monster group
  202.             monsters.add(monster)
  203.  
  204.         #----------------------------#
  205.         # UPDATE THIS SECTION!
  206.         # Now with asteroids!
  207.         #----------------------------#
  208.         if sprite.spritecollide(ship, monsters, False) or sprite.spritecollide(ship, asteroids, False):
  209.             sprite.spritecollide(ship, monsters, True)
  210.             sprite.spritecollide(ship, asteroids, True)
  211.             life = life - 1
  212.    
  213.         # NEW losing check!
  214.         if life == 0 or lost >= max_lost:
  215.             finish = True
  216.             window.blit(lose, (150, 200))
  217.  
  218.         # Same winning check :)
  219.         if score >= goal:
  220.             finish = True
  221.             window.blit(win, (150, 200))
  222.  
  223.         # Captions
  224.  
  225.         text = font2.render("Score: " + str(score), 1, (255, 255, 255))
  226.         window.blit(text, (10, 20))
  227.    
  228.         text_lose = font2.render("Missed: " + str(lost), 1, (255, 255, 255))
  229.         window.blit(text_lose, (10, 50))
  230.  
  231.         #-----------------------------#
  232.         # NEW: LIVES TRACKER!
  233.         #-----------------------------#
  234.         # Set a different color depending on the number of lives
  235.         if life == 3:
  236.             life_color = (0, 150, 0) #Green
  237.         if life == 2:
  238.             life_color = (150, 150, 0) #Mustard yellow?
  239.         if life == 1:
  240.             life_color = (150, 0, 0) #Red
  241.    
  242.         text_life = font1.render(str(life), 1, life_color)
  243.         window.blit(text_life, (650, 10))
  244.         #-----------------------------#
  245.         display.update()
  246.  
  247.     #bonus: automatic restart of the game
  248.     else:
  249.         finish = False
  250.  
  251.         score = 0
  252.         lost = 0
  253.  
  254.         # Add fire counter and lives
  255.         num_fire = 0
  256.         life = 3
  257.  
  258.         # Add asteroids
  259.         for b in bullets:
  260.             b.kill()
  261.         for m in monsters:
  262.             m.kill()
  263.         for a in asteroids:
  264.             a.kill()  
  265.        
  266.         time.delay(3000)
  267.  
  268.         for i in range(1, 6):
  269.             monster = Enemy(img_enemy, randint(80, win_width - 80), -40, 80, 50, randint(1, 5))
  270.             monsters.add(monster)
  271.        
  272.         # Add asteroid re-spawn loop
  273.         for i in range(1, 3):
  274.             asteroid = Enemy(img_ast, randint(30, win_width - 30), -40, 80, 50, randint(1, 7))
  275.             asteroids.add(asteroid)  
  276.    
  277.     time.delay(50)
  278.  
  279.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement