Playing with Strings in Game Maker Pt. 1

I don’t remember who it was that told me this, but apparently one of the first things they teach you in a university Computer Science course is how to play with strings. When I heard this, I thought it was an unusual place to start. Sure, it shows the basics of how a computer language works, but how useful would that really be? Up to that point I had never needed to build or break a string during the development of any of my games. Looking back upon that time, I realize how naive I was and how little I understood how incredibly important it actually is.

Playing with Strings

At the core of anything built in code is the transferring of data. When someone first starts to code, they inevitably move the bits of data in really small chunks, each individually. For example, you pass an objects X coordinate, then Y, then the image angle, etc. This is fine in many cases, but as your systems become more complex, the more you would likely prefer to have a simple function that just deals with player location. An even more relevant example is accepting user input for things such as their name. Game Maker has some basic message systems, they are clunky and ugly. Ideally you don’t want those pop-ups appearing as they take you right out of the experience. In these next few tutorials, I am going to go through several different methods of manipulating strings with practical examples. Let’s dive in.

Numbers and Strings

One of the most common errors I see people get caught up on, is that they are passing one type of information, like a string, to a function looking for another type, such as numbers. Understanding that Strings and Numbers are different data types is the first, and possibly most important lesson you need to learn before being able to manipulate data.

The data type “Number” in Game Maker is any number you can imagine, such as 300, -12, 14.98603. Unlike many other programming languages, there is no default for integer only (whole numbers) data types. If you need an integer, you can always round it off using one of the three functions: round(nearest), floor(round down), or ceil(round up).

The data type “String” is a bit more complicated, in the fact that it contains alpha-numeric characters, which means it can have numbers, letters and symbols. That means the number “4” is the same as “four”. What makes it even more confusing is that the characters are actually the visual representation of ASCII code numbers. That’s right, all the letters are actually numbers, which is why we need to treat them differently.

Chr vs Ord

To make sure you understand this, we will do a quick little example using the single character functions ‘chr’ and ‘ord’. Here we will demonstrate how numbers are letters and vice-versa. Quickly open a new file, create an object, then place that object in a room. In the Draw Event of the object, add a script that has the following code:

draw_text(100,100, chr(97));
draw_text(100,150, ord('a'));

When you run this example, you will see that the chr(97) produces the letter ‘a’, while the ord(‘a’) produces the ASCII code number 97.

String vs Real

Now that we have done that, we can look into something longer than a single character. A string is a sequence of characters and is usually denoted in code by being surrounded by quotation marks ” “. These are used all the time to display a message or record information. Often you will want to turn numbers into a string if you want to ensure that no math operations are applied. For example, if you had the player input their phone number (555-1234), you wouldn’t want 555 to subtract from 1234, therefore you must turn it into a string.

On the other hand, sometimes you will want to convert that string into a number. Game Maker has a function for that called ‘real’. This will translate a string number into a regular number. For example, if you want to tell the player how many days old they are, you would need to know their birthdate, which would be made of three strings (such as 03 17 1981) which we then would need to be turned into numbers.

A word of warning: you cannot convert text directly into numbers.  real(“Jason” ) will cause an error.

Project 1 – Player Name Input

We are now ready to start putting this knowledge to use and the first project will be to accept user input to create the player’s name. Our design will be to have text displayed on the screen showing the current player name and a new player name based on the keyboard input of the user to a maximum of 8 letters. We will not allow for numbers, spaces or other characters, only upper and lower case letters. We will also allow the user to use backspace to undo previous letters. Finally, when you press Enter we will change the current name to the one that was entered.

To start, we need one object placed in the center of a room and 3 scripts: scr_Name_Create, scr_Name_Draw, and scr_Name_KeyPress. Attach these scripts to the according Event, as in scr_Name_Create is the Create Event. For the key press, assign it to Any Key.

scr_Name_Create

inputAmount = 0;
inputMax = 7;
curName = "My Name";
newName = "";

Here we are setting the four variables we will need. We need something to count how many keypresses we have input (inputAmount) and our cap (inputMax). The following two are the place holders for our current name(curName) and the one being typed (newName). As you can see, both of those have quotes meaning that they are strings.

scr_Name_Draw

draw_set_halign(fa_center);

draw_set_color(c_black);
draw_text(x, y, "Current Name");

draw_set_color(c_red);
draw_text(x, y + 20, curName);

draw_set_color(c_black);
draw_text(x, y + 40, "New Name");

draw_set_color(c_blue);
draw_text(x, y + 60, newName);

This script is needed simply to display the text on screen. We start by aligning all the text in the center, then we set the color: black for the title, red for the current name, blue for what you type. Nothing fancy here, that will be found in the next script.

scr_Name_KeyPress

if inputAmount <= inputMax  {
    if (keyboard_lastkey >= 65 && keyboard_lastkey <= 90) or (keyboard_key >= 97 && keyboard_key <= 122)
    {
        newName = newName + keyboard_lastchar;
        inputAmount += 1;
    }
}

Stage one for our key press script is to take the actual keyboard input. We start with a check to ensure that we still have room for additional letters. Next we check for whether the key that has been pressed is a letter or not. In this case, we are allowing both uppercase (keycodes 65-90) and lowercase (keycodes 97-122).

If both of those cases are true, we begin to construct the name. We use the variable newName and add the last key that was inputted. (The adding of two or more strings is called concatenation, in case anyone asks.) Game Maker has two functions that can capture this, keyboard_lastkey and keyboard_lastchar. We are using the lastchar function as it gives us a letter which we can add. If you were to use keyboard_lastkey, you would have to wrap it in a chr to convert it, which is wasted code and also would likely only give you uppercase letters. Finally, we increase the input amount.

Continuing on, we want to back up through our name and remove the last letter if we hit the backspace. This code is still in the keypress script after the previous code.

if keyboard_key == vk_backspace
{
    last_ltr = string_length(newName);
    newName = string_delete(newName, last_ltr, 1)
    if inputAmount >= 1
    {
        inputAmount -= 1;
    }
}

Again, we check to see if the backspace has been pressed first. If that is true, we create a variable (last_ltr) which uses the function string_length to see how many characters are comprised in our newName variable. The next line we are subtracting the last character in the string. This is done using the string_delete function, which returns the shortened string. You can see that it requires three arguments. The first is the string to be chopped, then the starting spot in the string and the finally the total character count. In this case, the total count could be any number greater than zero as we know we are just removing the last letter and that there are none following it. Finally, we subtract from the inputAmount, but ensuring that we cap it so it doesn’t go into negative numbers.

The last step we are going to implement, also in the same keypress script, is the ability to commit the name to become our current name.

if keyboard_key == vk_enter
{
    curName = newName;
    newName = "";
    inputAmount = 0;
}

If the Enter key is pressed, we simply assign the variable curName to be newName and than blank out newName and set the inputAmount to zero so we can input a new name again.

As you can see, we have done several things with our text. We are now able to add letters to a string, remove them from the end, calculate the length of a string and limit our input, both in size and characters. With this knowledge, you should be able to do a wide range of things such as typewriter style text or pig Latin names and more.

Next time we will take a look at some more string functions and break larger things apart.

5 thoughts on “Playing with Strings in Game Maker Pt. 1

  1. You should add “io_clear();” after “… newName = newName + keyboard_lastchar;
    inputAmount += 1;” In this way, you add a character one by one.
    BTW, it’s a very great tutorial, thank you!!

  2. I am glad you enjoyed it! Adding io_clear() is a great suggestion. I might update this soon and add that as it does make things more structurally sound.

Leave a Reply