snake game python turtle code

"Master Python Turtle: Create Your Own Snake Game"

By William Martinez
AD

Creating the Classic Snake Game using Python and Turtle

In the realm of programming, there are few games as iconic and universally recognized as the Snake Game. This simple yet engaging game has been a staple in the industry since its inception on Nokia phones in the late 90s. Today, we're going to recreate this classic using Python and the built-in turtle module. Let's dive into the code and understand how it works.

Setting Up the Screen and the Snake

First, we import the turtle module and set up the screen for our game. We'll use a 600x600 pixel canvas with a black background.

import turtle
import time
import random

win = turtle.Screen()
win.title("Snake Game")
win.bgcolor("black")
win.setup(width=600, height=600)
win.tracer(0)

Next, we create the snake using three turtles - one for the head and two for the body. We'll use green for the snake and yellow for the food.

AD
Code for snake game in python
Code for snake game in python
Simple Python code for snake game with images
Simple Python code for snake game with images
Creating a Snake Game in Python.
Creating a Snake Game in Python.

Defining the Snake's Movement

The snake moves in a specific direction at a time. We'll use the arrow keys to change its direction. Here's how we define the snake's movement:

direction = "Stop"

def move():
    if direction == "up":
        y = snake_head.ycor()
        snake_head.sety(y + 20)
    elif direction == "down":
        y = snake_head.ycor()
        snake_head.sety(y - 20)
    elif direction == "left":
        x = snake_head.xcor()
        snake_head.setx(x - 20)
    elif direction == "right":
        x = snake_head.xcor()
        snake_head.setx(x + 20)

Changing the Snake's Direction

We'll use the onkey() function to bind the arrow keys to the change_direction() function. This function will update the direction variable based on the key pressed.

Develop Snake Game in Python
Develop Snake Game in Python
a computer screen with some type of programming program in the dark, it looks like they are
a computer screen with some type of programming program in the dark, it looks like they are
Strengthening game with snake
Strengthening game with snake

Creating the Food

The food is a simple yellow square that appears at a random location on the screen. We'll use the on_turtle_click() function to generate a new food when the snake eats the current one.

Checking for Collisions

We need to check for two types of collisions - the snake hitting the border and the snake hitting itself. If either of these happens, the game is over.

AD

Implementing the Game Loop

The game loop is the heart of the game. It moves the snake, checks for collisions, and updates the screen. Here's how we implement it:

LeenaBOT - Snake game coding in Python
LeenaBOT - Snake game coding in Python
Game Building With Python’s Turtle Module
Game Building With Python’s Turtle Module
What Are The Methods In Python Turtle Module
What Are The Methods In Python Turtle Module
Snake Game JavaScript Code
Snake Game JavaScript Code
Try this code🤩
Try this code🤩
TURTLE DESIGN using Python
TURTLE DESIGN using Python
while True:
    win.update()

    # Check for border collision
    if snake_head.xcor() > 290 or snake_head.xcor() < -290 or snake_head.ycor() > 290 or snake_head.ycor() < -290:
        time.sleep(1)
        snake_head.goto(0, 0)
        snake_head.direction = "Stop"
        for segment in segments:
            segment.goto(1000, 1000)
        segments.clear()
        direction = "Stop"

    # Check for self-collision
    for segment in segments:
        if segment.distance(snake_head) < 20:
            time.sleep(1)
            snake_head.goto(0, 0)
            snake_head.direction = "Stop"
            for segment in segments:
                segment.goto(1000, 1000)
            segments.clear()
            direction = "Stop"

    # Move the snake
    move()

    # Check for food collision
    if snake_head.distance(food) < 20:
        x = random.randint(-290, 290)
        y = random.randint(-290, 290)
        food.goto(x, y)

        # Add a segment to the snake
        new_segment = turtle.Turtle()
        new_segment.speed(0)
        new_segment.shape("square")
        new_segment.color("grey")
        new_segment.penup()
        segments.append(new_segment)

    # Move the end segments first in reverse order
    for index in range(len(segments) - 1, 0, -1):
        x = segments[index - 1].xcor()
        y = segments[index - 1].ycor()
        segments[index].goto(x, y)

    # Move segment 0 to head's position
    if len(segments) > 0:
        x = snake_head.xcor()
        y = snake_head.ycor()
        segments[0].goto(x, y)

    # Update the screen
    time.sleep(delay)

That's it! You've just created the classic Snake Game using Python and the turtle module. This game is a great starting point for learning about loops, conditionals, and functions in Python. It's also a fun project to show off to friends and family.

Happy coding!

AD
-
-
Anyone for a game of 'Code Golf'? - FORE!
Anyone for a game of 'Code Golf'? - FORE!
Tic Tac Toe in Python With Source Code
Tic Tac Toe in Python With Source Code
How to Make a Fully Automated Robotic Snakes and Ladders Game in Python
How to Make a Fully Automated Robotic Snakes and Ladders Game in Python
snake game
snake game
Puzzle Game In Python With Source Code
Puzzle Game In Python With Source Code
Glow Particle Animation (Turtle) Python Turtle, Coding Lessons, Coding Tutorials, Learn Web Development, Learn Computer Coding, Programming Code, Computer Coding, Python Programming, Programming Languages
Glow Particle Animation (Turtle) Python Turtle, Coding Lessons, Coding Tutorials, Learn Web Development, Learn Computer Coding, Programming Code, Computer Coding, Python Programming, Programming Languages
an interactive game for kids to play
an interactive game for kids to play
a computer screen with an image of a starburst
a computer screen with an image of a starburst
Pixel Art - Snake
Pixel Art - Snake
Python Adventure Game Source Code
Python Adventure Game Source Code
Python Turtle Drawing Trinket with details on Python!
Python Turtle Drawing Trinket with details on Python!
How To Code Snake 🐍
How To Code Snake 🐍
Python Project Ideas | Turtle Racer in Python | Python programming | Python for beginners
Python Project Ideas | Turtle Racer in Python | Python programming | Python for beginners
AD