Category: Game Design

Superman (Atari 2600) alternate map Romhacks, part 4

I had one more idea for an interesting map. This time I wanted to emphasize the importance of the Bridge to the map. So I thought, I would split the map into two halves, and put the bridge between them, as the only way to get from one side of the map to the other.

This was my prototype:

The prototype was shaped like an H.

I thought that this map had interesting potential, but I also had some concerns. I wanted to make sure that the traffic flow would still work, and that by splitting the map in this way, I didn’t make it likely that random movement would tend to collect everybody in one area of the map, and I wanted the random distribution of characters to not be unevenly distributed between east and west ends of town. I also wanted to ensure that the subway system would be evenly distributed, both in terms of entrances and exits, and that the subway provided useful shortcuts.

As I walked through this map, I quickly decided that a less obvioulsy symmetric map would be more interesting. I re-arranged screens and quickly came up with this:

A masterpiece of design!

The connections between the screens are a bit different from my previous versions. Moving horizontally, the map wraps, shifting up a row if you’re at the west edge, and down if you’re at the east edge. Vertically, the columns wrap around without shifting. The Bridge screen is different, when moving vertically it wraps around back to itself. This serves to keep the Bridge screen isolated, so bridge pieces will be somewhat protected from the helicopter when placed here.

Finally, the extreme corners of the map, the northeast and southwest corner screens, are connected to each other horizontally, creating a second junction between the two halves of the map. This helps provide a route for Clark Kent to walk to the Daily Planet at the end of the game, without being forced to use the Subway system, although this overworld walking route is very long.

The subway exits are again unchanged, and the subways provide several routes for traversing from one side of the map to the other. I arranged the subway system so that each colored subway screen has two exits on the opposite side of the map, and one exit on the same side of the map.

Thus, despite the broken bridge in the center, this map has very nice traffic flow between both halves of the map, many interesting shortcuts, and a challenging layout to learn, without the confusing one-way vertical borders on the Phonebooth and Bridge screens that vexed many beginner players of the original. After playing this map a few times, I think it’s every bit as good as the original, and might even be more fun to play. And aesthetically, I love that the Bridge is now the centerpiece of the map, and truly joins the two halves of Metropolis together.

Here’s the map again, with the wrap routes indicated:

I don’t think there’s much more I can do with the map after this. So I think this is where I will leave the evolution of the map variations.

I would still like to introduce randomized bridge piece starting screens, but to figure that out will require more understanding of the source code than I currently have.

I also think it would be neat to make a super-rom that includes all of the map variations in one file, switchable via the Game Select switch. Again, this is beyond my current capabilities with my very limited understanding of the source code and 6502 asm.

You can download the entire collection of romhacks here:

Superman (Atari 2600) alternate map Romhacks, part 3

After publishing part 2 of this series, I played my grid map romhack a few times, and I think it’s rather good. I don’t know that I would say that I prefer it over the original map, but this is certainly a viable alternative map.

After a few playthroughs, I notice a few things:

  1. The helicopter moves bridge pieces away from the Bridge screen much more frequently. In the original, once you’ve placed a piece at the Bridge screen, the helicopter would only rarely remove it.
  2. The helicopter seems to move pieces from their starting screen much sooner, as well.

I like both of these differences; they make the game more challenging, and I think, more fun. You really feel like you need to race the helicopter to complete the bridge task. But I think it’s worth experimenting with the map to see if there’s a way to restore the original design intent, by reducing the number of paths into the Bridge screen. It occurs to me that an easy way to do this is to make the two screens above and below the Bridge screen connect to each other, rather than to the Bridge screen. So the Bridge will exit vertically to those screens, but reversing course will skip over the Bridge, but still place you near the Bridge; players would need to figure out that they are “around the corner” from the Bridge in this map, which is potentially disorienting, but should be less of a problem than the original map, which puts you clear across into the middle of the other end of the city.

I do think that this map has a few peculiarities that make it sub-optimal.

  1. Some of the subway entrances are right next to their exits. There’s little point in a subway trip that results in you re-emerging on the overworld map one screen over from where you started. For example, the Red subway entrance is one screen away from two of its exits, due to being on the top left corner of the grid, and the wrapping effect. The Blue and Yellow subway entrances are about optimally located relative to their exit screens, and the Green subway entrance is directly above one of its exit screens.

