## GameMaker Tutorial: Password systems 2: encoding/decoding

As we established in the first article in this series, a game save password stores game state data. In this article, we’re going to talk about the low level details of how this is done. We won’t be talking much about the password itself, or the game state data. We’ll be focusing instead rather narrowly on how to encode and decode the data.

## Numeric data

As far as numeric data is concerned, we’re only going to worry about encoding/decoding integers, for simplicity’s sake. For the most part, we’ll be concerned with positive integers, but we’ll cover negative values as well.

Actually, treating numeric GML data values as integers is a little bit tricky, since in GameMaker the only data types available are strings and reals (floating point numbers). For the most part you can treat a number as though it were an integer in GameMaker, as long as you don’t do math on the number that causes the digits after the decimal point to become non-zero values.

If you want decimal values, you can store the value as an integer, and then divide it by 10, or 100, or however many decimal places as you need after you decode it. Or, if you want to store a fraction, you can store the numerator and denominator as integers, and divide them after decoding them.

As long as you don’t deal in fractions and decimals, you can pretend that your numbers are integers, and GameMaker for the most part will act as though they are. This will come up later when we hit the limit for the largest integer value that we can encode using our method (16,777,215). I’ll explain why below, but for now it’s enough to know this should be a large enough value that we don’t really need to worry about trying to encode larger values, at least for most games.

The basic idea is that each character in your password alphabet stands for an integer value. Notice that the complete alphabet (26 upper case + 26 lower case) + the 10 numerals + 2 special characters gives you a range of 64 values; 2^6 = 64, so each character in a password can represent a 6-bit binary value.

 A B C D E F G H 0 1 2 3 4 5 6 7 I J K L M N O P 8 9 10 11 12 13 14 15 Q R S T U V W X 16 17 18 19 20 21 22 23 Y Z a b c d e f 24 25 26 27 28 29 30 31 g h i j k l m n 32 33 34 35 36 37 38 39 o p q r s t u v 40 41 42 43 44 45 46 47 w x y z 0 1 2 3 48 49 50 51 52 53 54 55 4 5 6 7 8 9 ! ? 56 57 58 59 60 61 62 63

## Beyond 63

What can you do if you want to store a value larger than 63? Simple, you just use a second digit in your base-64 number. Just like the next number after 9 is 10, in base-64 the next number after ? is BA. Until you’ve looked at base-64 numbers for a long time, it’s going to be very difficult to recognize the value represented by a base-64 number, but we don’t need to — we’ll tell the computer to do it for us with some gml scripts.

We said before that a 4-digit base-64 number stores 24 bits, or up to 16,777,215 in base-10. But for some numbers that might be overkill. If we wanted to, we could treat each digit as a single base-64 value, and add them together. For a 4-character base-64 string, this would give us a range of 0-252, nearly a byte. It’s a much less compact way of storing the data, but for small values it’s not too bad.

To do the conversion from base-10 to base-64 and back, we’ll need some gml scripts.

### b64_to_dec(b64)

```/*
Takes a string of a b64-encoded value and converts it to a real number
*/
var b64_alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!?";
var value = 0;
var digit = 0;
var neg = 1;

if string_copy(argument0,1,1) == "-"{
argument0 = string_copy(argument0,2,string_length(argument0)-1);
neg = -1;
}

for (var i = string_length(argument0); i >= 1; i--){
value += (string_pos(string_copy(argument0,i,1), b64_alphabet)-1) * power(64,digit);
digit++;
}

return neg * value;```
```/*
Takes a real number and converts it to a base-64 encoded string. Supports integer values from 0-16777215.
*/

var b64_alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!?";
var value = abs(argument0);
var r;
var str = "";
var done = false;

while !done{
r = value mod 64;
str = string_char_at(b64_alphabet, r+1) + str;
value = (value - r) div 64;
if (value == 0){done = true;}
}

if (argument0 < 0){
str = "-" + str;
}

return str;```

Lastly, it will be handy to have a function that can pad a B64 encoded string to a specific length:

```/*
If the number is negative, the first character in the padded string will be a "-". If the padded_length is
less than the length of the b64 value, the function returns -1 to signify an error.

(Note the error code returned is a real number, -1, not to be confused with the correct output of
b64_padded(-1,2), which would return the *string* "-1")
*/

//argument0 the b64 string to pad to length
//argument1 the length to pad to

b64 = argument0;
len = argument1;

if len < string_length(b64){return -1;} //too short, return error
if len == string_length(b64){return b64;} //just right; we're already done

var str = "";
if string_copy(b64,1,1) == "-"{
str = "-";
len--;
b64 = string_copy(b64,2,string_length(b64)-1);
}
repeat (len - string_length(b64)){str+="A";}
str+=b64;

return str;```

## Negative Numbers

The scripts above handle negative values just fine. But the minus sign is not part of the base-64 alphabet. If we need to store negative numbers, we have a few choices.

We can expand our password alphabet to include a minus sign (or an arbitrary symbol that we can use as a substitute).

Or we can designate certain characters in the password to store a boolean which signifies whether a given numeric value stored elsewhere in the password is positive or negative. Then encode the absolute value of the number, and re-combine it later with the boolean that holds the sign.

Or we can sacrifice a bit in our base-64 encoded numbers and treat them as signed integers, such that A-g represent values 0 through 32, and h-? represent negative values -1 through -31.

## Beyond 16,777,215?

The encoding/decoding scripts work for values up to 16,777,215, or ???? in b64. This value is (2^24)-1. Beyond that, the numbers do not encode/decode properly. The reason for this has to do with the way GameMaker stores numeric values. All numbers in GameMaker are floating point values. GameMaker uses a 32-bit floating point, of which 24 of those bits are used for the digits to the left of the decimal point. The remaining 8 digits are used for the fractional value to the right of the decimal point. This means that for a number above 16777215, we can’t store the value in a 32-bit floating point variable without losing some precision. This precision prevents us from cleanly encoding a value above 16777215 and decoding it back to the same value. Fortunately, such high values should be rare to encounter in the game state data.

