leafleafleafDocy banner shape 01Docy banner shape 02Man illustrationFlower illustration

Python Pygame Snake Game Implementation Complete Code

Estimated reading: 5 minutes 64 views

In the previous section, our Snake game has been completed. If there is a problem with your program, please modify it in time with the complete code below; if there is no problem, go back and look at the program code of the game, This will make it easier to understand the code.

Python Snake Game Complete Code:

# import module
import pygame
import random
import sys
#define color
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
DARKGREEN = (0, 185, 0)
YELLOW=(255,255,0)
#define the direction
UP = 1
DOWN = 2
LEFT = 3
RIGHT = 4
#define the size of the window
windowsWidth = 800
windowsHeight = 600
#define map size
cellSize = 20 #Define the base unit size
mapWidth = int(windowsWidth / cellSize)
mapHeight = int(windowsHeight / cellSize)
HEAD = 0 # Snake head subscript
snakeSpeed ​​= 7 #The speed of the snake
#main function
def main():
    pygame.init() # module initialization       
    screen = pygame.display.set_mode((windowsWidth, windowsHeight))
    pygame.display.set_caption("Snake") #Set the window title
    screen.fill(WHITE)   
    snakeSpeedClock = pygame.time.Clock() # Create a Pygame clock object
    startGame(screen) #Game start
   
    while True:
        music=pygame.mixer.Sound("snake.wav")
        music.play(-1)
        runGame(screen, snakeSpeedClock)
        music.stop()
        gameOver(screen)
#Games start
def startGame(screen):
    gameStart = pygame.image.load("gameStart.png")
    screen.blit(gameStart, (70, 30))
    font = pygame.font.SysFont("SimHei", 40)
    tip = font.render("Press any key to start the game", True, (65, 105, 225))
    screen.blit(tip, (240, 550))
   
    pygame.display.update()
    while True: #Keyboard monitor events
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                terminate() # Terminate the program
            elif event.type == pygame.KEYDOWN:
                if (event.key == pygame.K_ESCAPE):
                    terminate() # Terminate the program
                else:
                    return #End this function, start the game
#Game running main body
def runGame(screen, snakeSpeedClock):    
    startX = random.randint(3, mapWidth - 8) #Start position
    startY = random.randint(3, mapHeight - 8)
    snakeCoords = [{"x": startX, "y": startY}, #Initial Snake
                   {"x": startX - 1, "y": startY},
                   {"x": startX - 2, "y": startY}]
    direction = RIGHT # start moving right
    food = {"x": random.randint(0, mapWidth - 1), "y": random.randint(0, mapHeight - 1)} #Random location of food
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                terminate()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT and direction != RIGHT:
                    direction = LEFT                   
                elif event.key == pygame.K_RIGHT and direction != LEFT:
                    direction = RIGHT                   
                elif event.key == pygame.K_UP and direction != DOWN:
                    direction = UP                   
                elif event.key == pygame.K_DOWN and direction != UP:
                    direction = DOWN               
                elif event.key == pygame.K_ESCAPE:                      
                    terminate()
        moveSnake(direction, snakeCoords) #Move Snake
        isEattingFood(snakeCoords, food) #Determine whether the greedy snake has eaten food
        ret = isAlive(snakeCoords) #Determine whether the snake is alive
        if not ret:
            break #greedy snake is dead. Game over   
      
        gameRun = pygame.image.load("background.png")
        screen.blit(gameRun, (0, 0))
        drawFood(screen, food)
        drawSnake(screen, snakeCoords)
        drawScore(screen, len(snakeCoords) - 3)        
       
        pygame.display.update()
        snakeSpeedClock.tick(snakeSpeed) #Control the frame rate
#draw food
def drawFood(screen, food):
    x = food["x"] * cellSize
    y = food["y"] * cellSize
    pygame.draw.rect(screen, YELLOW, (x, y, cellSize, cellSize))
#draw the greedy snake
def drawSnake(screen, snakeCoords):
    for coord in snakeCoords:
        x = coord["x"] * cellSize
        y = coord["y"] * cellSize
        pygame.draw.rect(screen, DARKGREEN, (x, y, cellSize, cellSize)) #The green of the outer layer of the snake
        pygame.draw.rect(screen, GREEN,(x + 4, y + 4, cellSize - 8, cellSize - 8)) #The bright green in the snake
#paint score
def drawScore(screen,score):
    font = pygame.font.SysFont("SimHei", 30)   
    scoreSurf = font.render("Score: " + str(score), True, WHITE)
    scoreRect = scoreSurf.get_rect()
    scoreRect.topleft = (windowsWidth - 200, 50)
    screen.blit(scoreSurf, scoreRect)
#mobile snake
def moveSnake(direction, snakeCoords):
    if direction == UP:
        newHead = {"x": snakeCoords[HEAD]["x"], "y": snakeCoords[HEAD]["y"] - 1}
    elif direction == DOWN:
        newHead = {"x": snakeCoords[HEAD]["x"], "y": snakeCoords[HEAD]["y"] + 1}
    elif direction == LEFT:
        newHead = {"x": snakeCoords[HEAD]["x"] - 1, "y": snakeCoords[HEAD]["y"]}
    elif direction == RIGHT:
        newHead = {"x": snakeCoords[HEAD]["x"] + 1, "y": snakeCoords[HEAD]["y"]}
    snakeCoords.insert(0, newHead)
#Determine whether the greedy snake has eaten food
def isEattingFood(snakeCoords, food):
    if snakeCoords[HEAD]["x"] == food["x"] and snakeCoords[HEAD]["y"] == food["y"]:
        food["x"] = random.randint(0, mapWidth - 1)
        food["y"] = random.randint(0, mapHeight - 1) # physical position reset
    else:
        del snakeCoords[-1] # If you don't eat the real thing, move forward, then delete one space at the end
# Determine if the snake is dead
def isAlive(snakeCoords):
    tag = True
    if snakeCoords[HEAD]["x"] == -1 or snakeCoords[HEAD]["x"] == mapWidth or snakeCoords[HEAD]["y"] == -1 or \
            snakeCoords[HEAD]["y"] == mapHeight:
        tag = False # Snake hits a wall
    for snake_body in snakeCoords[1:]:
        if snake_body["x"] == snakeCoords[HEAD]["x"] and snake_body["y"] == snakeCoords[HEAD]["y"]:
            tag = False # The greedy snake touches its own body
    return tag
#Game over message display
def gameOver(screen):
    #Load game over image
    screen.fill(WHITE)
    gameOve = pygame.image.load("gameover.png")
    screen.blit(gameOve, (0, 0))
    #Load game over message
    font = pygame.font.SysFont("SimHei", 36)
    tip = font.render("Press Q or ESC to exit the game, press other keys to restart the game", True, (65, 105, 225))  
    screen.blit(tip, (30, 500))
    #Display the content on the Surface object
    pygame.display.update()
    while True: #Keyboard monitor events
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                terminate() # Terminate the program
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE or event.key == pygame.K_q:
                    terminate()
                else:
                    return #End this function, restart the game   
# program termination
def terminate():   
    pygame.quit()
    sys.exit()
main()

Leave a Comment

CONTENTS