Matuiss2

Python simple snake game v1.01

Nov 29th, 2017
3,453
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.70 KB | None | 0 0
  1. # V 1.0 - Functional game
  2. # V 1.01 - Improves the readability, improves slightly the performance
  3. import pygame
  4. import sys
  5. import time
  6. import random
  7.  
  8.  
  9. def main():
  10.     """Snake v 1.01"""
  11.     score = 0  # Initial score
  12.     fps = pygame.time.Clock()
  13.     direction = "RIGHT"  # Initial direction
  14.     snake_position = [100, 50]  # Initial snake position
  15.     snake_body = [[100, 50], [90, 50], [100, 50]]  # Initial snake body
  16.     # It places the food randomly, excluding the border
  17.     food_position = [random.randint(1, 71) * 10, random.randint(1, 45) * 10]
  18.     food_spawn = True
  19.     # Game surface
  20.     player_screen = pygame.display.set_mode((720, 460))  # Set screen size
  21.     pygame.display.set_caption("Snake v.1.01")  # Set screen title and version
  22.     # Will define the colors
  23.     red = pygame.Color("red")
  24.     green = pygame.Color("green")
  25.     black = pygame.Color("black")
  26.     orange = pygame.Color("orange")
  27.     white = pygame.Color("white")
  28.  
  29.     def bug_check():
  30.         """ Checks the mistakes, and closes the program if it does while
  31.        printing on the console how many bugs it has """
  32.         bugs = pygame.init()
  33.         if bugs[1] > 0:
  34.             print("There are", bugs[1], "bugs! quiting.....")
  35.             time.sleep(3)
  36.             sys.exit("Closing program")
  37.         else:
  38.             print("The game was initialized")
  39.  
  40.     def you_lose():
  41.         """ When the players loses, it will show a red message in times new
  42.         roman font with 44 px size in a rectangle box"""
  43.         font_game_over = pygame.font.SysFont("times new roman", 44)
  44.         game_over_surface = font_game_over.render("Game over :(", True, red)
  45.         game_over_position = game_over_surface.get_rect()
  46.         game_over_position.midtop = (360, 15)
  47.         player_screen.blit(game_over_surface, game_over_position)
  48.         scoring(1)
  49.         pygame.display.flip()  # Updates the screen, so it doesnt freeze
  50.         quiting()
  51.  
  52.     def quiting():
  53.         """ When this function is called, it will wait 4 seconds and exit"""
  54.         time.sleep(4)
  55.         pygame.quit()
  56.         sys.exit()
  57.  
  58.     def scoring(game_over=0):
  59.         """ It will show the score on the top-left side of the screen in times new
  60.        roman font with 16px size and black color in a rectangle box"""
  61.         score_font = pygame.font.SysFont("times new roman", 16)
  62.         score_surface = score_font.render("Score : {}".format(score), True, black)
  63.         score_position = score_surface.get_rect()
  64.         if game_over == 0:  # By default it puts it on the top-left
  65.             score_position.midtop = (40, 10)
  66.         else:  # Unless its game over, where it puts below the game over message
  67.             score_position.midtop = (360, 80)
  68.         player_screen.blit(score_surface, score_position)
  69.  
  70.     bug_check()
  71.     while True:
  72.         for event in pygame.event.get():
  73.             if event.type == pygame.QUIT:
  74.                 quiting()
  75.             elif event.type == pygame.KEYDOWN:
  76.                 # Choose direction by user input, block opposite directions
  77.                 key_right = event.key == pygame.K_RIGHT or event.key == ord("d")
  78.                 key_left = event.key == pygame.K_LEFT or event.key == ord("a")
  79.                 key_down = event.key == pygame.K_DOWN or event.key == ord("s")
  80.                 key_up = event.key == pygame.K_UP or event.key == ord("w")
  81.                 if key_right and direction != "LEFT":
  82.                     direction = "RIGHT"
  83.                 elif key_left and direction != "RIGHT":
  84.                     direction = "LEFT"
  85.                 elif key_down and direction != "UP":
  86.                     direction = "DOWN"
  87.                 elif key_up and direction != "DOWN":
  88.                     direction = "UP"
  89.                 elif event.key == pygame.K_ESCAPE:
  90.                     quiting()  # It will quit when esc is pressed
  91.         # Simulates the snake movement(together with snake_body_pop)
  92.         if direction == "RIGHT":
  93.             snake_position[0] += 10
  94.         elif direction == "LEFT":
  95.             snake_position[0] -= 10
  96.         elif direction == "DOWN":
  97.             snake_position[1] += 10
  98.         elif direction == "UP":
  99.             snake_position[1] -= 10
  100.         # Body mechanics
  101.         snake_body.insert(0, list(snake_position))
  102.         if snake_position == food_position:
  103.             score += 1  # Every food taken will raise the score by 1
  104.             food_spawn = False  # It removes the food from the board
  105.         else:
  106.             # If the food is taken it will not remove the last body piece(raising snakes size)
  107.             snake_body.pop()
  108.         if food_spawn is False:  # When a food is taken it will respawn randomly
  109.             food_position = [random.randint(1, 71) * 10, random.randint(1, 45) * 10]
  110.         food_spawn = True  # It will set the food to True again, to keep the cycle
  111.         # Drawing
  112.         player_screen.fill(white)  # Set the background to white
  113.         for position in snake_body:  # Snake representation on the screen
  114.             pygame.draw.rect(player_screen, green, pygame.Rect(position[0], position[1], 10, 10))
  115.         # Food representation on the screen
  116.         pygame.draw.rect(player_screen, orange, pygame.Rect(food_position[0], food_position[1], 10, 10))
  117.         if snake_position[0] not in range(0, 711) or snake_position[1] not in range(0, 451):
  118.             you_lose()  # Game over when the Snake hit a wall
  119.         for block in snake_body[1:]:
  120.             if snake_position == block:
  121.                 you_lose()  # Game over when the Snake hits itself
  122.         scoring()
  123.         pygame.display.flip()  # It constantly updates the screen
  124.         fps.tick(20)  # It sets the speed to a playable value
  125.  
  126.  
  127. if __name__ == "__main__":
  128.     main()
Advertisement
Add Comment
Please, Sign In to add comment