It’s possible to remedy this by moving the subway entrances around, or by changing their exits to more useful screens for this map layout. I was reluctant to try this, because I wanted to keep the changes that I am making to the maps minimal, but it seems that these changes are necessary for the good of the game.

Metropolis 21/7

Another thing that strikes me is that I didn’t need to remove one screen from the overworld in order to have even rows. 21 = 3 x 7, so I could have made an overworld map of 3 rows of 7 screens. This might make the subways more useful, since it would make it easier to place the subway exits such that they are 3-4 screens from their entrances.

A 7×3 grid will allow all 21 overworld screens to be included in the new map. Again, I went to an image editor and re-arranged the screens to make a layout, then visually reviewed and analyzed the map for playabiltiy concerns, and made tweaks.

My first iteration of this was to lay the screens out in the original map’s horizontal sequence, and see how that would play. That map looks like this:

First iteration

Without actually playing it, it’s easy to miss things, but I can see that this map has a few potential issues:

  1. The bridge pieces starting screens are all on the west end of the map, and are nearby the Bridge screen.
  2. The Phonebooth, Bridge, and Jail are all on the bottom row, which makes the bottom row feel too important, and the top row feel unimportant.
  3. The “critical path” relationships in the original map are broken in this map. This may not be a problem per se, but it will make the new map feel less familiar to experienced players.
Superman bridge piece routes
The original Metropolis map has a very tight spatial relationship between the most important screens on the map. The new map layout breaks this by moving the Jail screen far away from the rest of the screens.

Otherwise, I think the map looks pretty decent. I’m not sure how I feel about the potential issues I mention above.

I do think that the Bridge should be the center piece of the map, so I shifted rows and columns in order to make it so, but the rooms are still in the original order, using the horizontal progression from the original map.

It’s interesting how shifting things around can change perspectives on things. With this view, I’m able to notice different things:

  1. Now all the “important” screens (Jail, Bridge, Phonebooth, Daily Planet, and all but one of the bridge pieces) are on the west end of town.
  2. But balancing that, all the subway entrances are on the East end of town.
  3. Subway exits are somewhat evenly distributed, but there’s a few interesting things to point out: The Red subway exits all line up in a column at the far west edge of the map, while the Yellow subway exits are all distributed across the top row. The Green subway exits follow a diagonal from the northwest corner of the map, moving southeast. And the Blue subway exits are scattered about as far from each other as they could be.
  4. Shifting the screens changes the loopback point at the top right, and as a result the screen that normally is to the left of the Phonebooth screen no longer is. Which, despite what I thought when I first decided to shift the screens to put the bridge in the center of the map, does fundamentally change the map. Then I realize… I did it wrong!

I can’t just grab the top row and move it to the bottom, and then slice the right couple of columns and move it to the left. That will not preserve the horizontal order of the screens. To do that, I need to grab the top-right screen, move it to the bottom left, and then let all the other screens shift right by one, snaking around. This approach gives this result:

Overall, it’s actually very similar to the first two iterations. It’s literally the same horizontal sequence as the first iteration, but it’s not all that different from the second iteration, either; the “important” screens are still mostly to the west, the subway entrances are still mostly to the east. I think the subway exits are a bit better distributed than in iteration 2.

The vertical path is quite different. I think this map will run slower, due to the placement of the Jail in the corner of the map, and its distance from most of the subway entrances, and the Phonebooth/Bridge screens. There might yet be some quick paths that will become apparent through repeated play, but for now I feel that the map feels disorienting because the Jail isn’t north of the Yellow subway entrance screen any longer, and I struggle to locate it as a result.

Certainly there are many other possible arrangements for the overworld map, and I haven’t even begun to re-design the subway. But I think this is enough to satisfy my curiosity, at least for the time being. I may come back and revisit this further if I feel a need to after playing the maps I already created more extensively.

There’s much more to do in a hack of Superman, as well. I would like to figure out how to randomize the starting places of the bridge pieces, for example. I would also be interested in figuring out how to put up a hard barrier around the outer edge of the map, rather than having the map wrap around at the edges. But these projects, if I ever attempt them, will have to wait until I have a deeper understanding of 6502 assembly.

