Python

Snake Game in Python using Turtle Module: Step-by-Step Guide

Introduction

Python is a versatile programming language that can be used to create a wide range of applications, including games. In this step-by-step guide, we will learn how to create a classic Snake game using the Turtle module in Python.

Setting up the Environment

Before we start coding, we need to make sure that we have the necessary tools installed. First, we need to have Python installed on our system. You can download the latest version of Python from the official website and follow the installation instructions.

Once Python is installed, we need to install the Turtle module. Turtle is a built-in module in Python that provides a simple way to create graphics and animations. To install Turtle, open your command prompt or terminal and run the following command:

pip install PythonTurtle

Creating the Game Window

Now that we have our environment set up, let’s start coding our Snake game. The first step is to create the game window. We will use the Turtle module to create a window with a specified width and height. Here’s the code:

«`python
import turtle

# Create the game window
window = turtle.Screen()
window.title(«Snake Game»)
window.bgcolor(«black»)
window.setup(width=600, height=600)
window.tracer(0)
«`

In the code above, we import the turtle module and create a new screen object called «window». We set the title of the window to «Snake Game» and the background color to black. We also set the width and height of the window to 600 pixels and turn off the animation using the tracer(0) method.

Creating the Snake

Now that we have our game window, let’s create the snake. In the Snake game, the snake is represented by a series of square segments. We will use the Turtle module to create these segments and position them on the screen. Here’s the code:

«`python
# Create the snake
snake = turtle.Turtle()
snake.speed(0)
snake.shape(«square»)
snake.color(«white»)
snake.penup()
snake.goto(0, 0)
snake.direction = «stop»
«`

In the code above, we create a new turtle object called «snake». We set the speed of the snake to 0, which means it will move instantly. We set the shape of the snake to «square» and the color to white. We also lift the pen up using the penup() method, so the snake doesn’t leave a trail when it moves. Finally, we position the snake at the center of the screen using the goto(0, 0) method and set its initial direction to «stop».

Moving the Snake

Now that we have our snake, let’s make it move. In the Snake game, the snake can move in four directions: up, down, left, and right. We will use the keyboard arrow keys to control the direction of the snake. Here’s the code:

Recomendado:  How to Draw the Mandelbrot Set in Python - Step-by-Step Guide

«`python
# Move the snake
def move():
if snake.direction == «up»:
y = snake.ycor()
snake.sety(y + 20)

if snake.direction == «down»:
y = snake.ycor()
snake.sety(y – 20)

if snake.direction == «left»:
x = snake.xcor()
snake.setx(x – 20)

if snake.direction == «right»:
x = snake.xcor()
snake.setx(x + 20)
«`

In the code above, we define a function called «move» that moves the snake based on its current direction. If the direction is «up», we increase the y-coordinate of the snake by 20 pixels. If the direction is «down», we decrease the y-coordinate by 20 pixels. If the direction is «left», we decrease the x-coordinate by 20 pixels. If the direction is «right», we increase the x-coordinate by 20 pixels.

To make the snake move continuously, we need to call the move function in a loop. We can use the main loop of the Turtle module to achieve this. Here’s the code:

«`python
# Main game loop
while True:
window.update()
move()
«`

In the code above, we call the update() method of the window object to update the screen. We then call the move() function to move the snake. Since we want the game to continue running indefinitely, we use a while loop with the condition set to True.

Handling Keyboard Input

Now that we have our snake moving, let’s handle the keyboard input to control its direction. We will use the Turtle module’s built-in event handling functions to achieve this. Here’s the code:

«`python
# Change the snake’s direction
def go_up():
if snake.direction != «down»:
snake.direction = «up»

def go_down():
if snake.direction != «up»:
snake.direction = «down»

def go_left():
if snake.direction != «right»:
snake.direction = «left»

def go_right():
if snake.direction != «left»:
snake.direction = «right»

# Keyboard bindings
window.listen()
window.onkeypress(go_up, «Up»)
window.onkeypress(go_down, «Down»)
window.onkeypress(go_left, «Left»)
window.onkeypress(go_right, «Right»)
«`

In the code above, we define four functions: go_up, go_down, go_left, and go_right. Each function changes the direction of the snake based on the current direction and the key pressed. For example, if the snake is currently moving up and the user presses the down arrow key, the direction will change to «down».

We then use the listen() method of the window object to listen for keyboard events. We use the onkeypress() method to bind each function to a specific key. For example, when the user presses the up arrow key, the go_up() function will be called.

Creating the Food

Now that we have our snake moving and responding to keyboard input, let’s create the food for the snake to eat. In the Snake game, the food is represented by a small square that appears randomly on the screen. Here’s the code:

Recomendado:  Python Graphviz: DOT Language - Todo sobre el lenguaje DOT en Python

