Reputation: 109
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"
Upvotes: 3
Views: 19916
Reputation: 251001
Use exception handling :
try :
#your code
except IndexError:
print "Game Over"
Upvotes: 10