Download all of my Superman map romhacks here:

Superman (Atari 2600) alternate map Romhacks, part 2

For the second alternative map, I needed to carefully re-organize the screens to put them into a grid.

There are 21 overworld screens, and so I will use a 5×4 grid, omitting one of the overworld screens, since there can be only 20 screens in a 5×4 grid.

Selecting the right screen to omit is important. The removed screen must not be:

  • A subway entrance
  • A subway exit
  • The phonebooth, bridge, or jail screen
  • A bridge piece start screen

One of my goals with this redesign is to keep the layout of the screens reasonably familiar to players of the original game. This is a formidable task, and technically impossible since I am changing the layout, but my goal is to make the changes minimal, and to preserve as much of the critical paths through the map as possible.

But just as important, I want the redesigned map to be balanced and fun to play.

To achieve this, I want the subway entrances and exits to be distributed about the map, and not clustered together too much.

There are 11 unique subway exits, and 5 subway entrances (counting the Daily Planet), so 16 of these screens have something to do with the subway system, and another three are the Jail, the Daily Planet, the Phonebooth, and the Bridge screen. (Both the Daily Planet and the Jail are also subway exit screens, so are already counted among the 16 overworld screens that are related to the subway system, but adding the Phonebooth and Bridge brings the total of “must keep” screens to 18, leaving just 3 redundant screens for possible removal.) I didn’t realize how tight the map design is until I noticed this.

After considering the matter for a bit, I decided that this screen would be the one to go:

But I just as well I could have picked this one:

Or this one:


I mean, they’re all kindof the same, aren’t they?

I note that the three “dispensable” screens all have a similar color scheme to them, green and white, and wonder if there’s something being communicated through a visual language here, or if it’s just a coincidence… there are two other green/light grey screens, the Yellow Subway entrance, and the screen above the Jail, which is one of the bridge piece starting rooms. So… probably just a coincidence, then.

At the edges of the overworld grid, the map will wrap around to the next row or column. As an experiment, I think I’ll also create a variation where the map will wrap around to the same row or column, but I think this variation will only be playable on Easy difficulty — because, when Superman is struck by kryptonite, he will be stuck in the current row of the overworld map, and if Lois Lane isn’t present on that row, he’ll be unable to get revived until she wanders in, or the helicopter brings her, which could take ages, and would be unfair.

I take a picture of the overworld, cut out each room, and put it into an image editor and move them around until I have them arranged in a 4×5 grid that I think will be satisfactory. I end up needing to move things around a good bit to achieve this, but I think I managed to do it while still preserving some of the critical relationships between certain rooms.

Here’s what I ended up with:

Grid map for the Superman romhack
I think this might be OK. And might make a cool quilting project, too!

Here’s the original map for comparison:

So you can see, there’s a bit of re-shuffling that I had to do in order to balance the map out, and many of the vertical and horizontal connections are different in the new map.

The major changes are:

  1. The one-way vertical boundaries for the Phone Booth and Bridge screens are two-way.
  2. One screen is removed from the overworld, to allow for an even grid.
  3. The Phonebooth and Bridge screens are in the center of the map. (Although, since the edges of the map still wrap, center/edge is all relative.)

The important non-changes are:

  1. The subway system exits are all to the same screens as before. (But, due to the shuffling of these screens relative to one another on the overworld, this does still mean there’s some significant differences. The key exits to get to the Daily Planet and Jail screens are the same as in the original, though. And several of the subway exits now get you close to the Bridge screen.)
  2. The bridge pieces are still found on the same screens as they were in the original. I didn’t try to re-locate them. (Sometime, I’d like to introduce randomization into their starting positions, and see how that plays.)

Now that I had the design determined, I had to hack the rom to make the changes for real. To do this, I went through the original code and noted the names of each screen, and figured out from the boundary change code the correct addresses for each room, and mapped them together. This was straightforward, if a bit tedious, but fortunately the map is small.

One thing I noticed as I coded the new map connections was that there’s a peculiarity at the top-right and bottom-left corners of the map, due to the way the rows and columns wrap; if you’re in the top-right screen, going up or right will both take you to the bottom-left screen; and if you’re in the bottom-left screen, going down or left will take you to the top-right screen. This doesn’t make sense, unless you understand the way the overworld wraps. If you get to the end of a row or column, continuing in that direction wraps you around to the next row or column, and at the very end of all the rows and columns, it wraps you around to the opposite corner, and so the top-right and bottom-left screens are connected to each other in two directions.

