Enumerated Types

We encounter many kinds of values in games (and in whatever domain we're programming in) that are simple, but are not numbers, characters, or true/false (boolean) values. A playing card's suit, for example, has one of four values: Spades, Hearts, Clubs, or Diamonds. Its rank is one of thirteen values: Ace, 2–10, Jack, Queen, or King. In Tic Tac Toe, a square has one of three values: unmarked, X, or O. The clues in a Crossword puzzle have one of two directions, Down and Across.

It is possible to model all of these using a numeric type such as byte, short, int, or long. And we can model the values of Tic Tac Toe squares using characters. For example, we can model suit and rank like this:

int suit; // 1 = Spades, 2 = Hearts, 3 = Clubs, 4 = Diamonds
int rank; // 1 = Ace, 2-10 = 2-10, 11 = Jack, 12 = Queen, 13 = King

This will do the job, but for a variety of reasons that won't make sense now, it is not ideal. Earlier we referred to the goal of making a game-state model as clear as possible. Java's enumerated types are a big help in this. Here are suit and rank modeled as enumerated types.

enum Suit { Spades, Hearts, Clubs, Diamonds }
enum Rank { Ace, R2, R3, R4, R5, R6, R7, R8, R9, R10, Jack, Queen, King }

We might wish to name the ranks 2, 3, 4, … but that isn't possible. Each value of an enumerated type has to obey the rules of Java identifiers, which say that an identifier cannot begin with a number.

Here is how we might model the state of a Tic Tac Toe square:

enum Square { Blank, X, O }

This expresses that each square on a Tic Tac Toe board can have one of three possible values: Blank, X, or O.

A die in a pair of dice has only six values, so should we model the value of a die using an enumerated type? This one seems better to model as an int. The numeric value of the face is what matters, and that is modeled most clearly with a numeric type. For reasons that we will mention when we discuss operators, it is most convenient to use the int type, even though a die's value would fit easily into a byte.

Some prefer to use all-caps for the values of an enumerated type, writing:

enum Season { WINTER, SPRING, SUMMER, FALL }

rather than:

enum Season { Winter, Spring, Summer, Fall }

However, there is no variation in the name of the type itself: The first letter of the word(s) are capitalized, the remaining letters are lowercase. Suppose we wish to be a little more precise with the name of the type for Tic Tac Toe squares:

enum TicTacToeSquare { Blank, X, O }

Capitalizing the first letter of each word in a multi-word identifier like TicTacToeSquare is called “camel case.”