Tutorial #1

Subscribe to Tech With Tim!

In this tutorial series we will be working to create the famous snake game in python with the module pygame. If you are more interested in a general pygame tutorial series click here

Starter Code

To make our lives a bit easier I've set up the main structure for our game already. We are going to be using two main classes (snake and cube).

#Snake Tutorial Python

import math
import random
import pygame
import tkinter as tk
from tkinter import messagebox

class cube(object):
    rows = 20
    w = 500
    def __init__(self,start,dirnx=1,dirny=0,color=(255,0,0)):
    def move(self, dirnx, dirny):
    def draw(self, surface, eyes=False):

class snake(object):
    def __init__(self, color, pos):

    def move(self):

    def reset(self, pos):

    def addCube(self):

    def draw(self, surface):

def drawGrid(w, rows, surface):

def redrawWindow(surface):

def randomSnack(rows, item):

def message_box(subject, content):

def main():


Creating our Game Loop

In all games we have a loop called a "main loop" or "game loop". This loop will continuously run until the game is exited. It is mainly responsible for checking for events and calling functions and methods based on those events.

We are going to be coding our game loop inside the main() function. We will declare some variables at the top of the function then move into our while loop which will represent our game loop.

def main(): 
    global width, rows, s
    width = 500  # Width of our screen
    height = 500  # Height of our screen
    rows = 20  # Amount of rows

    win = pygame.display.set_mode((width, height))  # Creates our screen object

    s = snake((255,0,0), (10,10))  # Creates a snake object which we will code later
    clock = pygame.time.Clock() # creating a clock object

    flag = True
    while flag:
        pygame.time.delay(50)  # This will delay the game so it doesn't run too quickly
        clock.tick(10)  # Will ensure our game runs at 10 FPS
        redrawWindow(win)  # This will refresh our screen  

Updating the Screen

It is usually good practice to do all of our drawing of objects from within one function or method. We will be using the redrawWindow function to update the display. We call this function once a frame from our game loop.

We will be adding more to this function later. However, for now we will simply draw the grid lines.

def redrawWindow(surface):
    surface.fill((0,0,0))  # Fills the screen with black
    drawGrid(surface)  # Will draw our grid lines
    pygame.display.update()  # Updates the screen

Drawing the Grid

We are now going to work on drawing the lines to represent the 20x20 grid. We will do this in the drawGrid function.

def drawGrid(w, rows, surface):
    sizeBtwn = w // rows  # Gives us the distance between the lines

    x = 0  # Keeps track of the current x
    y = 0  # Keeps track of the current y
    for l in range(rows):  # We will draw one vertical and one horizontal line each loop
        x = x + sizeBtwn
        y = y + sizeBtwn

        pygame.draw.line(surface, (255,255,255), (x,0),(x,w))
        pygame.draw.line(surface, (255,255,255), (0,y),(w,y))

Now when we run the program we can see the grid lines being drawn.pygame snake tutorial

Starting the Snake Class

Our snake object is going to contain a list of cubes which will represent the snake body. We are going to store these cubes in a list called body which will be a class variable. We will also have a class variable called turns.

To start our Snake class we will code the __init__() method and add the class variables.

class snake(object):
    body = []
    turns = {}
    def __init__(self, color, pos):
        self.color = color
        self.head = cube(pos)  # The head will be the front of the snake
        self.body.append(self.head)  # We will add head (which is a cube object)
        # to our body list

        # These will represent the direction our snake is moving
        self.dirnx = 0 
        self.dirny = 1