Turtle graphics snake game

3 min read 07-10-2024
Turtle graphics snake game


Slithering into Python: Building a Snake Game with Turtle Graphics

The classic Snake game is a simple yet addictive game where you control a snake that grows longer by eating food. It's a perfect project for beginners learning Python, and the intuitive Turtle graphics library makes it visually engaging. In this article, we'll explore how to create your own Snake game using Python's Turtle module.

Setting the Stage

The game's core mechanics involve moving a snake around a screen, picking up food to grow, and avoiding collisions with itself or the screen boundaries. To achieve this, we'll utilize Turtle's functionality for drawing shapes, controlling movement, and detecting collisions.

Let's start with the basic code structure:

import turtle
import time
import random

# Screen setup
screen = turtle.Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("Snake Game")

# Snake setup
snake = []
starting_positions = [(0, 0), (-20, 0), (-40, 0)]
for position in starting_positions:
    new_segment = turtle.Turtle("square")
    new_segment.color("green")
    new_segment.penup()
    new_segment.goto(position)
    snake.append(new_segment)

# Food setup
food = turtle.Turtle("circle")
food.penup()
food.color("red")
food.speed("fastest")
food.goto(random.randint(-280, 280), random.randint(-280, 280))

# Game variables
game_is_on = True
speed = 0.1

# Functions
def move():
    for seg_num in range(len(snake) - 1, 0, -1):
        new_x = snake[seg_num - 1].xcor()
        new_y = snake[seg_num - 1].ycor()
        snake[seg_num].goto(new_x, new_y)
    snake[0].forward(20)

def up():
    snake[0].setheading(90)

def down():
    snake[0].setheading(270)

def left():
    snake[0].setheading(180)

def right():
    snake[0].setheading(0)

# Event listeners
screen.listen()
screen.onkey(up, "Up")
screen.onkey(down, "Down")
screen.onkey(left, "Left")
screen.onkey(right, "Right")

while game_is_on:
    screen.update()
    time.sleep(speed)

    move()

# Game over
turtle.done() 

This code sets up the basic environment:

  • Screen setup: Creates a 600x600 black screen with the title "Snake Game".
  • Snake setup: Initializes the snake as a list of three green squares.
  • Food setup: Places a red circular food item at a random location.
  • Game variables: Defines game_is_on for controlling the game loop, and speed for adjusting the snake's movement rate.
  • Functions:
    • move(): Moves the snake by shifting each segment to the position of the one before it.
    • up(), down(), left(), right(): Change the snake's direction based on arrow key presses.
  • Event listeners: Bind arrow key presses to the respective direction functions.
  • Game loop: Continuously updates the screen, moves the snake, and checks for game over conditions.

Expanding on the Basics

The basic code allows the snake to move, but it doesn't yet handle interactions like eating food or collisions. Let's add those features:

  1. Food Detection:

    if snake[0].distance(food) < 15:
        food.goto(random.randint(-280, 280), random.randint(-280, 280))
        new_segment = turtle.Turtle("square")
        new_segment.color("green")
        new_segment.penup()
        new_segment.goto(snake[-1].xcor(), snake[-1].ycor())
        snake.append(new_segment)
        speed *= 0.9 # Increase speed slightly
    

    This code checks if the snake's head collides with the food. If so, it relocates the food, adds a new segment to the snake's tail, and increases the game speed.

  2. Collision Detection:

    for seg_num in range(1, len(snake)):
        if snake[0].distance(snake[seg_num]) < 10:
            game_is_on = False
    

    This loop checks if the snake's head collides with any of its own segments. If so, game_is_on is set to False, ending the game.

Finishing Touches

To make the game more visually appealing and engaging, consider adding:

  • Scorekeeping: Use a Turtle object to display the player's score on the screen.
  • Game Over Screen: When the game ends, display a message on the screen and allow the player to restart.
  • Sound Effects: Add sound effects for eating food, hitting the walls, and game over.

Building Your Own Snake Game

This article has provided a solid foundation for creating your own Snake game using Turtle graphics. By implementing the code and expanding upon it, you can customize the game with various features and design elements.

Remember, the key to programming is experimentation and learning from mistakes. Don't be afraid to modify the code, try out different ideas, and have fun!

References and Resources

With the right tools and a little creativity, you can build a thrilling Snake game that will keep you entertained for hours. So grab your Python skills and dive into the world of Turtle graphics!