Advertisement
zharry

ICS2O1-05 Treasure Hunt Pygame Answer

Jun 5th, 2016
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.95 KB | None | 0 0
  1. """
  2. Demonstration of Treasure Game
  3. Author: Harry Zhang
  4. Date: June 5, 2016
  5. Release Notes:
  6. - No variable dictionary
  7. - Limited commenting
  8. - Working game
  9.  
  10. !IMPORTANT!
  11. If any plagiarism or cheating is found, all students involved will get a ZERO mark.
  12.  
  13. Readme:
  14. Knowing the above, to have this code work for you,
  15. please change the image files located in the classes
  16. and the fontface to be used
  17. """
  18.  
  19. import pygame, sys, os, time, random, platform
  20. from pygame.locals import *
  21. from pygame.color import THECOLORS
  22.  
  23. if platform.system() == "Windows":
  24.     os.environ['SDL_VIDEODRIVER'] = 'windib'
  25.    
  26. # Enemy template
  27. class Enemy (pygame.sprite.Sprite):
  28.     def __init__(self, xCoord, yCoord, xDirection, yDirection, speed):
  29.         pygame.sprite.Sprite.__init__(self)
  30.        
  31.         # Create and load image for enemy
  32.         self.image = pygame.Surface((30, 30))
  33.         shapeImage = pygame.image.load("ENEMY IMAGE").convert()
  34.         self.image.blit(shapeImage, (0, 0))
  35.         self.image.set_colorkey((255, 255, 255))
  36.        
  37.         # Set it's bounding box and coordinates
  38.         self.rect = self.image.get_rect()
  39.         self.rect.centery = yCoord
  40.         self.rect.centerx = xCoord
  41.        
  42.         # Set it's motion and directions
  43.         self.xdir = xDirection
  44.         self.ydir = yDirection
  45.         self.speed = speed
  46.        
  47.     def update(self):
  48.         # Move the sprite everytime update() is called
  49.         self.rect.centerx = self.rect.centerx + self.xdir * self.speed
  50.         self.rect.centery = self.rect.centery + self.ydir * self.speed
  51.        
  52.         # Make sure the sprite is within the limits of the playing field
  53.         if self.rect.centerx <= 15 or self.rect.centerx >= screen.get_width() - 15:
  54.             self.xdir = -self.xdir
  55.         if self.rect.centery <= 15 or self.rect.centery >= screen.get_height() - 55:
  56.             self.ydir = -self.ydir
  57.  
  58. # Treasure Template
  59. class Treasure (pygame.sprite.Sprite):
  60.     def __init__(self, xCoord, yCoord):
  61.         pygame.sprite.Sprite.__init__(self)
  62.        
  63.         # Create and load picture for treasure
  64.         self.image = pygame.Surface((30, 30))
  65.         shapeImage = pygame.image.load("TREASURE IMAGE").convert()
  66.         self.image.blit(shapeImage, (0, 0))
  67.         self.image.set_colorkey((255, 255, 255))
  68.        
  69.         # Set it's bounding box and coordinates
  70.         self.rect = self.image.get_rect()
  71.         self.rect.centery = yCoord
  72.         self.rect.centerx = xCoord
  73.        
  74. # Player object template
  75. class Player (pygame.sprite.Sprite):
  76.     def __init__(self, xCoord, yCoord):
  77.         pygame.sprite.Sprite.__init__(self)
  78.        
  79.         # Load and set image for player
  80.         self.image = pygame.Surface((30, 30))
  81.         shapeImage = pygame.image.load("PLAYER IMAGE").convert()
  82.         self.image.blit(shapeImage, (0, 0))
  83.         self.image.set_colorkey((255, 255, 255))
  84.        
  85.         # Set bounding box and location for player
  86.         self.rect = self.image.get_rect()
  87.         self.rect.centery = yCoord
  88.         self.rect.centerx = xCoord
  89.  
  90. # Start pygame engine
  91. pygame.init()
  92. clock = pygame.time.Clock()
  93.  
  94. # Create a 800x600 window and name it "Treasure Hunt"
  95. window = pygame.display.set_mode((800, 600))
  96. pygame.display.set_caption("Treasure Hunt")
  97. screen = pygame.display.get_surface()
  98.  
  99. # Define font to be used in displaying score and text objects
  100. font = pygame.font.SysFont("CHOOSE YOUR FONT", 25)
  101.  
  102. # Define score and lives variables
  103. score = 0
  104. lives = 40
  105.  
  106. # Group containing all the enemies
  107. enemies = pygame.sprite.Group()
  108.  
  109. # Group containing all the treasures
  110. treasures = pygame.sprite.Group()
  111.  
  112. # Create 10 Enemies
  113. for i in range(10):
  114.    
  115.     # Assign a random x,y coordinate within the game area
  116.     xCoord = random.randrange(15, screen.get_width() - 15)
  117.     yCoord = random.randrange(15, screen.get_height() - 55)
  118.  
  119.     # Assign a random direction and speed
  120.     xdir = random.choice([-1, 1])
  121.     ydir = random.choice([-1, 1])
  122.     speed = random.randrange(4, 11)
  123.  
  124.     # Create and add the new enemy to the list of enemies
  125.     enemy = Enemy(xCoord, yCoord, xdir, ydir, speed)
  126.     enemies.add(enemy)
  127.    
  128. # Create 30 Treasure locations
  129. for i in range(30):
  130.    
  131.     # Assign a random x,y location within the game area
  132.     xCoord = random.randrange(15, screen.get_width() - 15)
  133.     yCoord = random.randrange(15, screen.get_height() - 55)
  134.  
  135.     # Create and add the new treasure object to the list of treasures
  136.     treasure = Treasure(xCoord, yCoord)
  137.     treasures.add(treasure)
  138.  
  139. # Create the player sprite
  140. player = Player(screen.get_width() // 2, screen.get_height() - 55)
  141.  
  142. # Clear the screen for the first frame
  143. screen.fill((255, 255, 255))
  144.    
  145. # Draw and move all of the enemies
  146. enemies.draw(screen)
  147. enemies.update()
  148.  
  149. # Draw all of the treasure objects
  150. treasures.draw(screen)
  151.  
  152. # Draw the player
  153. screen.blit(player.image, player.rect)
  154.  
  155. # Draw the bottom display for score and livesr
  156. pygame.draw.rect(screen, THECOLORS['yellow'], [0, screen.get_height() - 40, screen.get_width(), 40])
  157. text = font.render("Life: {} {} Score: {}".format(lives, " " * 10, score), True, THECOLORS['black'])
  158. screen.blit(text, (screen.get_width() // 2 - text.get_width() // 2, screen.get_height() - 40))
  159.  
  160. # The game has not finished
  161. gameOver = False
  162.  
  163. # Allow the game to keep going
  164. keepGoing = True
  165. while keepGoing:
  166.     clock.tick(30) # FPS
  167.    
  168.     # What to do if the game has not yet ended
  169.     if not gameOver:
  170.         # Clear the screen
  171.         screen.fill((255, 255, 255))
  172.    
  173.         # Draw and move all of the enemies
  174.         enemies.draw(screen)
  175.         enemies.update()
  176.        
  177.         # Draw all of the treasure objects
  178.         treasures.draw(screen)
  179.        
  180.         # Draw the player
  181.         screen.blit(player.image, player.rect)
  182.    
  183.         # Draw the bottom display for lives and score
  184.         pygame.draw.rect(screen, THECOLORS['yellow'], [0, screen.get_height() - 40, screen.get_width(), 40])
  185.         font = pygame.font.SysFont("comicsansms", 25)
  186.         text = font.render("Life: {} {} Score: {}".format(lives, " " * 10, score), True, THECOLORS['black'])
  187.         screen.blit(text, (screen.get_width() // 2 - text.get_width() // 2, screen.get_height() - 40))
  188.    
  189.         # Flip the drawn objects into view
  190.         pygame.display.flip()
  191.        
  192.         # Get pressed keys
  193.         keys = pygame.key.get_pressed()
  194.        
  195.         # If the up key is pressed move the player object up as long as it is within the game area
  196.         if keys[pygame.K_UP] and player.rect.centery > 15:
  197.             player.rect.centery -= 5
  198.            
  199.         # If the down key is pressed move the player down as long as it is within the game area
  200.         elif keys[pygame.K_DOWN] and player.rect.centery < screen.get_height() - 55:
  201.             player.rect.centery += 5
  202.            
  203.         # If the left key is pressed move the player left as long as it is within the game area
  204.         elif keys[pygame.K_LEFT] and player.rect.centerx > 15:
  205.             player.rect.centerx -= 5
  206.            
  207.         # If the right key is pressed move the player right as long as it is within the game area
  208.         elif keys[pygame.K_RIGHT] and player.rect.centerx < screen.get_width() - 15:
  209.             player.rect.centerx += 5
  210.        
  211.         # Search for any collision on the player with treasure objects
  212.         for treasure in treasures:
  213.            
  214.             # Check if the current treasure object being polled is in collision with the player
  215.             collided = pygame.sprite.collide_rect(player, treasure)
  216.    
  217.             if collided:
  218.                 # If it is add one to the score and remove that treasure object
  219.                 score = score + 1
  220.                 treasures.remove(treasure)
  221.            
  222.         # Search for any collision on the player with enemies
  223.         for enemy in enemies:
  224.            
  225.             # Check if the current enemy being polled is in collision with the player
  226.             collided = pygame.sprite.collide_rect(player, enemy)
  227.    
  228.             if collided:
  229.                 # If it is reset the players position and remove one life
  230.                 lives = lives - 1
  231.                 player.rect.centerx = screen.get_width() // 2
  232.                 player.rect.centery = screen.get_height() - 55
  233.        
  234.         # Check if the player has either won or lost the game
  235.         if score >= 30 or lives <= 0:
  236.             gameOver = True
  237.                
  238.         pygame.time.delay(20)
  239.        
  240.     else:
  241.         # If the player has won or lost
  242.        
  243.         # Clear the screen
  244.         screen.fill((255, 255, 255))
  245.        
  246.         # Draw and display the bottom bar for score and lives
  247.         pygame.draw.rect(screen, THECOLORS['yellow'], [0, screen.get_height() - 40, screen.get_width(), 40])
  248.         text = font.render("Life: {} {} Score: {}".format(lives, " " * 10, score), True, THECOLORS['black'])
  249.         screen.blit(text, (screen.get_width() // 2 - text.get_width() // 2, screen.get_height() - 40))
  250.        
  251.         # If the player has won
  252.         if score >= 30:
  253.            
  254.             # Draw and display a winning text
  255.             text = font.render("Congratulations! You got all the treasure!", True, THECOLORS['green'])
  256.             screen.blit(text, (screen.get_width() // 2 - text.get_width() // 2, \
  257.                                screen.get_height() // 2 - text.get_height() // 2))
  258.         else:
  259.            
  260.             # If the player lost, draw and display a try again text
  261.             text = font.render("Sorry, you died. Better luck next time!", True, THECOLORS['red'])
  262.             screen.blit(text, (screen.get_width() // 2 - text.get_width() // 2, \
  263.                                screen.get_height() // 2 - text.get_height() // 2))
  264.            
  265.         # Flip the drawn objects into view
  266.         pygame.display.flip()
  267.  
  268.     # Event loop
  269.     events = pygame.event.get()
  270.     for ev in events:
  271.  
  272.         if ev.type == QUIT:
  273.             keepGoing = False  # Stop the program, it's detected quit...
  274.  
  275. pygame.quit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement