Python: Sample Snake

Return to Python resources

import pygame, sys, random
from pygame.locals import *

pygame.init()
fps = pygame.time.Clock()

# Create window
window = pygame.display.set_mode((500,500))
pygame.display.set_caption("Snake")

# Create colours
colorRed = pygame.Color(255,0,0)
colorGreen = pygame.Color(0,255,0)
colorBlue = pygame.Color(0,0,255)
colorYellow = pygame.Color(255,255,0)
colorSnakeTail = pygame.Color(196,196,0)
colorBlack = pygame.Color(0,0,0)
colorWhite = pygame.Color(255,255,255)

gameRunning = True
snakeXY = [(10,10)]
snakeTail = []
fruitXY = (5,5)
fullWindow = (0,0,500,500)
currentX = 10
currentY = 10
dirX = 0
dirY = 0

while gameRunning:
    # Events
    for event in pygame.event.get():
        if event.type == QUIT:
            gameRunning = False
        elif event.type == KEYDOWN:
            if event.key == K_LEFT:
                dirX = -1
                dirY = 0
            elif event.key == K_RIGHT:
                dirX = +1
                dirY = 0
            elif event.key == K_UP:
                dirX = 0
                dirY = -1
            elif event.key == K_DOWN:
                dirX = 0
                dirY = +1

    # Calculations                
    currentX += dirX
    currentY += dirY
    snakeXY.insert(0,(currentX, currentY))
    nothing = snakeXY.pop()
    fruit = (fruitXY[0]*20, fruitXY[1]*20, 20, 20)

    # Check for fruit collision
    fruitCollide = False
    for snakePiece in snakeXY:
        snakeRect = Rect(snakePiece[0] * 20, snakePiece[1] * 20, 20, 20)
        pygame.draw.rect(window, colorYellow, snakeRect)
        # Detect collision with fruit
        if (snakeRect.colliderect(fruit)):
            fruitCollide = True
    if fruitCollide:
        snakeXY.append((currentX, currentY))
        # Reposition the fruit
        fruitXY = (random.randint(1, 25), random.randint(1, 25))

    # Draw graphics
    pygame.draw.rect(window, colorBlack, fullWindow)
    pygame.draw.rect(window, colorRed, fruit)
    pygame.display.update()
    fps.tick(10)

pygame.quit()
print("Good bye!")