Snake Game in Using Python Module Program Code

Snake Game in Using Python Module: 

If you are one of those people who are lover of playing snakes game then I am sure you will find this article useful. In this article, I’ll show you how to make the basics of the game very easily, even for those new to Python.

There are several ways to design a snakes game, one of which is through the use of the PyGame library within Python which is the Python library we use to make games.

The library comes with an online canvas that users can use to create shapes and images. and is already installed in python. So, in this post we will use Turtle program to create our simple Snake game which is perfect for individuals who have just started programming, especially Python developers.

Snake Game in Using Python Module

Within this course it can also employ two other modules, which are

  • time module. This allows us to keep track of the number of seconds that has passed between the last time.
  • The snake-game Random Module It generates random numbers in Python.

Other tools you’ll require include an editor for the text you like. I’ll use VSCode in this article. Of course, you’ll need it the following tools to install Python 3 on your device If there’s no Python 3 already. It is also possible to download and run your Geekflare Compiler. It could be a great deal of fun!

What is the process by which the snake game function?

The objective of this snake game is to manipulate the snake while eating the food items displayed on the screen in order to get the highest score.

Four keys are used by the player to control the direction of the game. They are moving in the direction in which the snake is moving. The snake game is ejected from action when it comes into contact with something. And the game has to be restarted.

  • Incorporating into our software the modules already installed (turtle time and turtle and random).
  • Snake Game’s display is made using the Turtle module.
  • The keys are set that determine the direction of the snake’s motion across the monitor.
  • Snake Game’s execution.

Make the snakegame.py file, to which we’ll include an implementation program.

The modules are imported

The time, turtle, and other Python modules are loaded in this area of snake game coding. Will also set the player’s starting score, the highest score the player can achieve, and the time the player spends on each move as default values. The delay can be calculated using the timing module.

import turtle
import random
import time

player_score = 0
highest_score = 0
delay_time = 0.1

Screens fors nake games are created.

Installing the tortoise module helps us to create a virtual screen. Which can serve as the mobile window of the game. The snake’s body can then be made, as well as the food the snake will eat. Additionally, it will show the score in 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 as seen in the above snippet starts by creating the turtle screen. And then it adds a title and color for the background screen. After determining the size of the screen, we draw the snake design on our canvas.

The penup method moves that pen over the turtle to ensure that a line is drawn when the turtle moves. Its goto method provides coordinates to allow the turtle to be directed to the exact location.

We grow the foods that snakes eat. In addition to the highest score a player can earn during the game, we want to show each player’s score when the snake collects food. That’s why we use pens. Writes as a pen. writing techniques to achieve this. Hideturtle will move the turtle icon from the screen to within the header area of whatever it is writing.

It is necessary to add your turtle.mainloop to the last line in your program which will allow the screen to be displayed for a long time allowing you user to perform an action in this screen.

The configuration of keys to direct the snake

In this scenario we will create keys to determine the direction in which the snake will be moving on the display. We will make use of the letters “L” as left key, and the ‘R’ for left, the letter ‘U indicates upwards and ‘D to mean down. We will apply these directions by using directions function on the turtle, which we will call”the snake.

Copy the code snippets that follow into 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')

The Move() function as mentioned earlier permits the snake’s movements to be in the direction defined within a specific area. Listen() is an event listener that relies on methods that will direct the snake’s movement in a specific direction after the user presses the button.

The method of implementing the game’s play in the form of snakes

After laying the fundamental outline of the game, we’ll have to make the game live-action. This will comprise the following:

  • increasing the diameter of the snake every time it is able to take in food by using the use of a different color.
  • increasing the scoring of the gamer each time the snake eats food and then keeping track of the score that has the most.
  • The player has the option of keeping the snake away to avoid hitting the wall, or maybe even hitting it’s own physique.
  • The game continues after the snake has been struck.
  • A player’s score will be reset to zero when the game is restarted however, the screen will show the score that is the highest of the player.
segments = []

#Implementing the gameplay
while True:
    wind.update()
    if snake.xcor() > 280 or snake.xcor() < -280 or snake.ycor() > 290 or snake.ycor() < -280:
        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()

We have given the display an unknown position for the snake’s food in the code snippet that we have used. The snake’s body will change to a new hue as it grows and absorbs nutrition, in this case turning white to demonstrate how its growth pattern is distinct.

The item is presented at random positions throughout the 270 degree coordinate region of the screen’s dimensions if the snake has taken the food but does not meet. The snake’s score for the player goes up by five each time it eats. Participants’ scores are reset to zero and the top scores are displayed on the screen if the snake collides with them.

Conclusion

This snake game you saw in this post may be expanded upon using this library for turtles in a simple and entertaining manner. The Python PyGame library may also be used to construct the same snake game. Learn a new method to play the snake game by watching this PyGame lesson.

Best YouTube Video to MP3 Converter App

Download Prime Video Android TV for PC

Leave a Comment