What happens if you try to store a larger value depends on the build target. Some may lose precision, resulting in off-by-one conversions — data corruption. Others may fail to return a value entirely when the conversion script is called, which would result in total loss of the data. Certain build targets (I’m not certain which ones) may use 64-bit floating point values, rather than 32-bit. In this case, we can go even higher, up to (2^52)-1. This is a ridiculously large number, and it’s almost certainly more than enough for any game state value you might want to encode.

### Tip for validation

If the password space allows a value larger than the max value for a given game state variable, you can use those larger values as a form of validation check. For example, let’s say that the maximum number of lives in your game is 255. This requires an 8-bit value, but since each character represents 6 bits, and we don’t want to bother splitting characters, we use 2 password characters, which represents 12 bits of data. We can use these additional value space between 256 and 4096 for a validation check.

The simplest method would be to reject any password that contains data in the lives bits that decodes to a value greater than 255. Another way to handle this is to use a math value to obfuscate the lives value. Since 4096/256 = 16, we can take the value of the two characters that we use to encode the lives count as follows: lives x 16 = password substring. Now, when you’re validating the password, you can mod the value of the characters that represent the lives by 16, and if the calculation doesn’t work out to 0, then you know the password isn’t valid.

Or you can make the “right” remainder be dependent upon some other part of the password — for example, when the Level is even, the lives substring should mod16 to 0, but when Level is odd, it should mod16 to 1, unless Level is divisible by 3, in which case… Sneaky/unnecessary complexity like this will make the password harder to understand, and therefore require more effort to crack the password system. Don’t fool yourself into thinking you’re coming up with a super secure uncrackable password, but it will make the password a little less obvious than a simple counter, and for password system crackers, will make the puzzle more fun.

## String data

Old NES password games did not typically have any string variables to preserve in a save password. In fact, the few games where you could enter a name were all, to the best of my knowledge, battery backup games that used savefiles.

It’s simple enough to store a string in a password, though, since a password is a string. The only real issue is dealing with variable length strings. For a lot of reasons, it’s probably best to stick with a fixed length for strings and pad shorter strings with spaces, trimming them later when applying the password to game state.

However, it looks weird if your password has string values stored as plain text in the password — it’s an obvious indicator to the player that the password is storing data, which could invite mischief. So it’s probably a good idea to encode the data somehow.

We could encode strings by using the numeric ASCII values of the letters, and then convert them back, character by character. While not encrypting the data, it would be sufficiently obfuscated for our purposes.

I won’t bother implementing this for now, since our demo password only has 4 characters, and in any case it’s not really necessary, but it’s good to have an idea of how we might do it if we decide to later on.

## Boolean data

GameMaker doesn’t have a true boolean data type. The boolean constants `true` and `false` are equal to 1 and 0 in GML. Boolean expressions in GameMaker are handled by evaluating to a real number, and any number <0.5 evaluates as false, and 0.5 or greater evaluates as true. Therefore, to encode a boolean, all we really need to do is encode a value of 0 or 1. Or any other value that will evaluate to true or false.

But, since a single base-64 character can store up to 6 bits of data, and each bit can store a 0 or a 1, a single character could in theory store up to 6 boolean values, which means a 6x greater density than if we just stored one boolean value in each character.

To achieve this, we need to convert a base-64 value to a binary value, and vice versa. Then we would need to break the binary value into its individual bits, and designate each bit for a specific boolean value.

Note that the next few functions do not really deal with binary values, but rather with strings storing 0 and 1 characters, which we can convert to boolean values by using the real() function.

Edit: I’ve updated these functions with more elegant implementations, and replaced the brute force switch statement lookup table approach that I had here originally. Thanks to Ian Schreiber for the suggestion.

### bin_to_dec(bin)

```/*
Takes a string of a binary encoded value and converts it to a real value.
*/
var bin_alphabet = "01";
var value = 0;
var digit = 0;

for (var i = string_length(argument0); i >= 1; i--){
value += ((string_pos(string_copy(argument0,i,1), bin_alphabet)-1) * power(2,digit));
digit++;
}

return value;```

### dec_to_bin(dec)

```/*
Takes a base-10 value and encodes it as a binary string
*/
var bin_alphabet = "01";
var r;
var str = "";
var done = false;
neg = sign(argument0);
value = abs(argument0);

while !done{
r = value mod 2;
str = string_char_at(bin_alphabet, r+1) + str;
value = (value - r) div 2;
if (value == 0){done = true;}
}

if (neg < 0) {str = "-1" + str;}

return str;```

### bin_to_b64(bin)

```/*
Takes a 6-digit binary encoded string and converts it to a b64-encoded character.
*/

return dec_to_b64(bin_to_dec(argument0));```

### bin_to_bool(bin)

```/*
Extracts the argment1-th bit out of the binary string supplied in argument0 and returns it, converted
to a real number. The real value can be interpreted as a boolean (0=false; 1=true).
Argument0 must be a string consisting only of "0"'s and "1"'s
Argument1 must be a number between 1 and string_length(argument0).
*/

return real(string_copy(argument0,argument1,1));```

### bool6_to_bin(bool,bool,bool,bool,bool,bool)

```/*
Takes six boolean values and concatenates them to create a 6-bit binary encoded string,
suitable for converstion to a b64 value with the bin_to_b64() function.
*/

/*
force conversion of arguments to gml boolean constants
*/

if argument0{argument0 = true;}else{argument0 = false;}
if argument1{argument1 = true;}else{argument1 = false;}
if argument2{argument2 = true;}else{argument2 = false;}
if argument3{argument3 = true;}else{argument3 = false;}
if argument4{argument4 = true;}else{argument4 = false;}
if argument5{argument5 = true;}else{argument5 = false;}

/*
concatenate bools to string
*/
return string(argument0) + string(argument1) + string(argument2) +
string(argument3) + string(argument4) + string(argument5);```

