I'm trying to create an easier version of the snake game. Everything in the code looks ok for me but I can't make snake move as I want to. Can you help me why my code doesn't work? I don't understand why my code is not okay.
I searched for some similar games codes, but they all used time. and I couldn't understand the need for that.
Here is the code:
import turtle
import random
window = turtle.Screen()
window.screensize(600, 600)
window.title("Snake Eats Tomato Game")
window.bgcolor("skyblue")
window.tracer(0)
snake = turtle.Turtle()
snake.color("dark blue")
snake.shape("square")
snake.shapesize(1)
snake.speed(1)
snake.penup()
snake.goto(0, 100)
snake.direction = "stop"
def 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)
point = 0
point_table = turtle.Turtle()
point_table.speed(0)
point_table.shape("square")
point_table.color("green")
point_table.penup()
point_table.hideturtle()
point_table.goto(-200, 200)
point_table.write(
"POİNT: {}".format(point), align="center", font=("Courier", 25, "normal")
)
def go_left():
if snake.direction != "right":
snake.direction = "left"
def go_right():
if snake.direction != "left":
snake.direction = "right"
def go_up():
if snake.direction != "down":
snake.direction = "up"
def go_down():
if snake.direction != "up":
snake.direction = "down"
window.listen()
window.onkey(go_left, "Left")
window.onkey(go_right, "Right")
window.onkey(go_up, "Up")
window.onkey(go_down, "Down")
tomato = turtle.Turtle()
tomato.penup()
tomato.color("tomato")
tomato.shape("circle")
tomato.speed(0)
tomato.setposition(random.randint(-300, 300), random.randint(-300, 300))
while True:
window.update()
snake.forward(3)
move()
if snake.xcor() < -330 or snake.xcor() > 330:
snake.right(90)
if snake.ycor() < -330 or snake.ycor() > 330:
snake.right(90)
if snake.distance(tomato) < 20:
point += 1
point_table.clear()
point_table.write(
"PUAN: {}".format(point), align="center", font=("Courier", 25, "normal")
)
tomato.setposition(random.randint(-300, 300), random.randint(-300, 300))
