Snake Game in Python – A Cool Python Project!

1202
0
snake game in Python

The snake game in python is a fun way to teach kids about programming. You need to create a program that takes input from the user and then displays the output based on what they typed. The user enters a number between 1-10 and then the program should display the corresponding number of snakes. If the user types anything else, the program should print out an error message.

Using Python to create a snake game is demonstrated in this video, and I have posted the demo video for the snake game in python on my youtube channel.

Requirements:

  • Any Code editor or IDE (Pycharm or VS code).
  • Python Interpreter.
  • psutil (pip install psutil).

Some Screenshots of Snake Game in Python

snake game in python
snake game in python
snake game in python
snake game in python

Source Code

# importing Libraries
import turtle
import random
import time

# creating turtle screen
screen = turtle.Screen()
screen.title('Snake Game')
screen.setup(width=900, height=700)
screen.tracer(0)
turtle.bgcolor('#1a1a1a')

# creating a border for our game
turtle.speed(5)
turtle.pensize(4)
turtle.penup()
turtle.goto(-410, 250)
turtle.pendown()
turtle.color('red')
turtle.forward(820)
turtle.right(90)
turtle.forward(500)
turtle.right(90)
turtle.forward(820)
turtle.right(90)
turtle.forward(500)
turtle.penup()
turtle.hideturtle()

# score
score = 0
delay = 0.1

# snake
snake = turtle.Turtle()
snake.speed(0)
snake.shape('circle')
snake.color('#FE0000')
snake.penup()
snake.goto(0,0)
snake.direction="stop"

# food
fruit = turtle.Turtle()
fruit.speed(0)
fruit.shape('turtle')
fruit.color('#00fe1f')
fruit.penup()
fruit.goto(30, 30)

old_fruit=[]

# Scoring
scoring = turtle.Turtle()
scoring.speed(0)
scoring.color('white')
scoring.penup()
scoring.hideturtle()
scoring.goto(0, 300)
scoring.write("Start Eating Turtles", align="center", font=("Courier",24,"bold"))

# define the movement
def snake_go_up():
    if snake.direction != "down":
        snake.direction = "up"

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

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

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

def snake_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)

# keyboard bindings
screen.listen()
screen.onkeypress(snake_go_up, "Up")
screen.onkeypress(snake_go_down, "Down")
screen.onkeypress(snake_go_left, "Left")
screen.onkeypress(snake_go_right, "Right")

# Main loop
while True:
    screen.update()
    # snake and fruit collision
    if snake.distance(fruit) < 20:
        x = random.randint(-290, 270)
        y = random.randint(-240, 240)
        fruit.goto(x, y)
        scoring.clear()
        score += 1
        scoring.write("Score: {}".format(score), align="center", font=("Courier", 24, "bold"))
        delay-=0.001

        # creating new_fruit
        new_fruit = turtle.Turtle()
        new_fruit.speed(0)
        new_fruit.shape('circle')
        new_fruit.color('#00fe1f')
        new_fruit.penup()
        old_fruit.append(new_fruit)

    # adding fruit to snake
    for index in range(len(old_fruit)-1,0,-1):
        a = old_fruit[index-1].xcor()
        b = old_fruit[index-1].ycor()

        old_fruit[index].goto(a,b)
    
    if len(old_fruit) > 0:
        a = snake.xcor()
        b = snake.ycor()
        old_fruit[0].goto(a, b)
    snake_move()

    # snake and border collision
    if snake.xcor() > 400 or snake.xcor() < -400 or snake.ycor() > 240 or snake.ycor() < -240:
        time.sleep(1)
        screen.clear()
        screen.bgcolor('#1a1a1a')
        scoring.goto(0, 0)
        scoring.write("    GAME OVER \n Your Score is {}".format(score), align="center", font=("Courier", 30, "bold"))

    # snake collision
    for food in old_fruit:
        if food.distance(snake) < 20:
            time.sleep(1)
            screen.clear()
            screen.bgcolor('#1a1a1a')
            scoring.goto(0, 0)
            scoring.write("    GAME OVER \n Your Score is {}".format(score), align="center", font=("Courier", 30, "bold"))
    time.sleep(delay)
Python

Code Explanation

Importing Libraries

The first thing the code does is import necessary libraries such as turtle, random, and time.

Creating Turtle Screen

The next step is creating a turtle screen for the game with a title, size, and background color. A border is also created with a red color.

Score and Delay

Variables for score and delay are initialized. The score starts at 0 and delay is set to 0.1.

Snake and Fruit

The snake and fruit are created with respective attributes such as color, shape, and position. The snake starts at position (0,0) and the fruit is initially at (30,30).

Scoring

A turtle object for scoring is created with appropriate attributes such as font size, font style, and color.

Defining Movement

Functions are defined for the movement of the snake in all four directions – up, down, left, and right.

Keyboard Bindings

The snake’s movement is linked to the arrow keys on the keyboard using the onkeypress() method.

Main Loop

This is the main loop of the game. The loop continues running until the game is over. The screen is updated on each iteration using the update() method.

The first if statement checks if the snake has collided with the fruit. If it has, a new fruit is created at a random location, the score is increased by 1, and the delay is decreased by 0.001. A new turtle object for the fruit is also created and added to the old_fruit list.

The next block of code adds the old_fruit objects to the snake, creating a growing effect. This is achieved by moving each old_fruit object to the position of the object in front of it. The first old_fruit object is moved to the current position of the snake.

The snake_move() function is then called to move the snake in the current direction.

The next block of code checks for collision with the border. If the snake has collided with the border, the game is over and the screen displays the final score.

The final block of code checks for collision with the snake’s body. If the snake has collided with its own body, the game is over and the screen displays the final score.

Finally, the game sleeps for the amount of time specified in the delay variable using the time.sleep() method.

Watch This Demo Video

If you liked this, click the 💚 below so other people will see this here on Xalgord. Please let me know if you have any comments! Feel free to connect on Instagram.

xalgord
WRITTEN BY

xalgord

Constantly learning & adapting to new technologies. Passionate about solving complex problems with code. #programming #softwareengineering

Leave a Reply