Write the game Snakes in python using turtle with scoring and make it play itself in a loop
mistral-nemo:latest
import turtle
import random
import time
# Set up screen
win = turtle.Screen()
win.title("Automatic Snake Game")
win.bgcolor("black")
win.setup(width=600, height=600)
win.tracer(0)
# Snake head
head = turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("white")
head.penup()
# Initialize head direction and movement variables
head.direction = random.choice(["up", "down", "left", "right"])
head.x_move = 0
head.y_move = 0
# Snake food
food = turtle.Turtle()
food.speed(0)
food.shape("circle")
food.color("red")
food.penup()
# Snake body (list of turtles)
segments = []
# Game variables
score = 0
attraction_force = 1
# Functions
def move():
if head.x_move == 0 and head.y_move == 0:
head.direction = random.choice(["up", "down", "left", "right"])
# Attract the snake towards the food
if head.distance(food) > 20:
if head.xcor() < food.xcor():
head.x_move = attraction_force
elif head.xcor() > food.xcor():
head.x_move = -attraction_force
else:
head.x_move = 0
if head.ycor() < food.ycor():
head.y_move = attraction_force
elif head.ycor() > food.ycor():
head.y_move = -attraction_force
else:
head.y_move = 0
# Move the snake head
head.setx(head.xcor() + head.x_move)
head.sety(head.ycor() + head.y_move)
def update():
global score, attraction_force
# Check border collision and change direction
if (
head.xcor() > 290
or head.xcor() < -290
or head.ycor() > 290
or head.ycor() < -290
):
head.direction = random.choice(["up", "down", "left", "right"])
head.x_move = 0
head.y_move = 0
# Check for food collision
if head.distance(food) < 20:
x = random.randint(-290, 290)
y = random.randint(-290, 290)
food.goto(x, y)
# Add a segment to the snake body
new_segment = turtle.Turtle()
new_segment.speed(0)
new_segment.shape("square")
new_segment.color("grey")
new_segment.penup()
segments.append(new_segment)
# Move the snake body segments
for index in range(len(segments) - 1, 0, -1):
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)
# Move the head
move()
# Check for head collision with the body segments
for segment in segments:
if segment.distance(head) < 20:
time.sleep(1)
head.goto(0, 0)
head.direction = random.choice(["up", "down", "left", "right"])
head.x_move = 0
head.y_move = 0
for segment in segments:
segment.goto(1000, 1000)
segments.clear()
# Update the score and attraction force (difficulty)
score += 1
win.title(f"Automatic Snake Game | Score: {score}")
if score % 5 == 0 and score != 0:
attraction_force = min(attraction_force + 1, 3)
# Update the screen
win.update()
# Main game loop (automatic movement)
while True:
update()
time.sleep(0.1) # Adjust the delay to change the snake's speed
turtle.done()
This works