Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction to nested lists
Iterating over nested lists
Modifying nested lists
12. Nested lists as game board representations – Part 2
Working with multiple lists


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:

  1. 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.
  2. 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.
  3. If we can't find the hero (for instance, when it's in the rightmost column), we simply return the board "as it is."


Implement another version of the hero_move_right(board) function. This time, when the hero stands in the rightmost column and wants to move right, put him in the leftmost column of the same row.


Stuck? Here's a hint!

Check if j + 1 equals len(board[i]). If it does, you need to put the hero in the leftmost column.