```//pads a binary encoded string (argument0) to length (argument1)
var bin = argument0;//bin string to pad

if len < string_length(bin){return -1;}
if len == string_length(bin){return bin;}

repeat(len - string_length(bin)){bin = "0" + bin;}

return bin;```

These scripts should suffice for encoding/decoding all of our data values.

Additionally, to keep the player honest, you probably want some kind of tamper-proofing to go with your password encoding. Otherwise, it makes tinkering with the password to cheat too easy. For example, you could play the game, get a password, then get hurt, and get a new password, and by comparing the two, you could infer which characters in the password correspond to your health. Then, you could substitute different values for the password characters that correspond to your health health until you hit upon a value that gave you max health, or, depending on how the game works, even infinite health or invulnerability.

It’s true that deciphering password encoding schemes is a lot of fun, but we don’t want to make the system so easy that it invites cheating. Make the player work at it, and feel like they truly hacked something when they figure out your system.

To do this, we can reserve certain characters in the password for storing checksum values, or even hash values. Understanding hash and checksum math isn’t too difficult, but isn’t terribly necessary, either. We don’t need something impossible to crack, just something functional. There are better checksum functions than I’ll demonstrate here, but this should suffice to make the concept understandable to anyone.

### Simple checksum

 Level Lives Health Ammo Checksum A-? A-? A-? A-? AA-??

Let’s say the game state data is encoded with the following 4 values from our cipher table, above:

 Level Lives Health Ammo password char B D ? ? base-10 value 1 3 63 63

A simple checksum for this would be 1+3+63+63 = 130. Of course, this checksum isn’t very strong; any four values for Level, Lives, Health, and Ammo that add up to 130 will have the same checksum. But it does stop someone from changing a single character in the password and getting another valid password.

To add the checksum value to the password, we need to encode 130 as a base-64 value. This would be a 2-digit base-64 number: 22. According to our base-64 encoding table, the value 2 is encoded by the symbol C. So, 22 == CC. So the entire password would be:

 Level Lives Health Ammo Checksum password char B D ? ? CC base-10 value 1 3 63 63 130

Note that since 63*4 = 252, the highest the checksum value will ever go will be 252, or D8.

If you wanted to get really crazy, you can scramble the order of the characters, shuffling checksum characters in between the data value characters. But we’re not that concerned with obfuscation, so we won’t bother with an example of this.

In the next article, we’ll cover how to design the password specification in greater detail, and write some sample scripts that takes the password, validates and decodes it, and assigns the stored values to re-create the game state.

### Part 3

In old school console games, especially for the NES, it was common to enter a “code” or “password” in order to resume play where you had left off previously. Back in the day, memory was extremely expensive, and very few games implemented a battery backed RAM solution that allowed the player to Save and Restore a game.

Instead, a system of encoding the game state data into a long “password” was often used in lieu of a real save system. In addition to encoding the game state, these password systems often had some kind of validation built into them, so that not just any arbitrary input would be accepted. For fun, sometimes games would have special, secret codes that would enable cheats. For a few players, cracking the encoding system to enable you to configure the gamestate to your exact wishes was a kind of advanced meta-game, excellent for budding young hackers. There is great nostalgia value in these systems if you are into old school retrogaming.

If you want to build a password save system, at a high level there are a few things you need to do:

2. Validation
3. Encoding/Decoding GameState

## Get the input

For simplicity’s sake, let’s assume a four-character code will encode all the information that we need. In practice, most 8-bit NES games used much more than this, but for a simple input demo this should be sufficient.

The easiest way to enter a string in GameMaker is the get_string_async() function.

`save_pw = get_string_async("Enter password", "");`

Since `get_string_async` is an asynchronous function, it does not return a value immediately. We need to add an Async Event to catch the return value when the function calls back to the main program. The correct Async Event to use for this function is the Dialog event. The `get_string_async()` function doesn’t simply return a string value, though; rather, it returns a data structure called a `ds_map`, which contains 3 values: an `id`, a `status`, and the `result`. The `result` is the string that was entered by the player, the password that we are looking for.

We can put the following code in the Dialog Event to handle the return callback:
Dialog Event:

```var i_d = ds_map_find_value(async_load, "id");
if i_d == save_pw{
}
}```

The interface that `get_string_async()` provides is not very satisfying, aesthetically, but it works well enough for now. (We’ll explore a few other methods later that will more faithfully replicate the “password entry” screens from old NES games, in a future article.)

Right away, we have a few problems with simply getting a string:

1. Because `get_string_async()` allows the player to enter any string they want, the player may enter a string of arbitrary length. For our demo, we need them to enter a string that is exactly the right length.
2. The get_string_async() is not constrained in the characters it will allow the player to enter. Passwords for NES games varied in their alphabets, but many would allow A-Z, a-z, 0-9, and often spaces and special characters. Some games would allow only capital letters, while others would allow lower and upper case. One serious flaw with the old password systems was that the letters were displayed in fonts which often made it difficult to differentiate certain characters, like 1 and l, or 0 and o, etc. Later NES games sometimes corrected for this by using a more distinct font, or by omitting the ambiguous characters from the alphabet entirely.

There are many ways to constrain the allowed characters, but we don’t need to get super fancy with it for our demo.

In the next article, we’ll demonstrate how to decode the password — that is, to translate the password value to game state information. Finally, we’ll demonstrate how to generate and display the password when the game is over (or paused, or at a save point, or whenever it’s appropriate for your game), so that the player can write it down and enter it the next time they play to resume where they left off.

## An appeal for better YouTube video tutorials

I like people who put up how-to videos on YouTube showing how to do things they enjoy doing, particularly videos about gaming, game design, development, programming, art, criticism, reviews, you name it. But, unfortunately the majority of them are not as well produced as they should be.