«`python
import random

# Create the food
food = turtle.Turtle()
food.speed(0)
food.shape(«square»)
food.color(«red»)
food.penup()
food.goto(0, 100)

# Move the food
def move_food():
x = random.randint(-280, 280)
y = random.randint(-280, 280)
food.goto(x, y)
«`

In the code above, we import the random module to generate random coordinates for the food. We create a new turtle object called «food» and set its properties similar to the snake. We also position the food at a random location using the goto() method.

To make the food move to a new location every time the snake eats it, we define a function called «move_food». This function generates random x and y coordinates within the screen boundaries and moves the food to that location using the goto() method.

Checking for Collisions

Now that we have our snake and food, let’s check for collisions between them. In the Snake game, if the snake collides with the food, it should grow longer and the score should increase. Here’s the code:

«`python
# Check for collisions
def check_collision():
if snake.distance(food) < 20: move_food() # Code to increase the score and grow the snake ```

In the code above, we define a function called «check_collision» that checks if the distance between the snake and the food is less than 20 pixels. If the condition is true, it means the snake has collided with the food. We then call the move_food() function to move the food to a new location.

At this point, we need to write the code to increase the score and grow the snake when it eats the food. We will keep track of the score using a variable and increase it by 10 every time the snake eats the food. We will also add a new segment to the snake’s body. Here’s the code:

«`python
# Increase the score and grow the snake
score = 0
segments = []

def increase_score():
global score
score += 10

def grow_snake():
new_segment = turtle.Turtle()
new_segment.speed(0)
new_segment.shape(«square»)
new_segment.color(«white»)
new_segment.penup()
segments.append(new_segment)

# Inside the check_collision() function
increase_score()
grow_snake()
«`

In the code above, we define a variable called «score» to keep track of the score and initialize it to 0. We also create an empty list called «segments» to store the segments of the snake’s body.

We define a function called «increase_score» that increases the score by 10 every time it is called. We use the global keyword to access the global variable «score» inside the function.

We define a function called «grow_snake» that creates a new turtle object for the new segment, sets its properties similar to the snake, and adds it to the «segments» list.

Inside the check_collision() function, we call the increase_score() function to increase the score and the grow_snake() function to add a new segment to the snake’s body.

Recomendado:  Python Statistics Module: Funciones y métodos en estadísticas

Updating the Score

Now that we have our score increasing when the snake eats the food, let’s update the score on the screen. We will use the Turtle module to create a new turtle object for the score and position it on the screen. Here’s the code:

«`python
# Create the score
score_pen = turtle.Turtle()
score_pen.speed(0)
score_pen.color(«white»)
score_pen.penup()
score_pen.hideturtle()
score_pen.goto(0, 260)
score_pen.write(«Score: 0″, align=»center», font=(«Courier», 24, «normal»))

# Update the score
def update_score():
score_pen.clear()
score_pen.write(«Score: {}».format(score), align=»center», font=(«Courier», 24, «normal»))

# Inside the increase_score() function
update_score()
«`

In the code above, we create a new turtle object called «score_pen» and set its properties similar to the snake. We position the score at the top of the screen using the goto() method and write the initial score using the write() method.

We define a function called «update_score» that clears the previous score using the clear() method and writes the updated score using the write() method. We use the format() method to insert the value of the score variable into the string.

Inside the increase_score() function, we call the update_score() function to update the score on the screen.

Game Over

Finally, let’s add the game over functionality to our Snake game. In the Snake game, the game is over when the snake collides with the boundaries of the screen or with its own body. Here’s the code:

«`python
# Game over
def game_over():
snake.goto(0, 0)
snake.direction = «stop»
for segment in segments:
segment.goto(1000, 1000)
segments.clear()
score = 0
update_score()

# Inside the move() function
if snake.xcor() > 290 or snake.xcor() < -290 or snake.ycor() > 290 or snake.ycor() < -290: game_over()for segment in segments: if segment.distance(snake) < 20: game_over() ```

In the code above, we define a function called «game_over» that resets the snake’s position to the center of the screen, sets its direction to «stop», hides all the segments of the snake’s body, clears the «segments» list, resets the score to 0, and updates the score on the screen.

Inside the move() function, we check if the snake has collided with the boundaries of the screen using the xcor() and ycor() methods. If the condition is true, we call the game_over() function.

We also check if the snake has collided with its own body by iterating over the «segments» list and checking the distance between each segment and the snake. If the condition is true, we call the game_over() function.

Conclusion

Congratulations! You have successfully created a Snake game in Python using the Turtle module. You have learned how to create the game window, create the snake, move the snake, handle keyboard input, create the food, check for collisions, update the score, and handle game over. Feel free to customize the game by adding more features, such as levels, obstacles, or power-ups. Have fun playing and coding!

Author

osceda@hotmail.com

Leave a comment

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *