Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pygame
- import random
- import pickle
- pygame.init()
- # Our colors
- white = [255, 255, 255]
- black = [0, 0, 0]
- lightblue = [185, 243, 255]
- lightgreen = [59, 207, 70]
- red = [255, 0, 0]
- grey = [148, 148, 148]
- transparent_black = [0, 0, 0, 0.3]
- green = [0, 155, 0]
- screen_width = 800 # Our screen width
- screen_height = 600 # Our screen height
- screen = pygame.display.set_mode((screen_width, screen_height)) # We create our screen
- pygame.display.set_caption("Snake")
- icon = pygame.image.load("icon.png")
- pygame.display.set_icon(icon)
- sprite_head = pygame.image.load("snakebig_sprite.png")
- sprite_apple = pygame.image.load("applebig_sprite.png")
- clock = pygame.time.Clock() # We set the clock for the FPS
- block_size = 20 # The size of one block (one part of the snake)
- direction = "right"
- xsmallfont = pygame.font.Font("Amatic.ttf", 20)
- smallfont = pygame.font.Font("Amatic.ttf", 30)
- mediumfont = pygame.font.Font("Amatic.ttf", 60)
- largefont = pygame.font.Font("Amatic.ttf", 80)
- def start_menu():
- """ Function that handles the start menu of the game"""
- intro = True
- while intro:
- for event in pygame.event.get():
- if event.type == pygame.QUIT:
- pygame.quit()
- quit()
- if event.type == pygame.KEYDOWN:
- if event.key == pygame.K_SPACE:
- intro = False
- screen.fill(lightblue)
- message("Welcome to Snake", green, y_displace=-100, size="large")
- message("Eat the apples and get bigger !", black, y_displace=-30, size="small")
- message("Don't run into yourself or the edges, or you will die...", black, y_displace=10, size="small")
- message("Press Space to start the game", red, y_displace=70, size="medium")
- message("By Alexis", black, y_displace=140, size="xsmall")
- pygame.display.update()
- clock.tick(10) # 10 FPS
- def snake(snakelist, block_size):
- """Function used to create the snake
- Arguments:
- snakelist (list): List containing the snake's coordinates of each block
- block_size (int): Size of a block"""
- if direction == "right":
- head = pygame.transform.rotate(sprite_head, 270)
- if direction == "left":
- head = pygame.transform.rotate(sprite_head, 90)
- if direction == "up":
- head = sprite_head
- if direction == "down":
- head = pygame.transform.rotate(sprite_head, 180)
- screen.blit(head, (snakelist[-1][0], snakelist[-1][1]))
- for XnY in snakelist[:-1]:
- pygame.draw.rect(screen, lightgreen, [XnY[0], XnY[1], block_size, block_size]) # Set one snake block to a light green 10*10 rectangle
- def apple():
- apple_randX = random.randrange(0, screen_width - block_size, block_size) # We create a new one
- apple_randY = random.randrange(0, screen_height - block_size, block_size)
- return apple_randX, apple_randY
- def message(msg, color, y_displace=0, size="medium"):
- """Function that print's to the screen a message, with a color
- Arguments:
- msg {str} -- The message to be displayed
- color {variable} -- The variable of the color"""
- if size == "xsmall":
- screen_text = xsmallfont.render(msg, True, color)
- if size == "small":
- screen_text = smallfont.render(msg, True, color)
- elif size == "medium":
- screen_text = mediumfont.render(msg, True, color)
- elif size == "large":
- screen_text = largefont.render(msg, True, color)
- 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
- def score(score, highscore):
- text = smallfont.render("Score : " + str(score), True, black)
- screen.blit(text, [0, 0])
- if score > highscore:
- highscore_file = open("highscore.txt", "wb")
- pickle.dump(highscore, highscore_file)
- def pause():
- """Function that pauses the game"""
- paused = True
- message("Game is paused", black, y_displace=-20, size="large")
- message("Press P to resume", grey, y_displace=50, size="medium")
- pygame.display.update()
- while paused:
- for event in pygame.event.get():
- if event.type == pygame.KEYDOWN:
- if event.key == pygame.K_p:
- paused = False
- def game_loop():
- global direction
- highscore_file = open("highscore.txt", "rb")
- highscore = pickle.load(highscore_file)
- highscore_file.close()
- direction = "right" # The initial direction is right
- game_exit = False # We set game_exit to be false
- game_over = False # We set game_over to be false
- head_x = screen_width / 2 # The initial X position of the snake's head, at the middle of the X axis
- head_y = screen_height / 2 # The initial Y position of the snake's head, at the middle of the Y axis
- head_x_change = 20 # Variable used to move the snake's head on the X axis
- head_y_change = 0 # Variable used to move the snake's head on the Y axis
- snakelist = [] # List containing all the coordinates of the blocks composing the snake
- snakelength = 1 # At the beginning, our snake length is 1
- apple_randX, apple_randY = apple() # X and Y position of the apple
- while not game_exit: # Our game loop
- while game_over is True: # Game Over screen
- screen.fill(lightblue)
- message("Game Over !", red, y_displace=-70, size="large")
- message("Your score : " + str(score_value), black, y_displace=20, size="small")
- message("Highscore :" + str(highscore), black, y_displace=50, size="small")
- message("R to Retry, Q to Quit", black, 100)
- pygame.display.update()
- for event in pygame.event.get():
- if event.type == pygame.QUIT: # If the user want's to exit the game (by clicking on the red cross or Alt + F4)
- game_exit = True
- game_over = False
- if event.type == pygame.KEYDOWN:
- if event.key == pygame.K_a: # If the key pressed is Q (A on an AZERTY keyboard)
- game_exit = True
- game_over = False
- if event.key == pygame.K_r: # If the key pressed is R
- game_loop() # Start over the game
- for event in pygame.event.get(): # Our event handler
- if event.type == pygame.QUIT: # If the user wants to quit (e.g. by clicking on the red cross)
- game_exit = True # We set game_exit to True in order to exit the game loop
- if event.type == pygame.KEYDOWN: # When the user presses a key
- if event.key == pygame.K_LEFT: # If the key is the left arrow
- if direction == "right":
- continue
- direction = "left"
- head_x_change = -20
- head_y_change = 0
- elif event.key == pygame.K_RIGHT: # If the key is the right arrow
- if direction == "left":
- continue
- direction = "right"
- head_x_change = 20
- head_y_change = 0
- elif event.key == pygame.K_UP: # If the key is the up arrow
- if direction == "down":
- continue
- direction = "up"
- head_y_change = -20
- head_x_change = 0
- elif event.key == pygame.K_DOWN: # If the key is the down arrow
- if direction == "up":
- continue
- direction = "down"
- head_y_change = 20
- head_x_change = 0
- elif event.key == pygame.K_p: # If the key is p
- pause() # We pause the game
- head_x += head_x_change # We move the head
- head_y += head_y_change
- 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
- game_over = True # We exit the game loop
- screen.fill(lightblue) # Set background color to a light blue
- # pygame.draw.rect(screen, red, [apple_randX, apple_randY, block_size, block_size])
- screen.blit(sprite_apple, (apple_randX, apple_randY))
- snakehead = [] # List containing the X and the Y coordinates of the snake's head
- snakehead.append(head_x) # We add the head_x variable to the snakehead list
- snakehead.append(head_y) # We add the head_y variable to the snakehead list
- snakelist.append(snakehead) # We then add the snakehead coordinates to our snakelist
- if len(snakelist) > snakelength: # When the snake advances, it gets bigger on the front, so we need to delete the end
- del snakelist[0] # We delete the first block
- for segment in snakelist[:-1]: # We go through each segment in the snake's body except the last element, which is the head
- if segment == snakehead: # If the snake's head touches its body
- game_over = True
- score_value = snakelength - 1
- snake(snakelist, block_size) # We create our snake
- score(score_value, highscore) # We update the score
- pygame.display.update() # We update the screen
- if head_x == apple_randX and head_y == apple_randY: # If the snake reaches the apple
- apple_randX, apple_randY = apple() # We create a new apple
- snakelength += 1 # The snake becomes longer
- clock.tick(17) # 17 FPS
- pygame.quit()
- quit()
- start_menu()
- game_loop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement