STAY INFORMED
following content serves as a personal note and may lack complete accuracy or certainty.

Minimal-Mistakes instruction
Useful vscode Shortcut Keys
Unix Commands
npm Commands
Vim Commands
Git Note
Useful Figma Shortcut Keys

2 minute read

my github repo

Programming languages used

  • python

Introduction

The Snake Game is a classic and simple video game that has been popular since the early days of computer gaming. The game concept is straightforward: control a snake on a grid or game board, and the snake grows longer as it consumes food. This project is quite helpful for your portfolio.

prerequisites

pip3 install pygame
import pygame
import sys
import copy
import random
import time

more info pygame

code

initialize

This code is basic set up for the game.

pygame.init()

width = 500
height = 500
scale = 10
score = 0

food_x = 10
food_y = 10

display = pygame.display.set_mode((width, height))
pygame.display.set_caption("Snake Game")
clock = pygame.time.Clock() # similar to delta time

def gameLoop():
    running = True

    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False


        # update screen
        pygame.display.flip()

        # 60frames per a second
        clock.tick(60)

gameLoop()

And I need 2 classes

  • Snake
  • Food

snake class

I need initial structure for snake, and I game is over, need to be reset. Reset function is almost same as initial structure.

class Snake:
    def __init__(self, x_start, y_start):
        self.x = x_start
        self.y = y_start
        self.w = 10
        self.h = 10
        self.x_dir = 1
        self.y_dir = 0
        self.body = [[self.x, self.y]]
        self.length = 1

    def reset(self):
        self.x = width / 2 - scale
        self.y = height / 2 - scale
        self.w = 10
        self.h = 10
        self.x_dir = 1
        self.y_dir = 0
        self.body = [[self.x, self.y]]
        self.length = 1

Once game starts, snake should be shown so I will create show function.

snake_color = (236, 240, 241)
snake_head = (247, 220, 111)
def show(self):
    for i in range(self.length):
        if i !== 0:
            # Surface, color, rect, width, height
            pygame.draw.rect(display, snake_color, (self.body[i][0], self.body[i][1], self.w, self.h))
        else:
            # snake head
            pygame.draw.rect(display, snake_color, (self.body[i][0], self.body[i][1],
                                                    self.w, self.h))

If snake eats food, the body is extended so I need to create the collision detection and grow function.

# check collision with food, should be collided to head
def check_eaten(self):
    if abs(self.body[0][0] - food_x) < scale and abs(self.body[0][1] - food_y) < scale:
        return True

def grow(self):
    self.length += 1
    self.body.append(self.body[self.length - 2])

The reason why append body.lenth - 2 is i dont know…

And update function. body is copied depends on the length, and follows the head.

def update(self):
    i = self.length - 1
    while i > 0:
        # copy the body object located self.body[i - 1]
        self.body[i] = copy.deepcopy(self.body[i - 1])
        i -= 1

    # move the head according to its current direction and scale.
    self.body[0][0] += self.x_dir * scale
    self.body[0][1] += self.y_dir * scale

If there is no game over function, it will be boring. I will create death function

    def death(self):
        i = self.length - 1
        while i > 0:
            # if head collided with body, dead.
            if abs(self.body[0][0] - self.body[i][0]) < self.w and abs(self.body[0][1] - self.body[i][1] < self.h) and self.length > 2:
                return True
            i -= 1

Now I am done with snake class. you can test with this code.

def gameLoop():
    running = True

    # create snake object
    snake = Snake(width / 2, height / 2)

    while running:
        # keydown event
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    snake.x_dir = 0
                    snake.y_dir = -1
                if event.key == pygame.K_DOWN:
                    snake.x_dir = 0
                    snake.y_dir = 1
                if event.key == pygame.K_LEFT:
                    snake.x_dir = -1
                    snake.y_dir = 0
                if event.key == pygame.K_RIGHT:
                    snake.x_dir = 1
                    snake.y_dir = 0

        # clear the surface
        display.fill(background)

        # call snake functions
        snake.show()
        snake.update()


        # update screen
        pygame.display.update()

        # 10frames per a second
        clock.tick(10)