Fifth Python Project: Snake Game - 1

 

Requirements (The highlighted parts are the ones covered this time):

1. Create a snake body
2. Move the snake
3. Control the snake

4. Detect collision with food
5. Create a scoreboard
6. Detect collision with wall (The game should display "Game Over" and the snake should stop moving)
7. Detect collision with tail (The game should end when the snake's head touches its own body)

 

 

snake.py

from turtle import Turtle

STARTING_POSITIONS = [(0, 0), (-20, 0), (-40, 0)]
MOVE_DISTANCE = 20
UP = 90
DOWN = 270
LEFT = 180
RIGHT = 0


class Snake:
    
    def __init__(self):
        self.segments = []
        self.create_snake()
        self.head = self.segments[0]

    def create_snake(self):
        for position in STARTING_POSITIONS:
            new_segment = Turtle(shape="square")
            new_segment.color("white")
            new_segment.penup()
            new_segment.goto(position)
            self.segments.append(new_segment) 
    
    def move(self):
        for segment_num in range(len(self.segments)-1, 0,-1):
            new_x = self.segments[segment_num - 1].xcor()
            new_y = self.segments[segment_num - 1].ycor()
            self.segments[segment_num].goto(new_x, new_y)
        self.head.forward(MOVE_DISTANCE)
        
    def up(self):
        if self.head.heading() != DOWN:
            self.head.setheading(UP)
    
    def down(self):
        if self.head.heading() != UP:
            self.head.setheading(DOWN)
    
    def left(self):
        if self.head.heading() != RIGHT:
            self.head.setheading(LEFT)
           
    def right(self):
        if self.head.heading() != LEFT:
            self.head.setheading(RIGHT)

 

main.py

from turtle import Screen, Turtle
from snake import Snake
import time

screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("Snake Game")
screen.tracer(0)
starting_position = [(0, 0), (-20, 0), (-40, 0)]

snake = Snake()

screen.listen()
screen.onkey(snake.up, "Up")
screen.onkey(snake.down,"Down")
screen.onkey(snake.left, "Left")
screen.onkey(snake.right, "Right")

game_is_on = True
while game_is_on:
    screen.update()
    time.sleep(0.005)
    
    snake.move()

screen.exitonclick()

 

 

Realization:

1. The `screen.update()` method can be used to delay updates,

    making the snake's movement appear smooth in the game.

2. Using a timer allows you to adjust the screen refresh rate. 

    The faster the refresh rate, the quicker the objects appear to move.

3. Variables that are used as fixed values should be defined as constants to keep the code clean