Creating an if statement with a indexerror - Python

14,253

Use exception handling :

 try :
     #your code
 except IndexError:
    print "Game Over"
Share:
14,253
Nekroz
Author by

Nekroz

Finally decided to try to learn some programming and really want to thank all nice and patient people out there that have helped me on my journey!

Updated on June 05, 2022

Comments

  • Nekroz
    Nekroz almost 2 years

    I'm trying to create a game similar to snake. The difference is that a food ration is recieved by using randint and the player will then be able to choose in which direction the snake should grow, the starting position is also randomly chosen. The game field is built with a matrix and therefore it's possible to grow "into the walls" by chosing a growth direction that makes the list go out of range.

    My question is if it's possible to create an if statemant that would end the game with a "game over" if the player chose to grow in a way that makes the list go out of range, something like:

    if IndexError: list index out of range : 
             print("Game over")
    

    With the exception handling my code would look something like this:

     try :
    
        if p == 0:
            table[x][y] = "+"
        elif p == 1:
            table[x][y] = "+"
            table[x][y+1] = "+"
        elif p == 2:
            table[x][y] = "+"
            table[x][y+1] = "+"
            table[x][y+2] = "+"
        else:
            table[x][y] = "+"
            table[x][y+1] = "+"
            table[x][y+2] = "+"
            table[x][y+3] = "+"
     except IndexError :
                     print ("Game Over")
    

    But I'm getting the error "unindent does not match any outher indentation level"