Advertisement
furas

Python - PyGame - Snake

Jan 7th, 2016
388
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.25 KB | None | 0 0
  1. import pygame
  2. import random
  3.  
  4. #
  5. # pygame (simple) template by furas
  6. #
  7.  
  8. # === CONSTANTS === UPPER_CASE names
  9.  
  10. DISPLAY_WIDTH = 800
  11. DISPLAY_HEIGHT = 600
  12.  
  13. FPS = 5
  14.  
  15. BLACK = (  0,   0,   0)
  16. WHITE = (255, 255, 255)
  17.  
  18. RED   = (255,   0,   0)
  19. GREEN = (  0, 255,   0)
  20. BLUE  = (  0,   0, 255)
  21.  
  22. BLOCK_SIZE = 50
  23.  
  24. # === CLASSES === CamelCase names
  25.  
  26. class Snake(): # now it is almost Snake(pygame.sprite.Sprite):
  27.  
  28.     def __init__(self, screen, x, y, tail_color=GREEN, head_color=BLUE):
  29.    
  30.         self.screen = screen
  31.         self.screen_rect = screen.get_rect()
  32.        
  33.         # single tile position and size
  34.         self.rect = pygame.Rect(x, y, BLOCK_SIZE, BLOCK_SIZE)
  35.  
  36.         # add one tile at start - `self.make_longer` will add more tiles
  37.         self.tiles = [self.rect]
  38.  
  39.         # add automatically new 5 tiles (one tile in every step)
  40.         self.make_longer = 5
  41.  
  42.         # you can use image file like PNG
  43.         self.image_head = pygame.Surface( (BLOCK_SIZE, BLOCK_SIZE) )
  44.         self.image_head.fill(head_color)
  45.  
  46.         self.image_tail = pygame.Surface( (BLOCK_SIZE, BLOCK_SIZE) )
  47.         self.image_tail.fill(tail_color)
  48.  
  49.         # speed
  50.         self.x_change = 0
  51.         self.y_change = 0
  52.  
  53.  
  54.     def draw(self):
  55.         # draw all tiles without head ([1:])
  56.         for tile_rect in self.tiles[1:]:
  57.             self.screen.blit(self.image_tail, tile_rect)
  58.  
  59.         # draw head ([0])
  60.         self.screen.blit(self.image_head, self.tiles[0])
  61.  
  62.  
  63.     def update(self):
  64.         # create new head
  65.         self.head_rect = self.tiles[0].move(self.x_change, self.y_change)
  66.  
  67.         # wall colision - is head still on screen ?
  68.         if not self.screen_rect.contains(self.head_rect):
  69.             return False # dead
  70.            
  71.         # add head at beginning of tiles (now snake is longer)
  72.         self.tiles.insert(0, self.head_rect)
  73.  
  74.         # make snake longer
  75.         if not self.make_longer:
  76.             # remove last tile to keep the same width
  77.             del self.tiles[-1]
  78.         else:
  79.             # make longer (one tile in every step)          
  80.             self.make_longer -= 1
  81.  
  82.         return True # still alive
  83.  
  84.            
  85.     def add(self):
  86.         # add one tile to self.tiles
  87.         self.make_longer = 1
  88.        
  89.  
  90. class Food(): # now it is almost Food(pygame.sprite.Sprite):
  91.  
  92.     def __init__(self, screen):
  93.         self.screen = screen
  94.  
  95.         # apple position and size
  96.         self.rect = pygame.Rect(0, 0, BLOCK_SIZE, BLOCK_SIZE)
  97.         self.spawn() # set random position
  98.        
  99.         # you can use image from file like PNG
  100.         self.image = pygame.Surface( (BLOCK_SIZE, BLOCK_SIZE) )
  101.         self.image.fill(RED)
  102.  
  103.     def spawn(self):
  104.         self.rect.x = random.randrange(0, 800, BLOCK_SIZE)
  105.         self.rect.y = random.randrange(0, 600, BLOCK_SIZE)
  106.  
  107.     def draw(self):
  108.         self.screen.blit(self.image, self.rect)
  109.  
  110. # === FUNCTIONS === lower_case names
  111.  
  112.  
  113. def main():
  114.  
  115.     score = 0
  116.    
  117.     # --- init ---
  118.    
  119.     pygame.init()
  120.    
  121.     game_display = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT))
  122.     game_display_rect = game_display.get_rect()
  123.    
  124.     pygame.display.set_caption('Snake')
  125.  
  126.     # --- objects ---
  127.    
  128.     schlange = Snake(game_display, game_display_rect.centerx, game_display_rect.centery, GREEN)
  129.     essen = Food(game_display)
  130.  
  131.     # --- (constants) texts ---
  132.    
  133.     font = pygame.font.SysFont(None, 50)
  134.  
  135.     text_pause = font.render('PAUSE', True, WHITE)
  136.     text_pause_rect = text_pause.get_rect()
  137.     # center on screen
  138.     text_pause_rect.center = game_display_rect.center
  139.    
  140.     text_game_over = font.render('GAME OVER', True, WHITE)
  141.     text_game_over_rect = text_game_over.get_rect()
  142.     # center on screen
  143.     text_game_over_rect.center = game_display_rect.center
  144.  
  145.     # --- (changing) texts ---
  146.  
  147.     text_score = font.render('SCORE: '+ str(score), True, WHITE)
  148.     text_score_rect = text_game_over.get_rect()
  149.     # left top cornert
  150.     text_score_rect.left = game_display_rect.left
  151.     text_score_rect.top = game_display_rect.top
  152.    
  153.     # --- mainloop ---
  154.  
  155.     paused = False
  156.     alive = True
  157.    
  158.     clock = pygame.time.Clock()
  159.     running = True
  160.  
  161.     while running:
  162.  
  163.         # --- envents ---
  164.        
  165.         for event in pygame.event.get():
  166.  
  167.             # --- global events ---
  168.            
  169.             if event.type == pygame.QUIT:
  170.                 running = False
  171.  
  172.             # --- player events ---
  173.            
  174.             # you can move it into Snake.event_handle(event)
  175.             # and call schlange.event_handle(event)
  176.                
  177.             if event.type == pygame.KEYDOWN:
  178.                
  179.                 if event.key == pygame.K_UP:
  180.                     if schlange.y_change == 0: # don't move backword
  181.                         schlange.x_change = 0
  182.                         schlange.y_change = -50
  183.  
  184.                 elif event.key == pygame.K_DOWN:
  185.                     if schlange.y_change == 0: # don't move backword
  186.                         schlange.x_change = 0
  187.                         schlange.y_change = 50
  188.  
  189.                 elif event.key == pygame.K_LEFT:
  190.                     if schlange.x_change == 0: # don't move backword
  191.                         schlange.x_change = -50
  192.                         schlange.y_change = 0
  193.  
  194.                 elif event.key == pygame.K_RIGHT:
  195.                     if schlange.x_change == 0: # don't move backword
  196.                         schlange.x_change = 50
  197.                         schlange.y_change = 0
  198.  
  199.                 elif event.key == pygame.K_SPACE:
  200.                     # pause/unpause game
  201.                     paused = not paused
  202.                    
  203.         # --- updates (without draws) ---
  204.  
  205.         if not paused and alive:
  206.             # move snake
  207.             alive = schlange.update()
  208.  
  209.             if alive:
  210.                 # check snake head collision with apple
  211.                 if schlange.tiles[0].colliderect(essen.rect):
  212.                     # move apple to new position
  213.                     essen.spawn()
  214.                     # make snake longer
  215.                     schlange.add()
  216.  
  217.                     # new score and new text
  218.                     score += 1
  219.  
  220.                     text_score = font.render('SCORE: '+ str(score), True, WHITE)
  221.                     text_score_rect = text_game_over.get_rect()
  222.                     # left top cornert
  223.                     text_score_rect.left = game_display_rect.left
  224.                     text_score_rect.top = game_display_rect.top
  225.  
  226.         # --- all draws (without updates) ---
  227.  
  228.        
  229.         # background
  230.         game_display.fill(BLACK)
  231.  
  232.         # objects
  233.         schlange.draw()
  234.         essen.draw()
  235.  
  236.         # text and decorations
  237.  
  238.         game_display.blit(text_score, text_score_rect)
  239.  
  240.         if paused:
  241.             game_display.blit(text_pause, text_pause_rect)
  242.  
  243.         if not alive:
  244.             game_display.blit(text_game_over, text_game_over_rect)
  245.            
  246.         # move on screen
  247.         clock.tick(FPS)
  248.         pygame.display.update()
  249.  
  250.     # --- the end ---
  251.  
  252.     # quit or create ending screen
  253.     pygame.quit()
  254.  
  255. # ---------------------------------------------------------------------
  256.    
  257. if __name__ == '__main__':
  258.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement