Islands

Learn how to create the Islands module.

Represent islands

Let’s move on to the islands in the game.

Islands are more complex than coordinates or guesses. They come in five different shapes: :atoll, :dot, :l_shape, :s_shape, and :square. Players can position them on the board, and their opponents try to guess their position.

Islands are made of groups of coordinates. This suggests that we can use a list to represent them.

Looking back at our list of actions, one of the things we need to do is determine whether or not an island is forested. In other words, we need to determine if all the coordinates of an island have been hit.

If we use a list to represent an island, we need to do two things:

  1. First, we need to mark coordinates as a hit.
  2. Then, whenever we need to see if the island is forested, we need to enumerate through the list.

To check for a win, we would have to enumerate through all the coordinates in all the islands. The total number of coordinates is small, so it’s not a really big deal. However, we can do better.

If we saved two lists—one for the initial list of coordinates, and another to which we add any coordinates that are hit during a guess—we can do a simple comparison of the two.

There’s a small problem with this, though. If we compare lists, the order of the elements matters.

[1, 2] == [2, 1]

Note: Running this in an IEx session displays false since the two lists are not interchangeable.

Get hands-on with 1200+ tech skills courses.