How I understand it:
In while loop I upgrade window with each iteration, then I call _snake_move() which checks if there was a button pressed (at the beginning direction is 'stop', so nothing happens), then if 'w' is pressed then go_up() is called which changes snake.direction to 'up'. With next iteration of the loop we call _snake_move() which now activates one of the conditional statements and causes sety(y+20) which should move the snake. Why it's not working?
import turtle
class Settings():
def __init__(self):
""" Initialize settings of the game. """
self.window_width = 500
self.window_height = 500
self.bgcolor = 'blue'
self.game_title = 'Reinforced Snake'
self.food = False
self.snake_color = 'red'
class Reinforced_Snake():
def __init__(self):
""" Initialize classes for the main one. """
# initialize classes
self.settings = Settings()
# initialize the main screen of the game
self.window = turtle.Screen()
self.window.bgcolor(self.settings.bgcolor)
self.window.title(self.settings.game_title)
self.window.setup(width = self.settings.window_width,
height = self.settings.window_height)
# initialize the snake
self._init_snake()
# turn off screen updates
self.window.tracer(0)
def _init_snake(self):
""" Initialize the snake instead of creating another class. """
self.snake = turtle.Turtle()
self.snake.speed(0)
self.snake.color(self.settings.snake_color)
# so that path is not drawn
self.snake.penup()
# place the snake and freeze it initially
self.snake.goto(0, 100)
self.snake.direction = 'stop'
def main(self):
""" Main loop. """
while True:
self.window.update()
self._snake_move()
def _snake_move(self):
""" Move the snake. """
self.window.listen()
self.window.onkey(self.go_up(), "w")
self.window.onkey(self.go_down(), "s")
self.window.onkey(self.go_right(), "d")
self.window.onkey(self.go_left(), "a")
if self.snake.direction == "up":
y = self.snake.ycor() #y coordinate of the turtle
self.snake.sety(20)
if self.snake.direction == "down":
y = self.snake.ycor() #y coordinate of the turtle
self.snake.sety(-20)
if self.snake.direction == "right":
x = self.snake.xcor() #y coordinate of the turtle
self.snake.setx(20)
if self.snake.direction == "left":
x = self.snake.xcor() #y coordinate of the turtle
self.snake.setx(-20)
def go_up(self):
if self.snake.direction != "down":
self.snake.direction = "up"
def go_down(self):
if self.snake.direction != "up":
self.snake.direction = "down"
def go_right(self):
if self.snake.direction != "left":
self.snake.direction = "right"
def go_left(self):
if self.snake.direction != "right":
self.snake.direction = "left"
if __name__ == '__main__':
snake = Reinforced_Snake()
snake.main()