I have only played through this map once, and mostly just to test that everything was connected properly. I think it’s a viable, and interesting variation, but I wouldn’t call it better than the original. Certainly, due to the re-positioning of the screens, the quick path to the bridge pieces isn’t as short as in the original map, which means speed running potential for this map is reduced. Beyond that, the Phonebooth and Bridge screens are not low-traffic screens any more, meaning that you’ll often find gangsters on these screens, and the helicopter may find bridge pieces that you’ve left at the Bridge site more readily, which will again make it more challenging as the helicopter removes them again.

You can download the entire collection of romhacks here:

Superman (Atari 2600) alternate map Romhacks

So for the first alternative map, I will just make the Up screen the same as the Right screen, and the Down screen the same as the Left screen. This means that there will only be the Horizontal progression through the map, and that Up/Right will be “forward” and Down/Left will be “backward” through this progression.

You can download the modded rom below:

I playtested this, and found that it works exactly as intended. The map is far simpler to navigate, and getting lost is now virtually impossible. Fly up/right to go forward, down/left to go backward, and all overworld screens appear in order. The confusing one-way vertical borders on the Phonebooth and Bridge screens are eliminated.

The downside of this is that traversing the overworld map is slower, since there are no shortcuts to be gained by using cornering techniques. You still can rapidly advance two screens in the horizontal map sequence by going diagonal from near the corner, transitioning on both the vertical and horizontal edge transitions. But compared to the original, where a vertical transition would typically advance you between three and five screens in the horizontal sequence, it’s much slower, and offers no real opportunities for useful shortcuts.

The only real shortcuts possible are via the subway system, which I left unmodified. Despite playing this game over nearly four decades, I’ve never bothered to memorize the subway in its entirety — there’s little reason to. The only exits of real importance are the ones that go to the Jail and Daily Planet. But with this map, knowing the rest of the exits is potentially more valuable, because it can get you to the other side of the overworld in less time than any other method. It may be interesting to study the exits and try to figure out alternate layouts that might make the map more interesting by providing additional useful shortcuts.

I can reliably win Superman typically in 1:30, +/- 15 seconds, but this variant took me 3:04 to win on my first play. I’m sure faster times are possible. The gangsters seemed to be bunched up more, and rounding them up preoccupied me at first, leading to the helicopter moving bridge pieces away, which I think happened earlier than normal. But because the map is essentially a two-dimensional line, finding the helicopter was trivial, making any challenge increase by the bridge pieces moving around quite minimal.

My impression is that this alternative map might have made the game more playable for very young players, ages 3-5, and as an “easy” version for beginning players, much like Superman‘s sibling Adventure offered players Game 1 with a simplified map. But overall, the simpler map makes the game less interesting and less challenging to play. But if you’re interested in the game’s design, playing this variant to see why it’s less interesting is… well, an interesting exercise. I invite you to download it and play it for yourself and make up your own mind. If you do, please drop a comment and let me know what you think.

My next Superman romhack will present the overworld map as a grid.

Pixel Art Chess Set: Communicating function through design

My five year old nephew started learning to play Chess recently, as I discovered on a visit a few weeks ago.  We played two games, and I didn’t have too much trouble beating him, but for a five year old he’s not bad. He knows all the pieces and their basic moves and their relative value.

I thought it would be fun to build a video Chess game that he could use to help learn strategy and how to see the board. So this is my latest project. I’ll be posting more about that as I work on it.

My first step was to design graphic resources. I didn’t want to spend too much time on it, just a basic “programmer art” chess set, that I could use to build the program with. Of course, it didn’t end up that way, and I’ve gone down the rabbit hole designing variations on sets of minimalist pixel art chess men. It’s too fun and fascinating not to.

My first attempt was actually rather good, I thought. I went for 16x16px representations of the classic chess pieces. I drew them very quickly, but was very pleased with my results, particularly the Knight.

I could have stopped right there, but it was so fun to make this set that I wanted to continue exploring and see if I could refine my pixeling technique further.

