Import Required Modules
Import Required Modules
import turtle
import time
import random
delay = 0.1
score = 0
high_score = 0
wn = turtle.Screen()
wn.title("Snake Game")
wn.bgcolor("blue")
wn.setup(width=600, height=600)
wn.tracer(0)
head = turtle.Turtle()
head.shape("square")
head.color("white")
head.penup()
head.goto(0, 0)
head.direction = "Stop"
food = turtle.Turtle()
food.speed(0)
food.shape("circle")
food.color("red")
food.penup()
food.goto(0, 100)
pen = turtle.Turtle()
pen.speed(0)
pen.shape("square")
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0, 260)
def go_up():
if head.direction != "down":
head.direction = "up"
def go_down():
if head.direction != "up":
head.direction = "down"
def go_left():
if head.direction != "right":
head.direction = "left"
def go_right():
if head.direction != "left":
head.direction = "right"
def move():
if head.direction == "up":
y = head.ycor()
head.sety(y + 20)
if head.direction == "down":
y = head.ycor()
head.sety(y - 20)
if head.direction == "left":
x = head.xcor()
head.setx(x - 20)
if head.direction == "right":
x = head.xcor()
head.setx(x + 20)
# Keyboard bindings
wn.listen()
wn.onkeypress(go_up, "w")
wn.onkeypress(go_down, "s")
wn.onkeypress(go_left, "a")
wn.onkeypress(go_right, "d")
segments = []
# Main Gameplay
while True:
wn.update()
if (
):
time.sleep(1)
head.goto(0, 0)
head.direction = "Stop"
segment.goto(1000, 1000)
segments.clear()
score = 0
delay = 0.1
pen.clear()
pen.write(
align="center",
x = random.randint(-270, 270)
y = random.randint(-270, 270)
food.goto(x, y)
new_segment = turtle.Turtle()
new_segment.speed(0)
new_segment.shape("square")
new_segment.color("orange")
new_segment.penup()
segments.append(new_segment)
score += 10
high_score = score
pen.clear()
pen.write(
align="center",
x = segments[index - 1].xcor()
y = segments[index - 1].ycor()
segments[index].goto(x, y)
if len(segments) > 0:
x = head.xcor()
y = head.ycor()
segments[0].goto(x, y)
time.sleep(1)
head.goto(0, 0)
head.direction = "Stop"
seg.goto(1000, 1000)
segments.clear()
score = 0
delay = 0.1
pen.clear()
pen.write(
align="center",
move()
# Add a delay
time.sleep(delay)
# This code creates a functional Snake game using the Turtle graphics library in Python. Players
control the snake with the "w," "s," "a," and "d" keys to collect red food while avoiding collisions with
the screen borders and the snake's own body. The game keeps track of the player's score and high
score. When the snake collides with the screen border or itself, the game resets.
Please note that this code snippet does not include a game over condition when the player decides
to quit the game. You may want to add a mechanism to allow players to exit the game gracefully if
needed.