The equipment to make videos is cheap, readily available, and increasingly easy to use, but making a good video is still not a simple thing. High quality production values and good content is requires work, but time and again I see a lot of the same amateurish mistakes made, and a lot of them are easy to correct.

## Set up

2. Do a quick sample take, and quality-check your results. If there’s a problem with the quality, bite the bullet and re-do the video. But avoid wasting that time by verifying the setup is right before you start production.
3. Check your audio levels before recording. I can’t tell you how many videos I can’t hear on my laptop’s speakers. But I have no problem at all hearing audio on my laptop when the recording levels were good.
4. Make sure that the audio track is audible, that there is no background noise, buzzing, dogs, traffic, airplanes, or anything else that distracts from the audio. Clear and sharp is nice to listen to.
5. Test your video capture quality. If you’re dropping frames, or getting blurry results, figure out why, and fix it before you post a video. Trying to read code through low-resolution downsampling or mpeg artifacting is awful.

## Content

1. Know what you’re talking about. Take the time to really learn your subject before you go out and publish videos. You don’t need to know it inside and out, but do know the topic you’re going to cover.
2. Think about what you’re going to say before you say it. Write up an outline or cue cards or a script if you need to. Have an agenda and don’t stray too far from it.
3. Get right to the point.
4. It’s fine to re-record the audio track and narrate over the video — it’s really hard to talk and do something that requires skill or thought at the same time. If you’re doing a programming tutorial, much of the video will probably be a still image of the screen, which you can pause and talk over as long as you need to.
5. Practice and rehearse. Don’t subject your audience to you fumbling about with your words or with the tools. There’s nothing wrong with stopping and doing it over, or at least editing out the mistakes. It’s harder than it looks. If you make a mistake, just keep going back and try again until you get it right, and then edit out the mistakes.
6. Speak naturally, but clearly and out loud, like you’re talking to a room full of people, rather than mumbling like you’re trying to avoid waking up someone sleeping in the next room. Try to project some vitality and excitement.
7. Have an intro. Get it out of the way quickly, but have it. Tell people who you are, where people can go to find out more about you and your projects, and what you’re topic you’re going to be talking about today. Say it out loud, put it in print on the screen, and put it in the video description.
8. Video footage of the working project being demonstrated. Show off all the features. This is the part of the video that will get attention and draw people in.
9. Now go under the hood. Now that you’ve shown us what your demo can do, take us on a tour of the code and explain how it works. This is the really interesting part of the video.
10. Iterations. If you build up the project in iterative phases, show that process. It’s very helpful to show new programmers how to break down a problem into smaller parts, and put those parts together and refine the approach toward a well-polished solution. Show the project in its stages of development, but don’t force us to watch the entire process start to finish. Skip to the good parts.
11. If it’s interesting, talk about alternative approaches, their pros and cons, and why you chose to do things the way you did. Was performance critical here? Flexibility of the solution? Code maintainability? Modular design? If there’s controversy over one approach vs. another, do a side by side demo of each approach, comparing their strengths and weaknesses.
12. Think about ways to say what you’re saying more simply. Don’t think on camera. You’re supposed to be presenting what you know, not discovering it.

## Postproduction

1. Edit! If you are rambling, or misspeak, go back and edit it out, or do a re-take.
2. Some people like to appear on camera. Nothing wrong with that. But when it’s time to show what’s on screen, switch to video capture software as your input source. Don’t film the screen over your shoulder. Use your editing software to stitch the shots together. You don’t have to do it all in one take.
3. Subtitles are appreciated, but if at all possible, don’t do “poor man’s subtitles” by opening up a text editor, setting the font big, and typing what you’re doing. Especially, don’t use this as the only method of conveying what you’re doing, in lieu of voice narration. Watching you type in realtime is extremely boring, especially if you hit backspace a lot.
4. Unless the video is on the topic of how to use the IDE, try to shorten or eliminate the amount of time devoted to navigating the interface. Most people know how to create a new asset, drag-and-drop a command into the Actions pane of the object editor, or type a file already. What’s interesting is what you’re putting in the asset. If you want to walk people through some code, that’s great, just don’t make us watch you type it. Paste it in, and then go through it line by line, highlighting the line you’re talking about if necessary. Instead of building the project up in front of the camera, walk people through a pre-built project, explaining it in detail.
5. Make your code style as presentable and readable as possible. Your code should be beautifully formatted with a extra attention paid to readability. Use well-chosen names for assets and variables. Use whitespace and indenting. Don’t code slop with the excuse that you’re doing things quickly because you’re on video. We’re watching the video in order to see how well you can code.
6. Don’t put a musical soundtrack in your video, or any other sort of filler audio. Narrate. Intro/outro music is fine if you’re shooting for professional polish, but not necessary. If you do use music, make sure a) it doesn’t suck, and b) it doesn’t get your video pulled for violating someone else’s copyright.
7. Ask yourself: Does the video need this? Cut extraneous bits. If you need to fiddle with your mic, or answer the phone, or whatever, cut it.
8. Ask yourself: Could I have done it even better? Re-do it.
9. Don’t post junk. If it didn’t turn out well, you don’t have to post it.
10. Don’t shoot for absolute perfection. A few minor flaws are excusable. But do try to make the best quality videos that you can.

## Essential extras

1. Host a demo project file somewhere, and link to it from the video description. If you’re sharing your knowledge and techniques, you might as well share your code. You’re already sharing it through the video, but by not including the downloadable project, you’re forcing everyone to waste their time re-typing in your code. There’s really no reason not to just provide it. There are many options for free file hosting services: google drive, dropbox, mediafire, github, sourceforge, the list goes on.

## Game Maker Wave Motion Tutorial

Following up on my motion and position tutorial, I present a tutorial on wave-motion. This was something I wanted to include in the original article, but I realized that there’s enough complexity to this concept that it merited its own separate article.

## Wave Motion

Wavelike motion is any motion that involves periodic oscillation, not just linear undulating motion. (Other types of wavelike motion include pulsing and concentric ripples, for example.) But we’ll talk mostly if not exclusively about linear undulation, since it is easiest to understand, simplest to implement, and the basis for many others.

## GameMaker Position and Motion Tutorial

Motion is critical to just about any video game. Nearly every game has moving things in it, and how they move is a vital part of the game. Learning how to program motion and control it effectively is one of the most important parts of a successful game. There are a number of possible approaches to handling position and movement. Learning how these work will help you make better games.

This isn’t absolutely everything there is to know about motion, but it’s a great overview to start with, and covers everything I’ve learned with respect to motion in GameMaker Studio.  (more…)

## Making a Configuration System in Game Maker, part 2: Requirements

If you haven’t yet, go back and read Part 1

## Design choices

Since we’re starting from (basically) nothing, we have a lot of decisions to make. Therefore, thinking about the design of your configuration system first before you start building things probably is a good idea.

## Requirements

First, let’s think of the features that we need. When I brainstorm features, I tend to go crazy. I think about everything I might possibly need. I think about all the things that would be OMG SO AWESOME to have. I find it helpful to do this, but I have learned that while having all these ideas is great and exciting, in the end you have to build everything, so every idea you come up with represents a lot of work and a lot of testing.

I’m only one person, working on these projects in my spare time — not a design house, or even a full-time lone developer, so if I want to ever have a hope of finishing my work, I have to scale back to the essentials. So why think about everything I can imagine?

1. I like my imagination. It’s awesome, and using it is fun.
2. The more I think about things, the better my ideas get.
3. When I think complex, even if I don’t ever build the whole thing, I can at least create a design that will better accommodate further development later if I want to extend the basic implementation. I might do the extending, or someone else might do it later; it doesn’t matter. Building code as a foundation for future code is a good thing if you can manage to do it. Doing so correctly means avoiding having to repeat yourself in future projects.
4. Even if I don’t have all the resources or talent that I might need in order to implement a design, having a good design documents makes it that much more likely to inspire others to contribute something to the project.

A very simple Options system might consist only of a single screen. But as we’ll soon see, there may be need to break things up into multiple screens, especially if we have many different options or categories of options.

If we have multiple screens, we’re going to need a means of navigating between them. This can be as simple as a group of rooms with room_goto commands linking them up, or it can be something else.

To design our Configuration Options system, we need to address a few things:

1. Features: What options do we want the user to be able to configure? What choices do we want each configuration option to have?
2. Interface/Controls: How do we want to present these options to the user? How will the user interact with the interface to set it?
3. Implementation/Integration: How do these configuration choices get applied, technically? How will these configuration options interface with the game itself?

## Features

Some of these will be fairly standard, common to many games, while some will be highly specific to the specifics of this game. I’ll address the standard ones, but don’t worry — once you see how we implement the standard features, it will be easy to set up config options for the features that are unique to your game.

You don’t need to support all of these options, but the following list is a good start for what you might want to consider:

### Graphics

PC hardware very commonly has different graphical capabilities, due to differences in hardware, particularly the video card and monitor. While just about any video card is going to be capable of playing most Game Maker games at full quality, there is still the monitor to contend with.

#### Display settings

It might be easiest to force a specific display mode, but that’s not a flexible approach and may not work for all players. By far, it’s better to assume that the display mode the game starts up in is the player’s preferred (or only) graphics mode, and leave it as is.

If you want to enable everyone to play your game, it’s a good idea to give them some control over how the graphics of your game will be displayed on their screen.

The easier approach is to allow the player to set the display settings through the computer’s control panel, and just run in whatever mode the display is set to when the game runs.

More professional looking games usually offer the play an in-game configuration menu that allows them to change the same settings without having to leave the game program. It’s a convenience, to be sure, but it does keep the user in your game.

Keep in mind, too, that in GameMaker, there’s a distinction drawn between the Display (the physical hardware), the Window, the Room, and the View. Most of what you might think could be accomplished by forcing a specific display configuration can be better accomplished through Widow, Room, and View settings.

• Fullscreen or Windowed mode?
• Display resolution
• Aspect ratio
• Refresh rate
• Color depth

#### Fullscreen or windowed mode?

Most games play best in fullscreen mode, but sometimes players like the option of playing inside a window, as it allows them to switch between other applications more easily. The downside of this is that it becomes all too easy to mouse outside of the game window, and lose focus. You can set the game to pause if the window loses focus, but this is still annoying disruption and can mess the player up even with pausing the game.

When to run in a window?  As a general rule, I like to develop and debug my game in windowed mode, since it’s easier for me to get at other windows that I’m working in. But for finished games, I usually like the game to run fullscreen. I want the game experience to be distraction-free.

That’s not always the case, though. Casual style games, pausable games, puzzle games, and turn-based games that wait on you to act are good candidates to have a Windowed mode as an option.

#### Resolution

These days, it’s probably not necessary to change the display resolution. Just about everyone uses LCD displays with fixed resolution. While these screens are capable of emulating other resolutions, they do not look as good when they do. Games for mobile devices of course will play on a device with a specific resolution that cannot be changed.

In any case, the game should never force a specific resolution on the player; you may want to offer the player controls to allow them to change the resolution for themselves within your game interface, though.

If a player wants to set a specific resolution, they can always just use the display settings control panel on their computer. If you want to provide an interface for this to them in your game, you can, but it’s a convenience or luxury feature, not a necessity. Supporting multiple resolutions means a lot of extra work and testing for a developer, so unless you’re a professional studio with the resources for this, it’s probably better to focus on supporting one resolution well.

Don’t worry about supporting every possible display size right away, the amount of work it takes to do it well will kill your project. Instead, focus on making the game as good as it can possibly be in one default resolution, and if your game ends up being popular enough to warrant it, you can build resources (primarily different sized rooms) to support other display resolutions better.