I decided to search the net for images of chess pieces to see what variety there was, and found a lot of examples of beautiful sets. I started to take notes and to infer design rules for chess men:

  1. Chess pieces are called “chess men” which seems antiquated and sexist, especially given that the most powerful piece in the game is the Queen.
  2. The modern standard chessmen are a design named for English chess master Howard Staunton, and have been in use only since the mid-19th century. A strength of its design is that each piece is easily distinguished from the others, making errors from mistakes in identifying a piece — a problem with other sets — unlikely. Previously, chess men of different types had a less distinct appearance from one another, and were not as standardized.
  3. In a Staunton set, the Knights are the most detailed, ornate, varied, and realistically represented pieces. 
  4. In Staunton sets, there is a standard height order: pawn, rook, knight, bishop, queen, king. (This surprised me, since Rooks are more valued in Chess I would have expected them to be taller than Bishops.)
  5. The pieces are differentiated by their tops. Each type of piece has a distinct, unambiguous shape.
  6. The body/base of the pieces have a common design, to create unity among the pieces in the set.

I tried to apply design choices to my chess set following these insights.

A follower on Twitter offered feedback that the pieces should be different heights, so I tried that. With a 16×16 pixel tile size, I could only shorten the back row pieces by 1-3 pixels.  I also tweaked the King piece by adding a few more pixels to its top, to make it a bit more distinct from the Queen, and moved the Pawn so that it wold be more centered in its square.

I do like the result:

Staunton pixel chessmen

I think my initial 16×16 Staunton set look like they’re in ALL CAPS, while this set is more “readable” by using “mixed case” heights for the pieces.

I wanted my chess game to be focused on usability and instruction. I needed each piece to be immediately recognizable, and not to convey a bunch of extraneous information to the player that has nothing to do with play mechanics. 

My next attempt was a different take altogether. I wanted the look of each piece to suggest its rules for movement. I also thought that it would be clever if the pieces communicated the rules for using them through their visual design.

I ended up being very pleased with this set as well, although I went through many more variations, particularly with the Pawn. This one also came together easily and rapidly.  When your tile size is 16×16 and you’re working in just a few colors, it’s easy to work fast.

Things I like about this set:

  1. The shape of the piece is a built-in tutorial for how the piece moves.
  2. The Pawns still have a pawn-like shape (at least the black pawns; white pawns are “upside down”).
  3. The Knight’s shape may be read as an abstraction of the horse’s head shape of the Staunton piece.

I think out of these variations, my favorites are: P9, Kn2, B3, R1, K?  I’m least certain which King I like.  I think K4 and K5 are my top two, but I also liked the idea of incorporating a crown motif into the design, to signify the King’s special property of being the King.  K1, K2 and K6 were attempts at this, but I think K1 looks too much like a Staunton Rook, unfortunately.

I wasn’t sure which of my designs to use for my final set, so  I posted my sets on Twitter and a pixel art community on Facebook. @Managore responded to my request for feedback by coming up with a set of his own design, which I quite like.

His design was retweeted and liked over 500 times, and received many positive compliments from his followers, many of whom are game developers. One of my favorite indie developers, @TerryCavanaugh, who made VVVVVV and Don’t Look Back, pointed out an physical chess set that had been designed a few years ago which incorporated the same ideas.

It’s exciting to see my idea get picked up and reworked by fellow game developers who are inspired by the concepts I am exploring. So fun! Getting that validation that what I’m working on is interesting to others is very motivating. But it’s particularly good to get some attention from developers whose work I’ve admired for years, however modest.

I’m excited about this project and look forward to working on the program. I have more design ideas that I’m looking forward to getting into soon.

Fun enum ideas for game development

Most video games have a counting, ranking, or level system of some sort. It’s often good to have a thematic flavor to your counting systems. This way, rather than calling your level progression by boring old regular numbers, you can give each level number a meaningful, or flavorful, name. This can add character or meaning to your game world, or it can be used to help disguise the underlying math, resulting in a game where the underlying mechanics are masked away from the player, leading to a more mysterious experience where they need to experiment and discover. What’s cooler: a “level 3 sword?” Or “the sword of autumn?” What’s more powerful: the knight sword or the rook sword?

To that end, I thought I’d demonstrate a few example enums that you can use to spice up your game design.

