Learn how to define the opponent board.

The opponent’s board

With the coordinates represented, let’s move on to the less complex of the two boards—the opponent’s board.

The opponent’s board is nothing but a group of guessed coordinates separated into those that hit an island and those that missed. There will be a large number of unguessed coordinates as well. However, if we identify all the guesses, we can assume the rest are plain “ocean” coordinates.

This sounds like two lists—one for hits and the other for misses. We could wrap these lists in a struct with :hits and :misses keys, just as we did for coordinates.

There’s something else to consider here, though. We can’t necessarily guarantee that we’ll receive any specific guess only once. Having unique lists of guessed coordinates would make it more efficient to re-create the opponent’s board from scratch.

We could write our own functions to ensure uniqueness, but there’s an easier way. We can use Elixir’s MapSet data structure to guarantee that each member of the MapSet will be unique.

Creating the guesses.ex file

Let’s create a new module for guesses at lib/islands_engine/guesses.ex, as we did with coordinates. Following the pattern we set in the Coordinate module, we alias the Guesses module to reduce typing, enforce the :hits and :misses keys, and define the struct:

@enforce_keys [:hits, :misses]
defstruct [:hits, :misses]

Get hands-on with 1200+ tech skills courses.