If you do change display resolution in the game, keep in mind a few things:

• Always change it back when you’re done. Use `display_reset()` for this. Keep in mind if the game crashes, this doesn’t get called, though, and may leave the computer in a resolution the player doesn’t want. This can panic a non-technical user.
• Don’t change display settings without first testing them. Use `display_test_all()` with the settings you’re about to set, before you actually set them. Be sure to have some fallback code that gracefully handles what takes place if the new settings don’t test OK.

You probably do want to know what resolution display the game is playing on, though. There are a lot of reasons to need to know this. Use `display_get_width()` and `display_get_height()` to detect the display resolution. Note this will return the current settings for the display, not what the display’s maximum or native resolution is.

You should decide the minimum display resolution you’ll support. GameMaker’s default room resolution is 640×480, which is the old VGA standard resolution. This is a very safe resolution to use, because just about any display will support it, but is also quite tiny these days. It’s still not a bad resolution to start out with, though. The smaller the minimum resolution you support, the more devices your game will run on.

It’s good to support larger resolutions, too, of course. Most people do have larger displays these days, and it’s desirable to utilize all that space effectively. Very large display resolutions can introduce performance issues, though, so test your framerates when running at maximum resolution, and make sure they’re acceptable.

If you’re targeting a specific mobile device, learn what its native resolution is, and use that. Read up on guidelines for Android and iOS development to learn the recommendations other developers follow.

To accomodate other resolutions, there are a variety of approaches. You can create a series of rooms and HUD graphics to provide a tailor-fit screen for every resolution you support. This is a lot of extra work, though. Scaling the game to fill the display can be an OK approach to take, and requires a lot less effort, but will result in a less attractive game with blurry edges due to the way the Game Maker runner handles scaling graphics. Another approach is to letterbox — draw the game in its standard resolution at a fixed 1:1 scale, and leave a black border around the edge of the screen, framing the game window. This can be good, too, but if you have too much black border it can be annoying.

#### Aspect Ratio

These days, you also have to consider aspect ratios, the ratio of the width and height of the screen. In the old days, computer monitors and TV sets in the United States all used 4:3.

Today, it’s a different story. On the desktop alone, people may have 4:3, 16:9, or 8:5 (16:10) displays. 16:9 is pretty quickly becoming the most common, particularly in 1920×1080 (1080p), and is also the ratio of HDTV, so if you have any desire to port your game to a game console, you may want to start out at 16:9.

And there are still others, albeit less common ones. If you’re planning on targeting a mobile platform, you’ve got even more possibilities.

If you’re building an HTML5 game, keep in mind that the browser window “chrome” (menus, toolbars, etc.) all take up space as well, which should be subtracted from the available display you have to run your game in, and this can change the effective “aspect ratio” of the web page unpredictably.

### Enable/disable special effects which may affect performance (such as particles).

There are two main reasons for making these configurable: performance on slower machines, and user preference. Some players don’t like effects-heavy games, and prefer a sparse, cleaner visual experience without all the bells and whistles. Sometimes the screen can become so cluttered with particles that you can’t see the action, and it hurts your game rather than enhances it. So it’s nice to allow the player the option to not have these things in their game.

#### Refresh Rate and Color Depth

These settings are controllable in GameMaker, but there’s almost no reason for it. Most games shouldn’t have any need to mess with the color depth of the display.

In the 1990’s, it was more common to see variety here, but these days it’s pretty safe to assume that the computer will be running in 32-bit color mode. Oddball machines might be running in 16-bit or 24-bit color, and even more rarely you may encounter a display configured to run in 16-color or 256-color mode, but these are rare, and probably won’t have the necessary hardware to run a GameMaker game adequately anyway.

Refresh rate is probably also safe to leave alone. This setting is more pertinent to CRT displays, which are rapidly disappearing from the desktop computer landscape. Most LCD monitors use a 60Hz refresh rate, although there are LCD HDTVs that use 120Hz or 240Hz refresh rates. Older TVs used 30Hz.

Some people can notice a difference between refresh rates, and can tell you readily just by looking what refresh rate a monitor is using, especially if they are familiar with the display in question, but most people can’t, and don’t even think about such things if they’re even aware of them.

Some game developers will say that it’s a good idea to sync the `room_speed` of your game to the refresh rate. Keeping FPS and refresh in sync, or at least in a whole-number ratio, is not a bad idea. But the better way to do this is to set your `room_speed` to the `display_get_frequency()` or just assume a refresh rate of 60 and use a `room_speed` of 30 or 60. Keep in mind that regardless of what the room speed is set to, it’s `fps` that is the actual frame rate, and this usually fluctuates a bit.

### Sound

• Master volume
• Music volume
• Effects volume
• Mute

Again, for the most part, these configuration options could be set by the user outside of the program, by using the volume knob on the speaker, or through the Sound and Volume control panel. But it’s a nice convenience to provide an interface to the user so they don’t have to leave your game to make adjustments. The nicest one is the separated music and effects volume. This will allow the player to adjust the mix to their taste.

One important thing to do is to remember the user’s preferred volume settings and automatically set them when the game runs, and set them back when the game exits.

The harder task will be to separate the volumes for the Master, Music, and Effects volume controls. Mute is actually very simple, and there are a few techniques that can be used. One way is to have a global variable called “mute”, and to set up a conditional before each and every sound function call. This is an inferior approach because it means you have to make sure you catch every single sound function call in all your code, whichis a pain to program. The other problem with it is that all those extra `if (mute){}` checks take processing power at runtime, albeit a tiny amount, it still adds up and could conceivably hurt performance.

