How to Make a Snake Game in Python


If you might be person who enjoys enjoying the snake recreation, I’m certain you are going to to find this text fascinating.

In this text, I will be able to educate you ways to get a hold of a easy snake recreation that even a newbie in Python would to find simple to broaden.

There exists a collection of tactics to create this recreation and one comprises using Python’s PyGame library which is a Python library we use to create video games.

The wrong way is by means of the turtle library. This module comes pre-installed with Python and it supplies a digital canvas for customers to create shapes and photographs.

Therefore, this text will use the turtle library to enforce our easy snake recreation which is beginner-friendly particularly for newbie Python builders.

In addition to this module, we can additionally use two different modules particularly;

  • Time module – This means will permit us to stay observe of the collection of seconds that experience elapsed because the earlier time.
  • Random module – It generates numbers randomly in Python.

Other elementary gear you are going to want to use come with a textual content editor of your selection. I will be able to use VSCode in this text. Of path, you are going to want to set up Python 3 to your gadget in the event you wouldn’t have it already. You may additionally use the Geekflare Compiler.

This must be amusing!

How the snake recreation works

The final purpose of this recreation is for the participant to reach the perfect rating by way of controlling the snake to accumulate the meals the display presentations.

The participant controls the snake the use of 4 path keys which might be relative to the path the snake is transferring against. Should the snake hit a block or itself, the participant loses the sport.

The following steps we can observe to enforce this recreation.

  • Importing into our techniques the pre-installed modules (turtle, time, and random).
  • Creating the sport’s display show the use of the turtle module.
  • Setting the keys for the snake’s transferring path across the display.
  • The gameplay implementation.

Create a snakegame.py report in which we can upload the implementation code.

Importing the modules

This little bit of the code will import the turtle, time, and random modules which might be by way of default pre-installed in Python. Additionally, we can then set default values for the participant’s preliminary rating, the perfect rating the participant will reach, and the time of lengthen taken by way of the participant in each and every transfer. The time module is used right here to calculate the time of lengthen.

Add the next little bit of code to your snakegame.py report.

import turtle
import random
import time

player_score = 0
highest_score = 0
delay_time = 0.1

Creating the sport’s display show

The turtle module we import right here will permit us to create a digital canvas that would be the recreation’s window display. From right here, we will be able to create the snake’s frame and the meals the snake will accumulate. Our display may also show the participant’s tracked rating.

Add this code to the Python report.

. . .
# window display created
wind = turtle.Screen()
wind.identify("Snake Maze🐍")
wind.bgcolor("crimson")

# The display measurement
wind.setup(width=600, peak=600)


# growing the snake 
snake = turtle.Turtle()
snake.form("sq.")
snake.colour("black")
snake.penup()
snake.goto(0, 0)
snake.path = "Stop"

# growing the meals
snake_food = turtle.Turtle()
shapes = random.selection('triangle','circle')
snake_food.form(shapes)
snake_food.colour("blue")
snake_food.pace(0)
snake_food.penup()
snake_food.goto(0, 100)

pen = turtle.Turtle()
pen.pace(0)
pen.form('sq.')
pen.colour('white')
pen.penup()
pen.hideturtle()
pen.goto(0, 250)
pen.write("Your_score: 0 Highest_Score : 0", align="middle", 
font=("Arial", 24, "customary"))
turtle.mainloop()

The code snippet above begins with initializing the turtle display and passes a identify and a background colour to the display. After defining the window measurement of our display, we draw the form of the snake at the digital canvas.

The penup() means merely alternatives up the turtle’s pen in order that a line isn’t drawn because the turtle strikes. The goto(x,y) means incorporates coordinate positions that transfer the turtle to an absolute place.

We then create the meals that the snake collects. We will need to show the participant’s rating each and every time the snake collects the meals and the perfect rating the participant reaches all the way through the sport. Therefore,  we use the pen.write() means to enforce this. The hideturtle() hides the turtle icon from the display at the header phase that this article is written.

It is vital to upload the turtle.mainloop() on the finish of your code, which can show the display longer to permit you the consumer to do one thing at the display.

Run the report and you will have the next output:

The snake and food display with the player's initial and highest score.

Setting up the path keys for the snake

Here, we can arrange particular keys that may information the path the snake might be transferring at the display. We will use the ‘L’ for left, ‘R’ for proper, ‘U’ for up, ‘D’ for down. We will enforce those instructions the use of the turtle’s path serve as that we can name at the snake.

Add the next code snippet to your code.

# Assigning instructions
def moveleft():
    if snake.path != "proper":
        snake.path = "left"

def moveright():
    if snake.path != "left":
        snake.path = "proper"

def moveup():
    if snake.path != "down":
        snake.path = "up"

