Model Coordinates

Learn how to model coordinates.

Basic units

Now that we have some information to work with, let’s start modeling the most common entity—coordinates. Coordinates are ubiquitous in the game. They are the basic units of both players’ boards and of the islands.

We can identify individual coordinates by the combination of numbers for the row and the column. Passing around the separate row and column values to represent a coordinate, though, is a little messy. It also doesn’t capture the idea that those numbers represent a single entity. It would be better to combine them into a single data structure we can pass around.

We have choices about how we could represent that. We might choose to use a tuple like this: {1, 1}. However, we should be careful about tuples if we’re ever going to encode our data as JSON, since it doesn’t have a tuple type.

We might also choose a map, like this: %{row: 1, col: 1}. It encapsulates both numbers into a single entity and is easy to pattern match against.

A third option is to use a struct. We’ll pass coordinates around to create islands for players to guess. Structs maintain all the qualities of maps, but they offer compile-time checks on the keys, and allow us run-time checks on the struct’s type.

We’ll use coordinates and pass them around quite a bit. The extra checks make structs seem like the way to go.

Discussing the code for coordinate.ex

The first thing we need is a Coordinate module that aliases itself. Let’s create that at lib/islands_engine/coordinate.ex. Initially coordinate.ex will look like the following. We’ll add the code step by step:

Get hands-on with 1200+ tech skills courses.