The better way to handle mute is to simply setting the volume to 0. This is done with the `sound_global_volume()` function, which we also use for setting the master volume. The sounds still play, but at 0 volume, you don’t hear them. You don’t have to add code for every `sound_play` and `sound_loop` function in your code. And since the computer doesn’t have to ask every single time whether the game is muted or not, it’s a lot less processing. `sound_global_volume(0)` mutes your game, and `sound_global_volume(1)` restores the master volume to full. Use a global variable to store the setting for the master volume as well, so instead of restoring the volume to full blast on unmute, you set it back to the master volume value.
`globalvar master_volume;`
`//master_volume is set in the config screen.`
`mute() {sound_global_volume = 0;}`
`unmute() {sound_global_volume = master_volume;}`
You can put the Mute function into your game configuration menu, or you can make it more readily accessible to the player by creating a control for it that they can access while the game is playing.

Separate volume controls for bgm and sound effects will take a little more work, using the `sound_volume()` function to control the volume for each individual sound in your game, so we’ll cover that in detail later.

Note: GameMaker Studio 1.1 introduces an entirely new audio system. The above code samples work with the old system.

### Controls

• Provide the player with a screen showing the current settings, and allow them to set up their own custom settings.
• Allow the player to save their custom settings as a profile, load from a profile, delete profiles.
• Allow the player to reset the controls back to their default settings, or to select a custom profile (such as for different keyboard layouts, etc.).
• Provide the player with options to use various input devices (keyboard? mouse? joystick/gamepad?)

### Difficulty/Game Options

• Difficulty (Easy/Normal/Hard)
• Starting level
• Enable/disable (or throttle) specific features
• Number of lives
• Text size/speed (if you’re displaying lots of dialogs)
• etc.

This part is highly dependent upon your game. You can set up an interface to allow the user to set these things, but integrating them into your game will be highly dependent upon your game. Some things (number of lives, starting level) will be trivial to implement and integrate; others will take a great deal of design sense and playtesting.

### High Scores/Achievements

An Achievements system, again, will be highly dependent on your game. But we can probably provide some abstractions that make it easier to implement your achievement system in a consistent way, such that the specifics may be different from game to game, but they way they are handled will be the same.

Some features we might like to see:

• Record more than 10 high scores
• Record other types of achievements
• Record achievements per player account
• Clear achievements
• Upload scores/achievements to an online “Hall of Fame” server

### Localization options

• Language
• Keyboard layout – keyboard layout could tie in well with the Controls. A user with a non-QWERTY keyboard could set that here, or have it be auto-detected from a system variable, and automatically update the keyboard controls with default keys appropriate to the layout map of the local keyboard. But then, the user should still be able to override these with their own preferences.

### Save States/User Profiles

If your game stores user profiles or save state data, provide an interface to the user to do things with them. Common activities include:

• Create new
• Delete
• Copy
• Rename
• Edit info (for user profile data, such as user name, password, and other profile data).

What’s in the save state file will be a bit beyond the scope of this series, and in any case should be highly dependent on your game. While I won’t tell you what to put in your savefile, I can tell you how to set up some file i/o functions that will enable you to read and write your savefile, and maybe some suggestions for how to protect this information, validate it, and format it.

It’s also a good idea to save the configuration settings themselves. Configuration settings (graphics, sounds, etc.) should be separate from game savestate data (My character’s name is XYZ, He is level N, his inventory consists of…, he has visited the following locations… he has achieved the following goals… etc.)

We have a few design choices for how we want to do the config save. The simplest would be to simply revert to defaults every time the game is launched (ie, not save anything, but remember a basic set of options that will definitely work on any system the game is run on.) From a user’s perspective, however, this would become annoying, as they will need to re-configure settings to their taste every time they quit the game. The next simplest approach would be to remember what the settings were the last time the user set them, and to remember the defaults in case the Last config profile gets corrupted.

This is probably as far as you really need to go; but once you are saving profiles, you’re not too far from allowing the player to save multiple configuration profiles, or per-user profiles. We’ll probably implement this later on as an advanced feature.

• ### Other stuff

• Network: These days, you may also want to have configurations options for network (TCP/IP settings, firewall/proxy server settings, etc.)
• Social: Or you might want to have some kind of social networking features, such as sharing your game progress with your Facebook and Twitter friends, inviting friends to try out your game, or even send friends in-game items to help them, and so on.
• Hall of Fame/Achievements: Or a “submit high score to server” feature. Or you might have a registration and payment screen.

These things are much more complex to design and implement properly, and as such will be outside the scope of this tutorial for now, but it’s good to think about them!

Personally, I would like to see these type of features built in to Game Maker, and I hope that YoYoGames will incorporate features like this in time. When I say “built into Game Maker, I don’t  just mean having a library of available GML functions that one can use to build a configuration system out of. That is, after all, what we are going to do with this project. What I mean is, it would be nice if such a system existed as a ready-made component that you could just drop in to any project, and set up with just a few clicks or lines of code.

These features, and the interface the user will interact with to manage them, will be challenging and time-consuming to implement, and are not really “the game”. A good configuration system and interface is excellent polish for a professional-quality project. Game Maker’s purpose is to make game development easy by doing the hard technical stuff for you. So far, they’ve done that by focusing on the in-game building blocks that a designer would use to produce a play experience. Now that they’re turning Game Maker into a more professional tool, I hope that they’ll start thinking about including these kind of features, too.

Until then, we have to fend for ourselves. The above list of features represents a significant amount of work that we need to do. Setting up a system that is flexible enough to allow us to do this easily is no small task. If I’m lucky, by procrastinating long enough, I may find that they end up doing the work for me:) If I am going to do all this work, then I want to get the most return for that work that I possibly can by making a re-usable system that I can apply easily in any game. This means a de-coupled, generic system that can be adapted easily to a wide variety of projects. This is a good situation to create a Game Maker Extension (.gex). However, an extension will not give us a complete system — an Extension allows us to package a library of useful new GML functions that we write, but our built system will also need room, object, sprite, and sound resources, and a .gex cannot include those resources. Ultimately, this means that we may not be able to realize a dream of a drop-in system. But even providing better building blocks to create such a system would be better than nothing.