def movedown():
    if snake.path != "up":
        snake.path = "down"

def transfer():
    if snake.path == "up":
        coord_y = snake.ycor()
        snake.sety(coord_y+20)

    if snake.path == "down":
        coord_y = snake.ycor()
        snake.sety(coord_y-20)

    if snake.path == "proper":
        coord_x = snake.xcor()
        snake.setx(coord_x+20)

    if snake.path == "left":
        coord_x = snake.xcor()
        snake.setx(coord_x-20)

wind.pay attention()
wind.onkeypress(moveleft, 'L')
wind.onkeypress(moveright, 'R')
wind.onkeypress(moveup, 'U')
wind.onkeypress(movedown, 'D')

The transfer() serve as above units the motion of the snake in the outlined place inside a exact coordinate price.

The pay attention() serve as is an match listener that calls at the strategies that transfer the snake to a explicit path when the participant presses the important thing.

The snake recreation gameplay implementation

After laying down the fundamental outlook of our snake recreation, we can have to make the sport real-time.

This will contain the next:

  • Growing the snake’s period each and every time it collects the meals by way of ideally the use of a other colour.
  • Incrementing the participant’s rating each and every time the snake collects the meals and monitoring the perfect rating.
  • The participant is in a position to keep an eye on the snake from colliding with the wall or its personal frame.
  • The recreation restarts when the snake collides.
  • The participant’s rating is reset to 0 when the sport restarts, whilst the display keeps the participant’s perfect rating.

Add the remainder of this code to your python report.

segments = []

#Implementing the gameplay
whilst True:
    wind.replace()
    if snake.xcor() > 290 or snake.xcor() < -290 or snake.ycor() > 290 or snake.ycor() < -290:
        time.sleep(1)
        snake.goto(0, 0)
        snake.path = "Stop"
        snake.form("sq.")
        snake.colour("inexperienced")

        for section in segments:
            section.goto(1000, 1000)
            segments.transparent()
            player_score = 0
            delay_time = 0.1
            pen.transparent()
            pen.write("Player's_score:  Highest_score: ".layout(player_score, highest_score), align="middle", font=("Arial", 24, "customary"))

        if snake.distance(snake_food) < 20:
            coord_x = random.randint(-270, 270)
            coord_y = random.randint(-270, 270)
            snake_food.goto(coord_x, coord_y)

            # Adding section
            added_segment = turtle.Turtle()
            added_segment.pace(0)
            added_segment.form("sq.")
            added_segment.colour("white")
            added_segment.penup()
            segments.append(added_segment)
            delay_time -= 0.001
            player_score += 5

            if player_score > highest_score:
                highest_score = player_score
                pen.transparent()
                pen.write("Player's_score:  Highest_score: ".layout(player_score, highest_score), align="middle", font=("Arial", 24, "customary"))

    # checking for collisions
    for i in vary(len(segments)-1, 0, -1):
        coord_x = segments[i-1].xcor()
        coord_y = segments[i-1].ycor()
        segments[i].goto(coord_x, coord_y)

    if len(segments) > 0:
        coord_x = snake.xcor()
        coord_y = snake.ycor()
        segments[0].goto(coord_x, coord_y)
    transfer()

    for section in segments:
        if section.distance(snake) < 20:
            time.sleep(1)
            snake.goto(0, 0)
            snake.path = "forestall"
            snake.colour('white')
            snake.form('sq.')

            for section in segments:
                section.goto(1000, 1000)
                section.transparent()
                player_score = 0
                delay_time = 0.1
                pen.transparent()
                pen.write("Player's_score:  Highest_score: ".layout(player_score, highest_score), align="middle", font=("Arial", 24, "customary"))

     time.sleep(delay_time)

turtle.mainloop()

In the above code snippet, we set a random place for the snake’s meals inside the display. Every time the snake collects this meals, its frame section will increase with a other colour; white, in this example, to distinguish its enlargement.

After the snake collects the meals with out colliding, the meals is about at a random place inside the 270 coordinate vary of the display measurement. Every time the snake collects meals, the participant’s rating increments by way of 5.  When the snake collides, the participant’s rating is about to 0 whilst the display keeps its perfect rating.

Now go back the Python report and also you must see your turtle display taking a look like this:

Conclusion 🐍

Using the turtle library is one amusing and simple method to create the snake recreation as we've got noticed in this text. Alternatively, it is advisable enforce the similar the use of the PyGame library. You can take a look at the PyGame tutorial here and spot how it is advisable enforce the sport another way.

You may additionally check out a quantity guessing recreation in Python. Enjoy coding!

Related Articles

Leave a Reply

Your email address will not be published.

Back to top button