For a class (snake class) created from the turtle module in Python:
Problem 1. when the move() method is called, the snake segments are moving backwards instead of forward . The problem seems to be the return function called in each method (I think it is), where the original position of the snake is called, thus it cannot move forward
Fixed this by removing the return function in the positions() method, but a new problem arises when the screen briefly opens and closes, the fault may lie in the move() method [i.e., in this line, snake_segments = self.segments()]
Given are the code for Problem 1, the fix for for problem 2, and the main.py code
Problem 1 (snake segments moving backward instead of forward):
from turtle import Turtle
class Snake:
def __init__(self):
self.x = 0
self.y = 0
def positions(self):
start_pos = []
for _ in range(0, 3):
start_pos.append((self.x, self.y))
self.x -= 20
return start_pos
def segments(self):
new_positions = self.positions()
snake_segments = []
for cord in new_positions:
new_turtle = Turtle()
new_turtle.penup()
new_turtle.shape("square")
new_turtle.color("white")
self.x = cord[0]
self.y = cord[1]
new_turtle.goto(x=self.x, y=self.y)
snake_segments.append(new_turtle)
return snake_segments
def move(self):
snake_segments = self.segments()
for segment_index in range(len(snake_segments) - 1, 0, -1):
new_x = snake_segments[segment_index - 1].xcor()
new_y = snake_segments[segment_index - 1].ycor()
snake_segments[segment_index].goto(new_x, new_y)
snake_segments[0].forward(20)
Below is the Fix for Problem 1 but gives Problem 2 (screen opens and closes)
from turtle import Turtle
class Snake:
def __init__(self):
self.x = 0
self.y = 0
def positions(self):
start_pos = []
for _ in range(0, 3):
start_pos.append((self.x, self.y))
self.x += 20
self.segments(start_pos)
def segments(self, start_pos):
# new_positions = self.start_pos
snake_segments = []
for cord in start_pos:
new_turtle = Turtle()
new_turtle.penup()
new_turtle.shape("square")
new_turtle.color("white")
self.x = cord[0]
self.y = cord[1]
new_turtle.goto(x=self.x, y=self.y)
snake_segments.append(new_turtle)
return snake_segments
def move(self):
snake_segments = self.segments()
#print(snake_segments)
for segment_index in range(len(snake_segments) - 1, 0, -1):
new_x = snake_segments[segment_index - 1].xcor()
new_y = snake_segments[segment_index - 1].ycor()
snake_segments[segment_index].goto(new_x, new_y)
snake_segments[0].forward(20)
Below is the main.py file
from turtle import Screen, Turtle import time from snake import Snake
screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("My Snake Game")
screen.tracer(0)
snake = Snake()
game_is_on = True
while game_is_on:
screen.update()
time.sleep(0.5)
snake.move()
screen.exitonclick()
whileloop idiom is not a good way to do a realtime event loop in turtle. Preferontimer.self.xandself.ybeing modified inpositions(...)andsegments(...)while they should only be modified inmove(...).