ENUMerate all the things!

Alphabet {A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z}

Greek Alphabet {Alpha, Beta, Gamma, Delta, Epsilon, Zeta, Eta, Theta, Iota, Kappa, Iota, Kappa, Lambda, Mu, Nu, Xi, Omicron, Pi, Rho, Sigma, Tau, Upsilon, Phi, Chi, Psi, Omega}

Military Phonetic Alphabet {Alpha, Beta, Charlie, Delta, Echo, Foxtrot, Golf, Hotel, India, Juliett, Kilo, Lima, Mike, November, Oscar, Papa, Quebec, Romeo, Sierra, Tango, Uniform, Victor, Whiskey, Xray, Yankee, Zulu}

Army (simplified) {Private, Specialist, Corporal, Sergeant, Officer, Lieutenant, Captain, Major, Colonel, General}

Navy (simplified) {Seaman, Petty Officer, Ensign, Lieutenant, Commander, Captain, Admiral}

Chess {Pawn, Knight, Bishop, Rook, Queen, King}

Rainbow {Red, Orange, Yellow, Green, Blue, Indigo, Violet}

Elements {Earth, Air, Fire, Water}

CardRank {Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace, Joker}

CardSuit {Clubs, Diamonds, Hearts, Spades}

Zodiac {Aquarius, Pisces, Aries, Taurus, Gemini, Cancer, Leo, Virgo, Libra, Scorpio, Sagittarius, Capricorn}

Seasons {Spring, Summer, Autumn, Winter}

Months {January, February, March, April, May, June, July, August, September, October, November, December}

Weekdays {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}

Lunar Cycle {New, WaxingCrescent, FirstQuarter, WaxingGibbous, Full, WaningGibbous, ThirdQuarter, WaningCresent}

Some of these may not necessarily have a natural order to them, but might just be a set of categories which you could use to organize something in your game. That something could be worlds, or items, or creature types, or powers, or anything else you can think of.

What else?

What else is there? Probably a whole lot! You could probably make a good basis for a game system out of gemstones, or metals, or barnyard animals, or anything, really!

If you know of a set of things that would make a good enum that I’ve left out, leave a comment below.

Using enums in GameMaker Studio

Enums are covered in the manual in the article on Data Types.

The basic syntax is as follows:

First, you have to declare the enum.

enum <variable>{<constant> [= <value>]}

You create the enum using the enum keyword, naming the enum <variable>. Then, in brackets, you list all the constants that make up the values in the enum. You can explicitly declare values for the enum constants, or you can leave them implied, in which case GameMaker will assign them integer values starting at 0, and increasing in order through the collection. You can even use expressions rather than a static value.

To access the enum constants, you use the syntax enum_variable.constant.

In your code, there are all kinds of situations where using an enum is potentially useful. Here’s a few things to look for in your code that might signal a good opportunity to use an enum:

Conditionals for checking state

Consider the following ways of checking the state of some object:

