Snake Game - Task2
Snake Game - Task2
To run and execute the provided Snake game code using the turtle module, you can follow these
steps:
food = vector(0, 0)
aim.x = x
aim.y = y
def inside(head):
return -200 < head.x < 190 and -200 < head.y < 190
def move():
head = snake[-1].copy()
head.move(aim)
if not inside(head) or head in snake:
update()
return
snake.append(head)
if head == food:
print('Snake:', len(snake))
else:
snake.pop(0)
clear()
update()
ontimer(move, 100)
hideturtle()
tracer(False)
listen()
move()
done()
Open a terminal or command prompt and navigate to the directory where you saved snake_game.py.
Then run the following command:
bash
Copy code
python snake_game.py
Explanation:
Import Statements:
from turtle import *: Imports all necessary functions from the turtle module.
from random import randrange: Imports the randrange function from the random module.
from freegames import square, vector: Imports the square and vector functions from the freegames
module.
Global Variables:
food, snake, aim: Define the food position, the snake's body, and the snake's direction.
Functions:
move(): Moves the snake, checks for collisions, updates the snake's body, and redraws the game
screen.
Game Setup:
This will start the Snake game, and you can control the snake using the arrow keys. The snake will
grow as it eats the food, and the game will end if the snake collides with the boundaries or itself.