To begin, we’ll start small, and implement some basic things, and then iterate and refine our solution until we have something that hopefully works really well for a wide variety of games.

In our next article, we’ll discuss the code needed to make these configuration settings, as well as how to store and retrieve them.

## Make a Configuration System in Game Maker, part 1

One thing that’s still currently harder than it should be in Game Maker is creating an interface to allow the user to configure the game preferences. It’s a real pain to have to implement a configuration system in each game you make from scratch — it takes a lot of time away from the development of the actual game.

Game Maker is supposed to make game development faster and easier. It really should have features to allow making the parts of the game program that are not the game itself faster and easier as well. One may consider this a weakness in Game Maker, if one takes Game Maker to be intended primarily for making game development quicker and easier. Which, it is.

But, Game Maker also is intended to be an educational platform, so I see this as both an inconvenience and an educational opportunity. How often do you get to devise your own UI widget and implement them out of primitives rather than use some library?

Since Game Maker does not provide this out of the box, and due to the difficulty of implementing such a system even once with good quality, it’s very worthwhile to try to build a generic system for game configuration options, something flexible enough to allow it to be used in many game projects, rather than have to build anew for each new game you develop. The up front investment in development for the system will be regained in the re-use of the system in many projects.

This article is the first in a series which describes in detail how to design and implement such a system in Game Maker: Studio. In the process, I’ll be generating a number of Extensions which you may use in your own projects.

Unfortunately, these articles will necessarily be Windows-centric, as I do not have the means to test what I’m building on anything but Windows and HTML5. I’ll be making the source available, though, so if you want to try these out in Android, OS X or iOS, or (if needed) modify/extend them to work on these platforms, you’re very much encouraged to do so, as long as you share the source and keep it open.

I would welcome other Game Maker Studio users who are building for OS X, iOS, and Android who want to collaborate on this project to contact me.

## Going wild with UI design

Many games (especially professional games) go crazy with interface design. The designer is encouraged to (pardon the clichés) think outside the box and reinvent the wheel. More than simply coming up with new skins for buttons, sliders, pulldowns, and listboxes, etc., they do something really special to integrate the game, or its theme, with the configuration screen controls.

For a superb example of such an implementation, check out the configuration screen for Derek Yu’s Spelunky.

By the way, did you know that Spelunky was originally created in Game Maker? Later on, its developer re-did it for XBox Live, and released the source for his Game Maker project, so be sure to go check that out. Play the game, and see how the configuration screen is cleverly set up as a special room in the “normal” play world, where your explorer can trip switches that control the configuration of the game. Then look at the source to understand how this was implemented.

Keep in mind that while Spelunky’s solution to the config screen is original and innovative, it’s not perfect — for example, it’s not terribly fast to use. There are always tradeoffs with any design — do what makes the most sense for your game and always with the user foremost in your thoughts.

If you want to, you can create an interface like this, but it’ll be more of a custom job. This series is geared toward building a foundation out of generic, reusable code. But the good news is, much of what we cover in here will end up being useful, because really the only difference between a custom configuration screen and a generic one is the interface, and we’re going to keep the other parts of the system abstract enough that they should be re-usable even in a custom system.

So, keep reading! Besides, it’s better to learn these basic approaches before trying to tackle something more innovative and complicated.

A word of caution, though: many times these highly customized interfaces look cool, but are terrible in how they function. They aren’t intuitive or understandable, or the controls are actually difficult to manipulate. Always strive to make your UI user-friendly.

There are entire bookshelves worth of books you could read to learn about good User Interface design principles. I don’t have space here to say it all, but in summary:

1. Avoid forcing the user to have to think about how to do what they want to do. The UI is not a puzzle. Its purpose and function both should be immediately obvious.
2. The UI should convey information clearly to the user. This information should be: the purpose of the control; the current configuration state.
3. Controls should be easy to use and easy to understand how to use.
4. There should be as few controls as are necessary. It’s a myth that people want lots and lots choices. They think they do, but what they really want are choices that are relevant to them, and the options that they want. A good designer can make most of these choices for the user without having to ask them their preference, but also knows which choices need to be offered to the user.  Look for ways to reduce the amount of controls you give to the user. Show only controls that are relevant in the current context. Combine controls when they represent mutually exclusive options.
5. Provide sensible defaults. The default option should be the most sensible choice for the most people. Often, this is one standard option, but not always. Sometimes there are two or three good candidates for what may be a sensible default, and it is not obvious which one the default should be. Knowing which is the best configuration for a default setting may depend on environment and context. So, if your program can sense these things somehow, that can aid in selecting the most appropriate default.

There are always exceptions to the above rules. Like, I’m sure that for a certain puzzle game, a really innovative configuration screen that is itself a puzzle, and in its way serves to introduce the player to the game’s mechanics and gameplay would be awesome. But if you’re going to pull something like that off, you need to be very careful that your design works.

## A Game Maker Weakness: No UI widget libraries

Game Maker has nearly nothing in the way of traditional interface control widgets. This alone makes creating a Settings screen very difficult for a novice Game Maker user. However, figuring out how to do this is an excellent opportunity for an aspiring Game Maker user, provided of course you can figure it out. Learning this will give you a lot of useful skills and insights about how to design both software and user interfaces.

In the long run, I believe it will be better for everyone if YoYoGames extends Game Maker to provide better built-in tools to allow developers to create polished, professional configuration screens without having to sink huge amounts of time into it. Preferably, some widget objects based on the native OS, but skinnable to allow the game to have its own look and theme would be the best way to go.

Until then, we have to make do, so we might as well come up with some useful approaches and share the knowledge about them. Fortunately, creating our own widgets out of Objects, a few sprites, and a little GML isn’t that difficult.

In the next article, we’ll talk about the Design of our Configuration System, and brainstorm the features we want it to have. I’m not just being editorially cute by using the “royal we” either — if there’s something you’d like to see in what I’m building, drop a comment.