//check state using string matching
if state == "state_idle" {//do state actions}
//check state using literal numbers
if state == 0 {//do idle actions}
//check state using variable
state_idle = 0;
[...]
if state == state_idle {//do state0 actions}
//check state using enums
if state == enum.value {//do state actions}

Out of these, using enums is the best approach. Why are enums better?

Conditional checking by string matching is much slower than number matching. Your string value provides semantic meaning to the reader, making the code easier to understand when a human reads it. But when the program goes to check the conditional, it has to check every letter in both strings to see if they match.

As well, this approach is fairly error prone. It’s very easy to type the strings in slightly wrong. If you’re not careful, it’s easy to type one string where the state is assigned, and another string value where you’re checking state in order to do something state-specific. If you don’t catch the error, you’ll have a hard to diagnose bug because the conditional check won’t match what you’ve set the state variable to. One extra space, or misspelled word, or inconsistent use of capital letters, and the string match check will fail. The compiler won’t help you catch this sort of bug.

It’s a lot faster to do conditional checking via numbers. But naming your states with literal numbers: 0, 1, 2, etc. provides no meaning. Is 0 the idle state? is 1 running? is 2 jumping? Keeping track of this stuff in your head makes your work as a programmer harder, and makes the code hard to read, and brittle. You can do slightly better by creating a named variable and assigning the number value to it. The named variable can be expressive, e.g. state_idle = 0, state_running = 1, etc. But variables values can change, and storing each value takes a little bit of memory. By contrast, an enum value is constant — it cannot be changed once it is declared. And enums are global, so they are only declared and set in memory once, and thus require fewer resources. Even if you have ten thousand instances that use your enum, the memory used by them is the same as if there is only once instance.

Create an enum that provides expressive labels on these values, and you have the best of both worlds: expressive code that checks conditions fast, and uses computer resources efficiently.

Iteration over a set

Conventionally, programmers often rely on conventional looping variable names such as i or j to iterate over a collection of things, such as the members of an array, or other data structure. While this is OK, you can make your code more expressive by using enums to denote important numbers.

For example, it’s common for programmers to use a nested for loop iterating over the variables i and j to create a grid structure. Instead of using i and j, we can use variables named row and column instead. As we iterate over the range of rows and columns, we can use enums as flags to do something special at row (or column) == enum.constant.

Another example:

Say we want to implement an inventory equipping system for the player. The character has inventory slots for head, body, gloves, right hand, left hand, shoes. We decide to create an array, called inventory[], and assign the equipped item in each slot.

We could simply index the array with numbers:

inventory[0] = hat;
inventory[1] = armored_breastplate;
inventory[2] = iron_gauntlets;
inventory[3] = sword;
inventory[4] = empty;
inventory[5] = double_jump_boots;

Now, it’s not too hard to tell what each inventory slot is for. But it’s not as easy as it could be, either. Is the sword in the left hand or the right hand?

Let’s use an enum, and make the code easier understand.

enum inv_slots{head, body, gloves, right_hand, left_hand, shoes};
 
inventory[inv_slots.head] = hat;
inventory[inv_slots.body] = armored_breastplate;
inventory[inv_slots.gloves] = iron_gauntlets;
inventory[inv_slots.right_hand] = sword;
inventory[inv_slots.left_hand] = empty;
inventory[inv_slots.shoes] = double_jump_boots;

Now, it’s quite easy to see that the double_jump_boots are being worn on the player’s feet, rather than being carried in the player’s hands. It’s simple to keep track of which slot is which.

Creating a set of related, named values

Here’s a useful enum for direction angles for a top-down game:

enum compass {e = 0, ne = 45, n = 90, nw = 135, w = 180, sw = 225, s = 270, se = 315};

It’s much easier to remember and understand direction = compass.sw instead of direction = 225. You can use this enum for 4-direction and 8-direction movement or aiming, and you could even expand upon it if you wanted by adding constants for ene, nne, nnw, wnw, wsw, ssw, sse, and ese, like so:

enum compass {
 e = 0, 
 ene = 22.5, 
 ne = 45, 
 nne = 67.5, 
 n = 90, 
 nnw = 112.5
 nw = 135, 
 wnw = 157.5
 w = 180, 
 wsw = 202.5
 sw = 225, 
 ssw = 252.5
 s = 270, 
 sse = 292.5
 se = 315,
 ese = 337.5
 };

(I like to format my code like this; lining up the variable names, equals signs, and values makes it easy to scan down the file, and makes it clear that these values are all related.)

If I wanted, I could go a step further and use radians to make it clearer that these values are fractions of a circle:

enum compass {
 e = 0, 
 ene = radtodeg(pi * 0.125), 
 ne = radtodeg(pi * 0.25),
 nne = radtodeg(pi * 0.375), 
 n = radtodeg(pi * 0.5), 
 nnw = radtodeg(pi * 0.625),
 nw = radtodeg(pi * 0.75),
 wnw = radtodeg(pi * 0.875),
 w = radtodeg(pi), 
 wsw = radtodeg(pi * 1.125),
 sw = radtodeg(pi * 1.25),
 ssw = radtodeg(pi * 1.375),
 s = radtodeg(pi * 1.5),
 sse = radtodeg(pi * 1.625,
 se = radtodeg(pi * 1.75),
 ese = radtodeg(pi * 1.875)
 };

You can group together, and name other values that go together in a system using enums in this way, too.

Parting thoughts

Hopefully, these examples will help you see how enums can be useful to make your code more expressive, easier to read, and easier to maintain. Look for opportunities to use them in your code. They can really help!