Search code examples
pythonwindowsif-statementsyntax-errorcomputer-science

What is wrong with my elif statement: invalid syntax?


class Snake(object):

    def __init__(self, size):

        self.size = size

        self.board = []

        self.snake = []

        self.food = []

        self.score = 0

   def move(self, direction):

if direction in "UP, DOWN, LEFT, RIGHT":

    self.board[self.snake[0]][self.snake[1]] = direction

    self.snake = self.snake[1:] + [self.snake[0]]



def eat(self, food):

if food == "right":

    self.score += 1

elif food == "left":

    self.score -= 1



def checkCollision(self, other):

if self.snake[0] == other.snake[0] and self.snake[1] == other.snake[1]:

    print("Oops, you hit yourself!")

elif self.snake[0] == other.snake[1] and other.snake[0] == self.snake[1]:

    print("Oops, you hit the wall!")

else:

    print("Collision")





if __name__ == "__main__":

    snake = Snake(5)

    print("You are playing as: " + snake.name)

while snake.score >= 0:

    print("You have " + snake.score + " points left.")

    print("moving snake")

    snake.move("left")

    print("Current board:")

    print(snake.board)

    print("Eating food")

    snake.eat("left")

    print("Current board:")

    print(snake.board)

The Problem is with line 37 elif food == "left":

I'm getting a syntax error: invalid syntax and I am not sure how to go about fixing this specific error. I am new to programming in python and this should probably be obvious to someone more experienced I am hoping. For me I can't seem to figure it out.


Solution

  • Python relies on indentation for its blocks. Multiple of your lines aren't indented properly.

    if food == "right":
        self.score += 1
    elif food == "left":
        self.score -= 1
    

    Make sure to indent your code. There are other parts of the code that aren't indented properly such as checkCollision and your if __name__ == "__main__"