Snake Game in Using Python Module

I’m confident that this essay will be helpful to you if you’re a fan of the game of snakes. I’ll walk you through the steps of creating a simple game in this post that even Python newbies will find easy to create. The PyGame library in Python, which is a Python package we use to develop games, is one of the various approaches to design the game.

Making use of the library turtle is an additional strategy. Users can generate graphics and draw forms on an online canvas thanks to this module, which is already installed with Python. So, in this tutorial, we’ll use the turtle library to build our fundamental snake

Snake Game in Python

  • time module. This technique allows us to track the amount of seconds which have passed since the previous time.
  • the snake game Random module – It creates random numbers in Python.

Other tools that you’ll require include an editor for text that you prefer. I’ll be using VSCode in this post. Of course, you’ll require in order to set up Python 3 on your device if you don’t have it installed already. You can also download to install the Geekflare Compiler. This could be a lot of an enjoyable experience!

Contents

How does the snake game work

Players must manipulate the snake to acquire the food that is displayed on the screen in order to achieve the best score possible in this game. The player directs the snake by pressing one of four directional keys that point in the direction the snake is moving.

The snake will be removed from the game if it strikes a player or an object. The procedures we’ll use to play this game moving forward.

  • Importing into our applications the modules that are pre-installed (turtle time, turtle as well as random).
  • The game’s screen display is created with Turtle module.
  • Set the keys to control the snake’s direction of movement around the screen.
  • The game’s implementation.

Create the snakegame.py file to which we’ll add an implementation program.

Importing the modules

This section of the programme loads the Python-installed time, turtle, and random modules. Additionally, default numbers for the player’s initial score, the maximum score they can reach, and the amount of time the player delays between each move will be defined. In order to determine how much time has been delayed, the time module is needed.

import turtle
import random
import time

player_score = 0
highest_score = 0
delay_time = 0.1

Making the game’s screen

The turtle module that we install allows us to create a virtual screen that will serve as the game’s window screen. We can then build the snake’s body, as well as the food items that the snake will eat. The screen will also show the score of the player’s tracker.

# window screen created
wind = turtle.Screen()
wind.title("Snake Maze")
wind.bgcolor("red")

# The screen size
wind.setup(width=600, height=600)


# creating the snake 
snake = turtle.Turtle()
snake.shape("square")
snake.color("black")
snake.penup()
snake.goto(0, 0)
snake.direction = "Stop"

# creating the food
snake_food = turtle.Turtle()
shapes = random.choice('triangle','circle')
snake_food.shape(shapes)
snake_food.color("blue")
snake_food.speed(0)
snake_food.penup()
snake_food.goto(0, 100)

pen = turtle.Turtle()
pen.speed(0)
pen.shape('square')
pen.color('white')
pen.penup()
pen.hideturtle()
pen.goto(0, 250)
pen.write("Your_score: 0 Highest_Score : 0", align="center", 
font=("Arial", 24, "normal"))
turtle.mainloop()

The code in the aforementioned excerpt establishes the turtle screen first before adding an initial title and backdrop colour. We first choose the size before sketching the snake’s shape onto our digital canvas. To prevent lines from being made while the turtle is moving, the penup method picks up the turtle’s pen.

With the use of its goto technique, the turtle may be directed to an exact position using coordinates. The food that the snake eats is made by us.

Every time the snake gathers food, we want to display each player’s score. We also want to show the highest score a person receives during the game. For this reason, we use pens. As the pen, write. Describe a method to complete.

The setting up of directions keys for the snake

In this instance, we programme certain keys to control the snake’s motion across the screen. We’ll use the letter “L” as the left key, “R” for left, “U” for upwards, and “D” for downwards. These instructions will be put into practise by calling the snake using the turtle’s direction function.

Include the following code examples in your.

# Assigning directions
def moveleft():
    if snake.direction != "right":
        snake.direction = "left"

def moveright():
    if snake.direction != "left":
        snake.direction = "right"

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

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

def move():
    if snake.direction == "up":
        coord_y = snake.ycor()
        snake.sety(coord_y+20)

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

    if snake.direction == "right":
        coord_x = snake.xcor()
        snake.setx(coord_x+20)

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

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

Move() function mentioned above allows the snake’s movement in the position that is specified within a specified coordinate. Listen() functions as an event listener which calls on the methods that direct the snake in a certain direction once the user press the button.

The implementation of the game’s gameplay in the form of a snake

The game will need to be converted into a live-action after the fundamental structure has been established. This is what it will include:

  • extending the snake’s length by a different colour each time it consumes food.
  • whenever the snake consumes food, the player’s score is increased, and the highest score is then tracked.
  • The snake may be held to protect it from slamming against the wall or even its own body.
  • After striking the snake, the game continues.
  • On the screen however, is the player’s highest score even though the player’s score is reset to zero when the game is restarted.
segments = []

#Implementing the gameplay
while True:
    wind.update()
    if snake.xcor() > 290 or snake.xcor() < -290 or snake.ycor() > 290 or snake.ycor() < -290:
        time.sleep(1)
        snake.goto(0, 0)
        snake.direction = "Stop"
        snake.shape("square")
        snake.color("green")

        for segment in segments:
            segment.goto(1000, 1000)
            segments.clear()
            player_score = 0
            delay_time = 0.1
            pen.clear()
            pen.write("Player's_score: {} Highest_score: {}".format(player_score, highest_score), align="center", font=("Arial", 24, "normal"))

        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 segment
            added_segment = turtle.Turtle()
            added_segment.speed(0)
            added_segment.shape("square")
            added_segment.color("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.clear()
                pen.write("Player's_score: {} Highest_score: {}".format(player_score, highest_score), align="center", font=("Arial", 24, "normal"))

    # checking for collisions
    for i in range(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)
    move()

    for segment in segments:
        if segment.distance(snake) < 20:
            time.sleep(1)
            snake.goto(0, 0)
            snake.direction = "stop"
            snake.color('white')
            snake.shape('square')

            for segment in segments:
                segment.goto(1000, 1000)
                segment.clear()
                player_score = 0
                delay_time = 0.1
                pen.clear()
                pen.write("Player's_score: {} Highest_score: {}".format(player_score, highest_score), align="center", font=("Arial", 24, "normal"))

     time.sleep(delay_time)

turtle.mainloop()

In the code snippet above that we’ve used, we’ve assign a random place for the snake’s food on the screen. Each time the snake eats the nutrition, the body grows in a different color, white in this instance, to make it clear that its growth is distinct.

When the snake has collected the food and does not collide, the food is displayed in a random location within the 270-degree coordinate area of the screen’s size. Every time the snake takes food, the score of the player increases by 5. If the snake is involved in a collision with the player, their score is reset to 0 and the screen keeps its highest score.

Conclusion

The turtle library is a fun and simple way to make the snakes game that we’ve seen in this tutorial. You can also use the PyGame library in Python to implement the same game. Find out how you may utilise the game differently by reading these PyGame instructions.

Download Snake Rivals Fun Snake Game

Snake Run Race 3D Running Game

Download Snake.io – Fun Snake .io Games