Matuiss2

Python simple snake game v1.23

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