Very well done! Now, let's say we want to introduce a new element to our board: a hero, denoted by the letter 'H'
. Here is the new board:
game_board = [
['-', '-', 'x', '-', '-'],
['-', 'H', '-', '-', '-'],
['x', '-', '-', '-', '-'],
['-', '-', '-', 'x', '-']
]
We want to write a function that will move the hero one field to the right – unless the field to the right contains an obstacle or is outside the board. Look at the code below:
def hero_move_right(board):
for i in range(len(board)):
for j in range(len(board[i]) - 1):
if board[i][j] == 'H' and board[i][j + 1] != 'x':
board[i][j] = '-'
board[i][j + 1] = 'H'
return board
return board
Inside our function, we iterate over the nested list until we find the field with our hero. Note three things:
- In the inner loop, we iterate in the
range(len(board[i]) - 1)
. The "minus one" part means that we don't want to look for the hero in the rightmost column – in that case, we couldn't move the hero anyway.
- The field to the right of the hero is
board[i][j + 1]
. We first check if the field is not occupied by an obstacle and only then return the updated board.
- If we can't find the hero (for instance, when it's in the rightmost column), we simply return the board "as it is."