Advertisement
Guest User

Untitled

a guest
Apr 25th, 2015
224
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.46 KB | None | 0 0
  1.  
  2. import pygame
  3.  
  4. # Global constants
  5.  
  6. # Colors
  7. BLACK    = (   0,   0,   0)
  8. WHITE    = ( 255, 255, 255)
  9. BLUE     = (   0,   0, 255)
  10. RED      = ( 255,   0,   0)
  11. GREEN    = (   0, 255,   0)
  12.  
  13. # Screen dimensions
  14. SCREEN_WIDTH  = 800
  15. SCREEN_HEIGHT = 600
  16.  
  17. class Player(pygame.sprite.Sprite):
  18.     """
  19.    This class represents the bar at the bottom that the player controls.
  20.    """
  21.  
  22.     # -- Methods
  23.     def __init__(self):
  24.         """ Constructor function """
  25.  
  26.         # Call the parent's constructor
  27.         super().__init__()
  28.  
  29.         # Create an image of the block, and fill it with a color.
  30.         # This could also be an image loaded from the disk.
  31.         width = 40
  32.         height = 60
  33.         self.image = pygame.Surface([width, height])
  34.         self.image.fill(RED)
  35.  
  36.         # Set a referance to the image rect.
  37.         self.rect = self.image.get_rect()
  38.  
  39.         # Set speed vector of player
  40.         self.change_x = 0
  41.         self.change_y = 0
  42.  
  43.         # List of sprites we can bump against
  44.         self.level = None
  45.  
  46.     def update(self):
  47.         """ Move the player. """
  48.         # Gravity
  49.         self.calc_grav()
  50.  
  51.         # Move left/right
  52.         self.rect.x += self.change_x
  53.  
  54.         # See if we hit anything
  55.         block_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False)
  56.         for block in block_hit_list:
  57.             # If we are moving right,
  58.             # set our right side to the left side of the item we hit
  59.             if self.change_x > 0:
  60.                 self.rect.right = block.rect.left
  61.             elif self.change_x < 0:
  62.                 # Otherwise if we are moving left, do the opposite.
  63.                 self.rect.left = block.rect.right
  64.  
  65.         # Move up/down
  66.         self.rect.y += self.change_y
  67.  
  68.         # Check and see if we hit anything
  69.         block_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False)
  70.         for block in block_hit_list:
  71.  
  72.             # Reset our position based on the top/bottom of the object.
  73.             if self.change_y > 0:
  74.                 self.rect.bottom = block.rect.top
  75.             elif self.change_y < 0:
  76.                 self.rect.top = block.rect.bottom
  77.  
  78.             # Stop our vertical movement
  79.             self.change_y = 0
  80.  
  81.     def calc_grav(self):
  82.         """ Calculate effect of gravity. """
  83.         if self.change_y == 0:
  84.             self.change_y = 1
  85.         else:
  86.             self.change_y += .35
  87.  
  88.         # See if we are on the ground.
  89.         if self.rect.y >= SCREEN_HEIGHT - self.rect.height and self.change_y >= 0:
  90.             self.change_y = 0
  91.             self.rect.y = SCREEN_HEIGHT - self.rect.height
  92.  
  93.     def jump(self):
  94.         """ Called when user hits 'jump' button. """
  95.  
  96.         # move down a bit and see if there is a platform below us.
  97.         # Move down 2 pixels because it doesn't work well if we only move down 1
  98.         # when working with a platform moving down.
  99.         self.rect.y += 2
  100.         platform_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False)
  101.         self.rect.y -= 2
  102.  
  103.         # If it is ok to jump, set our speed upwards
  104.         if len(platform_hit_list) > 0 or self.rect.bottom >= SCREEN_HEIGHT:
  105.             self.change_y = -10
  106.  
  107.     # Player-controlled movement:
  108.     def go_left(self):
  109.         """ Called when the user hits the left arrow. """
  110.         self.change_x = -6
  111.  
  112.     def go_right(self):
  113.         """ Called when the user hits the right arrow. """
  114.         self.change_x = 6
  115.  
  116.     def stop(self):
  117.         """ Called when the user lets off the keyboard. """
  118.         self.change_x = 0
  119.  
  120. class Platform(pygame.sprite.Sprite):
  121.     """ Platform the user can jump on """
  122.  
  123.     def __init__(self, width, height):
  124.         """ Platform constructor. Assumes constructed with user passing in
  125.            an array of 5 numbers like what's defined at the top of this code.
  126.            """
  127.         super().__init__()
  128.  
  129.         self.image = pygame.Surface([width, height])
  130.         self.image.fill(GREEN)
  131.  
  132.         self.rect = self.image.get_rect()
  133.  
  134. class Level():
  135.     """ This is a generic super-class used to define a level.
  136.        Create a child class for each level with level-specific
  137.        info. """
  138.  
  139.     # Lists of sprites used in all levels. Add or remove
  140.     # lists as needed for your game.
  141.     platform_list = None
  142.     enemy_list = None
  143.  
  144.     # How far this world has been scrolled left/right
  145.     world_shift = 0
  146.  
  147.     def __init__(self, player):
  148.         """ Constructor. Pass in a handle to player. Needed for when moving
  149.            platforms collide with the player. """
  150.         self.platform_list = pygame.sprite.Group()
  151.         self.enemy_list = pygame.sprite.Group()
  152.         self.player = player
  153.  
  154.     # Update everythign on this level
  155.     def update(self):
  156.         """ Update everything in this level."""
  157.         self.platform_list.update()
  158.         self.enemy_list.update()
  159.  
  160.     def draw(self, screen):
  161.         """ Draw everything on this level. """
  162.  
  163.         # Draw the background
  164.         screen.fill(BLUE)
  165.  
  166.         # Draw all the sprite lists that we have
  167.         self.platform_list.draw(screen)
  168.         self.enemy_list.draw(screen)
  169.  
  170.     def shift_world(self, shift_x):
  171.         """ When the user moves left/right and we need to scroll everything: """
  172.  
  173.         # Keep track of the shift amount
  174.         self.world_shift += shift_x
  175.  
  176.         # Go through all the sprite lists and shift
  177.         for platform in self.platform_list:
  178.             platform.rect.x += shift_x
  179.  
  180.         for enemy in self.enemy_list:
  181.             enemy.rect.x += shift_x
  182.  
  183. # Create platforms for the level
  184. class Level_01(Level):
  185.     """ Definition for level 1. """
  186.  
  187.     def __init__(self, player):
  188.         """ Create level 1. """
  189.  
  190.         # Call the parent constructor
  191.         Level.__init__(self, player)
  192.  
  193.         self.level_limit = -1000
  194.  
  195.         # Array with width, height, x, and y of platform
  196.         level = [[210, 70, 500, 500],
  197.                  [210, 70, 800, 400],
  198.                  [210, 70, 1000, 500],
  199.                  [210, 70, 1120, 280],
  200.                  ]
  201.  
  202.  
  203.         # Go through the array above and add platforms
  204.         for platform in level:
  205.             block = Platform(platform[0], platform[1])
  206.             block.rect.x = platform[2]
  207.             block.rect.y = platform[3]
  208.             block.player = self.player
  209.             self.platform_list.add(block)
  210.  
  211. # Create platforms for the level
  212. class Level_02(Level):
  213.     """ Definition for level 2. """
  214.  
  215.     def __init__(self, player):
  216.         """ Create level 1. """
  217.  
  218.         # Call the parent constructor
  219.         Level.__init__(self, player)
  220.  
  221.         self.level_limit = -1000
  222.  
  223.         # Array with type of platform, and x, y location of the platform.
  224.         level = [[210, 30, 450, 570],
  225.                  [210, 30, 850, 420],
  226.                  [210, 30, 1000, 520],
  227.                  [210, 30, 1120, 280],
  228.                  ]
  229.  
  230.  
  231.         # Go through the array above and add platforms
  232.         for platform in level:
  233.             block = Platform(platform[0], platform[1])
  234.             block.rect.x = platform[2]
  235.             block.rect.y = platform[3]
  236.             block.player = self.player
  237.             self.platform_list.add(block)
  238.  
  239. def main():
  240.     """ Main Program """
  241.     pygame.init()
  242.  
  243.     # Set the height and width of the screen
  244.     size = [SCREEN_WIDTH, SCREEN_HEIGHT]
  245.     screen = pygame.display.set_mode(size)
  246.  
  247.     pygame.display.set_caption("Side-scrolling Platformer")
  248.  
  249.     # Create the player
  250.     player = Player()
  251.  
  252.     # Create all the levels
  253.     level_list = []
  254.     level_list.append(Level_01(player))
  255.     level_list.append(Level_02(player))
  256.  
  257.     # Set the current level
  258.     current_level_no = 0
  259.     current_level = level_list[current_level_no]
  260.  
  261.     active_sprite_list = pygame.sprite.Group()
  262.     player.level = current_level
  263.  
  264.     player.rect.x = 340
  265.     player.rect.y = SCREEN_HEIGHT - player.rect.height
  266.     active_sprite_list.add(player)
  267.  
  268.     #Loop until the user clicks the close button.
  269.     done = False
  270.  
  271.     # Used to manage how fast the screen updates
  272.     clock = pygame.time.Clock()
  273.  
  274.     # -------- Main Program Loop -----------
  275.     while not done:
  276.         for event in pygame.event.get(): # User did something
  277.             if event.type == pygame.QUIT: # If user clicked close
  278.                 done = True # Flag that we are done so we exit this loop
  279.  
  280.             if event.type == pygame.KEYDOWN:
  281.                 if event.key == pygame.K_LEFT:
  282.                     player.go_left()
  283.                 if event.key == pygame.K_RIGHT:
  284.                     player.go_right()
  285.                 if event.key == pygame.K_UP:
  286.                     player.jump()
  287.  
  288.             if event.type == pygame.KEYUP:
  289.                 if event.key == pygame.K_LEFT and player.change_x < 0:
  290.                     player.stop()
  291.                 if event.key == pygame.K_RIGHT and player.change_x > 0:
  292.                     player.stop()
  293.  
  294.         # Update the player.
  295.         active_sprite_list.update()
  296.  
  297.         # Update items in the level
  298.         current_level.update()
  299.        
  300.         # If the player gets near the right side, shift the world left (-x)
  301.         if player.rect.right >= 500:
  302.             diff = player.rect.right - 500
  303.             player.rect.right = 500
  304.             current_level.shift_world(-diff)
  305.  
  306.         # If the player gets near the left side, shift the world right (+x)
  307.         if player.rect.left <= 120:
  308.             diff = 120 - player.rect.left
  309.             player.rect.left = 120
  310.             current_level.shift_world(diff)
  311.  
  312.         # If the player gets to the end of the level, go to the next level
  313.         current_position = player.rect.x + current_level.world_shift
  314.         if current_position < current_level.level_limit:
  315.             player.rect.x = 120
  316.             if current_level_no < len(level_list)-1:
  317.                 current_level_no += 1
  318.                 current_level = level_list[current_level_no]
  319.                 player.level = current_level
  320.  
  321.         # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT
  322.         current_level.draw(screen)
  323.         active_sprite_list.draw(screen)
  324.  
  325.         # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT
  326.  
  327.         # Limit to 60 frames per second
  328.         clock.tick(60)
  329.  
  330.         # Go ahead and update the screen with what we've drawn.
  331.         pygame.display.flip()
  332.  
  333.     # Be IDLE friendly. If you forget this line, the program will 'hang'
  334.     # on exit.
  335.     pygame.quit()
  336.  
  337. if __name__ == "__main__":
  338.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement