Advertisement
Guest User

Code Snake Python

a guest
May 29th, 2016
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.85 KB | None | 0 0
  1. import pygame
  2. import random
  3. import pickle
  4.  
  5. pygame.init()
  6.  
  7. # Our colors
  8. white = [255, 255, 255]
  9. black = [0, 0, 0]
  10. lightblue = [185, 243, 255]
  11. lightgreen = [59, 207, 70]
  12. red = [255, 0, 0]
  13. grey = [148, 148, 148]
  14. transparent_black = [0, 0, 0, 0.3]
  15. green = [0, 155, 0]
  16.  
  17. screen_width = 800      # Our screen width
  18. screen_height = 600     # Our screen height
  19.  
  20. screen = pygame.display.set_mode((screen_width, screen_height))    # We create our screen
  21. pygame.display.set_caption("Snake")
  22. icon = pygame.image.load("icon.png")
  23. pygame.display.set_icon(icon)
  24.  
  25. sprite_head = pygame.image.load("snakebig_sprite.png")
  26. sprite_apple = pygame.image.load("applebig_sprite.png")
  27.  
  28. clock = pygame.time.Clock()     # We set the clock for the FPS
  29.  
  30. block_size = 20     # The size of one block (one part of the snake)
  31.  
  32. direction = "right"
  33.  
  34. xsmallfont = pygame.font.Font("Amatic.ttf", 20)
  35. smallfont = pygame.font.Font("Amatic.ttf", 30)
  36. mediumfont = pygame.font.Font("Amatic.ttf", 60)
  37. largefont = pygame.font.Font("Amatic.ttf", 80)
  38.  
  39.  
  40. def start_menu():
  41.     """ Function that handles the start menu of the game"""
  42.     intro = True
  43.  
  44.     while intro:
  45.  
  46.         for event in pygame.event.get():
  47.             if event.type == pygame.QUIT:
  48.                 pygame.quit()
  49.                 quit()
  50.             if event.type == pygame.KEYDOWN:
  51.                 if event.key == pygame.K_SPACE:
  52.                     intro = False
  53.  
  54.         screen.fill(lightblue)
  55.         message("Welcome to Snake", green, y_displace=-100, size="large")
  56.         message("Eat the apples and get bigger !", black, y_displace=-30, size="small")
  57.         message("Don't run into yourself or the edges, or you will die...", black, y_displace=10, size="small")
  58.         message("Press Space to start the game", red, y_displace=70, size="medium")
  59.         message("By Alexis", black, y_displace=140, size="xsmall")
  60.         pygame.display.update()
  61.         clock.tick(10)  # 10 FPS
  62.  
  63.  
  64. def snake(snakelist, block_size):
  65.     """Function used to create the snake
  66.  
  67.    Arguments:
  68.        snakelist (list): List containing the snake's coordinates of each block
  69.        block_size (int): Size of a block"""
  70.  
  71.     if direction == "right":
  72.         head = pygame.transform.rotate(sprite_head, 270)
  73.     if direction == "left":
  74.         head = pygame.transform.rotate(sprite_head, 90)
  75.     if direction == "up":
  76.         head = sprite_head
  77.     if direction == "down":
  78.         head = pygame.transform.rotate(sprite_head, 180)
  79.  
  80.     screen.blit(head, (snakelist[-1][0], snakelist[-1][1]))
  81.     for XnY in snakelist[:-1]:
  82.         pygame.draw.rect(screen, lightgreen, [XnY[0], XnY[1], block_size, block_size])     # Set one snake block to a light green 10*10 rectangle
  83.  
  84.  
  85. def apple():
  86.     apple_randX = random.randrange(0, screen_width - block_size, block_size)    # We create a new one
  87.     apple_randY = random.randrange(0, screen_height - block_size, block_size)
  88.  
  89.     return apple_randX, apple_randY
  90.  
  91.  
  92. def message(msg, color, y_displace=0, size="medium"):
  93.     """Function that print's to the screen a message, with a color
  94.  
  95.    Arguments:
  96.        msg {str} -- The message to be displayed
  97.        color {variable} -- The variable of the color"""
  98.     if size == "xsmall":
  99.         screen_text = xsmallfont.render(msg, True, color)
  100.     if size == "small":
  101.         screen_text = smallfont.render(msg, True, color)
  102.     elif size == "medium":
  103.         screen_text = mediumfont.render(msg, True, color)
  104.     elif size == "large":
  105.         screen_text = largefont.render(msg, True, color)
  106.  
  107.     screen.blit(screen_text, [screen_width / 2 - screen_text.get_rect().width / 2, screen_height / 2 - screen_text.get_rect().height / 2 + y_displace])     # We display the text in the middle of the screen
  108.  
  109.  
  110. def score(score, highscore):
  111.     text = smallfont.render("Score : " + str(score), True, black)
  112.     screen.blit(text, [0, 0])
  113.     if score > highscore:
  114.         highscore_file = open("highscore.txt", "wb")
  115.         pickle.dump(highscore, highscore_file)
  116.  
  117.  
  118. def pause():
  119.     """Function that pauses the game"""
  120.     paused = True
  121.     message("Game is paused", black, y_displace=-20, size="large")
  122.     message("Press P to resume", grey, y_displace=50, size="medium")
  123.     pygame.display.update()
  124.     while paused:
  125.         for event in pygame.event.get():
  126.             if event.type == pygame.KEYDOWN:
  127.                 if event.key == pygame.K_p:
  128.                     paused = False
  129.  
  130.  
  131. def game_loop():
  132.  
  133.     global direction
  134.  
  135.     highscore_file = open("highscore.txt", "rb")
  136.     highscore = pickle.load(highscore_file)
  137.     highscore_file.close()
  138.  
  139.     direction = "right"     # The initial direction is right
  140.  
  141.     game_exit = False    # We set game_exit to be false
  142.     game_over = False    # We set game_over to be false
  143.  
  144.     head_x = screen_width / 2    # The initial X position of the snake's head, at the middle of the X axis
  145.     head_y = screen_height / 2    # The initial  Y position of the snake's head, at the middle of the Y axis
  146.  
  147.     head_x_change = 20   # Variable used to move the snake's head on the X axis
  148.     head_y_change = 0   # Variable used to move the snake's head on the Y axis
  149.  
  150.     snakelist = []      # List containing all the coordinates of the blocks composing the snake
  151.     snakelength = 1     # At the beginning, our snake length is 1
  152.  
  153.     apple_randX, apple_randY = apple()  # X and Y position of the apple
  154.  
  155.     while not game_exit:    # Our game loop
  156.  
  157.         while game_over is True:    # Game Over screen
  158.             screen.fill(lightblue)
  159.             message("Game Over !", red, y_displace=-70, size="large")
  160.             message("Your score : " + str(score_value), black, y_displace=20, size="small")
  161.             message("Highscore :" + str(highscore), black, y_displace=50, size="small")
  162.             message("R to Retry, Q to Quit", black, 100)
  163.             pygame.display.update()
  164.             for event in pygame.event.get():
  165.                 if event.type == pygame.QUIT:   # If the user want's to exit the game (by clicking on the red cross or Alt + F4)
  166.                     game_exit = True
  167.                     game_over = False
  168.                 if event.type == pygame.KEYDOWN:
  169.                     if event.key == pygame.K_a:     # If the key pressed is Q (A on an AZERTY keyboard)
  170.                         game_exit = True
  171.                         game_over = False
  172.                     if event.key == pygame.K_r:     # If the key pressed is R
  173.                         game_loop()     # Start over the game
  174.  
  175.         for event in pygame.event.get():    # Our event handler
  176.             if event.type == pygame.QUIT:       # If the user wants to quit (e.g. by clicking on the red cross)
  177.                 game_exit = True    # We set game_exit to True in order to exit the game loop
  178.             if event.type == pygame.KEYDOWN:    # When the user presses a key
  179.                 if event.key == pygame.K_LEFT:      # If the key is the left arrow
  180.                     if direction == "right":
  181.                         continue
  182.                     direction = "left"
  183.                     head_x_change = -20
  184.                     head_y_change = 0
  185.                 elif event.key == pygame.K_RIGHT:     # If the key is the right arrow
  186.                     if direction == "left":
  187.                         continue
  188.                     direction = "right"
  189.                     head_x_change = 20
  190.                     head_y_change = 0
  191.                 elif event.key == pygame.K_UP:      # If the key is the up arrow
  192.                     if direction == "down":
  193.                         continue
  194.                     direction = "up"
  195.                     head_y_change = -20
  196.                     head_x_change = 0
  197.                 elif event.key == pygame.K_DOWN:      # If the key is the down arrow
  198.                     if direction == "up":
  199.                         continue
  200.                     direction = "down"
  201.                     head_y_change = 20
  202.                     head_x_change = 0
  203.                 elif event.key == pygame.K_p:       # If the key is p
  204.                     pause()     # We pause the game
  205.  
  206.         head_x += head_x_change     # We move the head
  207.         head_y += head_y_change
  208.  
  209.         if head_x >= screen_width or head_x < 0 or head_y >= screen_height or head_y < 0:    # If the snake's head touches the screen
  210.             game_over = True    # We exit the game loop
  211.  
  212.         screen.fill(lightblue)      # Set background color to a light blue
  213.         # pygame.draw.rect(screen, red, [apple_randX, apple_randY, block_size, block_size])
  214.  
  215.         screen.blit(sprite_apple, (apple_randX, apple_randY))
  216.  
  217.         snakehead = []       # List containing the X and the Y coordinates of the snake's head
  218.         snakehead.append(head_x)    # We add the head_x variable to the snakehead list
  219.         snakehead.append(head_y)    # We add the head_y variable to the snakehead list
  220.         snakelist.append(snakehead)     # We then add the snakehead coordinates to our snakelist
  221.  
  222.         if len(snakelist) > snakelength:    # When the snake advances, it gets bigger on the front, so we need to delete the end
  223.             del snakelist[0]    # We delete the first block
  224.  
  225.         for segment in snakelist[:-1]:      # We go through each segment in the snake's body except the last element, which is the head
  226.             if segment == snakehead:    # If the snake's head touches its body
  227.                 game_over = True
  228.  
  229.         score_value = snakelength - 1
  230.         snake(snakelist, block_size)    # We create our snake
  231.         score(score_value, highscore)  # We update the score
  232.         pygame.display.update()     # We update the screen
  233.  
  234.         if head_x == apple_randX and head_y == apple_randY:     # If the snake reaches the apple
  235.             apple_randX, apple_randY = apple()  # We create a new apple
  236.             snakelength += 1    # The snake becomes longer
  237.  
  238.         clock.tick(17)  # 17 FPS
  239.  
  240.     pygame.quit()
  241.     quit()
  242.  
  243. start_menu()
  244. game_loop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement