PC Games

Orb
Lasagne Monsters
Three Guys Apocalypse
Water Closet
Blob Wars : Attrition
The Legend of Edgar
TBFTSS: The Pandoran War
Three Guys
Blob Wars : Blob and Conquer
Blob Wars : Metal Blob Solid
Project: Starfighter
TANX Squadron

Android Games

DDDDD
Number Blocks
Match 3 Warriors

Tutorials

2D shoot 'em up
2D top-down shooter
2D platform game
Sprite atlas tutorial
Working with TTF fonts
2D adventure game
Widget tutorial
2D shoot 'em up sequel
2D run and gun
Roguelike
Medals (Achievements)
2D turn-based strategy game
SDL 1 tutorials (outdated)

Latest Updates

SDL2 turn-based strategy tutorial
Thu, 14th April 2022

Water Closet ported to PlayStation Vita
Tue, 4th January 2022

The Legend of Edgar 1.35
Sat, 1st January 2022

Achievements tutorial
Thu, 2nd December 2021

SDL2 Rogue tutorial
Thu, 30th September 2021

All Updates »

Tags

android (3)
battle-for-the-solar-system (9)
blob-wars (9)
brexit (1)
code (6)
edgar (7)
games (39)
lasagne-monsters (1)
making-of (5)
match3 (1)
numberblocksonline (1)
orb (2)
site (1)
tanx (4)
three-guys (3)
three-guys-apocalypse (3)
tutorials (10)
water-closet (4)

Books


The Honour of the Knights (First Edition) (The Battle for the Solar System)

When starfighter pilot Simon Dodds is enrolled in a top secret military project, he and his wingmates begin to suspect that there is a lot more to the theft of a legendary battleship and an Imperial nation's civil war than either the Confederation Stellar Navy or the government are willing to let on.

Click here to learn more and read an extract!

« Back to tutorial listing

— Creating an in-game achievement system —
Part 1: Unlocking Medals

Note: this tutorial assumes knowledge of C, as well as prior tutorials.

Introduction

A number of gaming platforms these days, such as XBox, PlayStation, and Steam support achievements; a system in which players are rewarded for carrying out specific tasks in a game, such as completing a level within a set time, defeating a certain number of enemies, finding a bunch of hidden objects, etc. In this tutorial, we're going to look at how to add such a system to a game, including how to upload the progress online, so it can be viewed outside of the game. This first part will cover everything that is needed to get our system up and running.

Extract the archive, run make, and then use ./medals01 to run the code. You will see a window open like the one above, showing some text on a black screen. Press 1 to earn a bronze medal, Return to earn a silver medal, and press Space three times to earn a gold medal. Once you've earned all other medals, you will be automatically awarded the ruby medal. Close the window to exit.

Inspecting the code

We'll start by looking at defs.h, where all our defines live:


enum {
	MEDAL_BRONZE,
	MEDAL_SILVER,
	MEDAL_GOLD,
	MEDAL_RUBY,
	MEDAL_MAX
};

We have an enum here to hold all our medals. We have 4 medals (with MEDAL_MAX existing to help with our array sizes).

We also have an enum for our sounds:


enum {
	SND_MEDAL,
	SND_MAX
};

Right now, the only sound we're playing is the one for when a medal is earned, which we're calling SND_MEDAL. Again, SND_MAX is to help with our array sizes.

Next, let's look at structs.h, starting with the Medal struct:


struct Medal {
	char id[MAX_NAME_LENGTH];
	char title[MAX_NAME_LENGTH];
	char description[MAX_DESCRIPTION_LENGTH];
	int type;
	int notify;
	int hidden;
	unsigned long awardDate;
	Medal *next;
};

The Medal struct holds all the details of our medal. `id` is the internal id of the medal (such as "key1"). `title` is the title of the medal, such as "First!". `description` is the description of the medal, such as "Pressed 1". `type` is the type of medal this is, using a value from the enums in defs.h. `notify` is a field to say whether this medal should notify the player. We'll see this in detail later. `hidden` is a flag to say whether the medal is hidden. You may have seen this before. It's useful for preventing story points in games from being spoiled if a player browses the achievements list before reaching that part of the game. awardDate is the date at which the medal was earned, in milliseconds from the epoch. Our Medal is a linked list, and therefore has a `next` pointer.

Next, we have a Game struct, to hold our game information:


typedef struct {
	Medal medalsHead;
} Game;

Right now, it has one field - medalsHead, which will be used to hold the medal information, as a linked list.

That's defs.h and structs.h done, so now we can move on to how we're handling our Medals. All our logic and rendering for our Medals lives in a file called medals.c. There are quite a number of functions to look at, as a result, so we'll work through them all one at a time.

Starting with initMedals:


void initMedals(void)
{
	loadMedals();

	medalTextures[MEDAL_BRONZE] = getAtlasImage("gfx/bronzeMedal.png", 1);
	medalTextures[MEDAL_SILVER] = getAtlasImage("gfx/silverMedal.png", 1);
	medalTextures[MEDAL_GOLD] = getAtlasImage("gfx/goldMedal.png", 1);
	medalTextures[MEDAL_RUBY] = getAtlasImage("gfx/rubyMedal.png", 1);

	notifyOrder = 1;

	resetAlert();
}

We're first making a call to a function named loadMedals. We'll see this later. Next, we're loading our four medal textures, assigning each to the appropriate index in an AtlasImage array called medalTextures (static in medals.c, of length MEDAL_MAX). With those loaded, we set a variable named notifyOrder to 1. This variable is being used to track the order in which medals are awarded for the current session, since it's possible for multiple medals to be unlocked at the same instant. We'll see this being used in a moment. Finally, we call another function named resetAlert. Again, we'll see this in action later.

The next function is awardMedal. This is the key function we call when the player unlocks a Medal (such as pressing Space three times):


void awardMedal(char *id)
{
	Medal *m;
	int numRemaining, hasRuby;

	hasRuby = numRemaining = 0;

	for (m = game.medalsHead.next ; m != NULL ; m = m->next)
	{
		if (m->awardDate == 0 && strcmp(m->id, id) == 0)
		{
			m->awardDate = time(NULL);

			m->notify = SDL_GetTicks() + notifyOrder++;

			SDL_LogMessage(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO, "Awarding medal '%s'", m->id);
		}

		if (m->awardDate == 0)
		{
			numRemaining++;
		}

		if (strcmp(m->id, "ruby") == 0)
		{
			hasRuby = 1;
		}
	}

	if (numRemaining == 1 && hasRuby)
	{
		awardMedal("ruby");
	}
}

This function takes a single argument - the id of the Medal we want to unlock (as `id`). We start by assigning two variables named hasRuby and numRemaining to 0. hasRuby will be used to track whether we have a Ruby Medal available, so that we can award it upon unlocking all the other medals. numRemaining tracks the number of Medals that we have yet to unlock.

We then begin looping through our list of medals, assigning each to a variable called `m`. We test to see if `m`'s awardDate is 0 and also whether its `id` is the same as the id passed into the function. If a Medal's awardDate is 0, it is currently unearned. Testing to see if the medal's awardDate is 0 prevents us from unlocking it multiple times. Upon finding the Medal to unlock, we set `m`'s awardDate to the current time, by calling time(NULL), and also set its `notify` value to the current value of notifyOrder. We also increment the value of notifyOrder as we do so. This means that each time a medal is unlocked, the unlock order can be preserved.

We then test the medal's awardDate value. If it's 0, we'll increment numRemaining, since we still have medals left to award. We're also test to see if the `id` of the medal is "ruby". Much like the platinum trophy on the PlayStation, our Ruby Medal will only be unlocked once we've unlocked all other medals.

Having processed our medals and awarded a medal if approrpriate, we finally check to see if we want to award the Ruby Medal. The Ruby Medal will always be the final medal we award, so we test to see if we only have one medal remaining, and also whether there is a Ruby medal to award. If we don't check to see if there is a Ruby medal to award, we run the risk of a stack overflow as our game keeps trying to unlock a Ruby medal that doesn't exist.

The next function is doMedalAlerts:


void doMedalAlerts(void)
{
	if (alertMedal == NULL)
	{
		nextAlert();
	}
	else
	{
		alertRect.x = MAX(alertRect.x - app.deltaTime * 24, SCREEN_WIDTH - alertRect.w);

		alertTimer -= app.deltaTime;

		if (alertTimer <= 0)
		{
			alertMedal->notify = 0;

			resetAlert();
		}
	}
}

This function is responsible for either selecting the next medal alert to show or displaying the current one. We start by testing if alertMedal is NULL. If so, we'll call nextAlert (we'll see more on this next). If it's not NULL, we'll want to slide it in from the right-hand side of the screen. We start by subtracting 24 from alertRect's `x`, using the MAX macro to limit it to the screen's width, less the width (w) of alertRect. In other words, we'll be decreasing the value of `x`, but not so much that the alert fully leaves the right-hand edge of the screen.

We also decrease the value of alertTimer. Once its value has reached 0 or less, we'll set alertMedal's `notify` to 0 and call resetAlert. This is basically the timer for how long the alert will be displayed before it vanishes from the screen. Setting the Medal's `notify` to 0 means that it is no longer a candidate for displaying.

The next function is nextAlert:


static void nextAlert(void)
{
	int i, w, h, l;
	Medal *m;

	for (m = game.medalsHead.next ; m != NULL ; m = m->next)
	{
		if (m->notify != 0)
		{
			if (alertMedal == NULL || m->notify < alertMedal->notify)
			{
				alertMedal = m;
			}
		}
	}

	if (alertMedal != NULL)
	{
		playSound(SND_MEDAL, -1);

		app.fontScale = 1.0;

		calcTextDimensions(alertMedal->title, &w, &h);

		w += 125;

		alertRect.w = MAX(w, alertRect.w);

		memset(abbrevDescription, 0, sizeof(abbrevDescription));

		l = strlen(alertMedal->description);

		for (i = 0 ; i < l ; i++)
		{
			calcTextDimensions(abbrevDescription, &w, &h);

			if (w < alertRect.w)
			{
				strncat(abbrevDescription, &alertMedal->description[i], 1);
			}
			else
			{
				strcat(abbrevDescription, "...");
				break;
			}
		}
	}
}

This is another essential function, and one that looks for the next Medal to be displayed. We start by looping through all our Medals (assigned to a variable called `m`), and looking for any that have a notify value of greater than 0. If we find one, we'll want to compare its `notify` value to the current alertMedal's `notify`. If alertMedal is NULL or alertMedal's `notify` value is greater than `m`'s, we'll assign alertMedal to `m`. Basically, we're looking for a Medal with the lowest non-zero notify value to display next.

We'll then check if alertMedal is not NULL, meaning we've got a Medal to display. We'll play a sound, then use calcTextDimensions with the Medal's `title`, to work out the length of the alert box. Note that we're assuming the length of the title here will be sensible, as we're not limiting it in any way; a long title could therefore produce a very long box. We're then adding 125 to `w` (the width of the box) for padding. We're then checking which is greater: `w` or alertRect's `w` (that is defaulted to a value of 475 in resetAlert). The idea behind this is that we want to ensure the alert is at least 475 pixels wide; a short title would make things look a bit odd.

Next, we're going to add in the medal description to the alert. As the description could be longer than the title and overflow the box, we're going to add in one character at a time and test the length of the text we want to produce, until we either add in all the text or we reach the edge of the alert box. To start with, we're memsetting a variable called abbrevDescription (a char array of length MAX_DESCRIPTION_LENGTH + 4), into which we'll be copying our text. We're then using strlen to get the length of the Medal's description before then using a for-loop to iterate over all the characters. For each iteration of the loop, we're using calcTextDimensions to see if the width of abbrevDescription (assigned to a variable called `w`) is less than alertRect's `w` (its width). If so, we're using strncat to append the single character at description's `i` position to abbrevDescription. If it doesn't fit, we're going to use strcat to append an ellipsis (...) to the end of the string, and then call break to exit the loop.

This will ultimately mean that abbrevDescription will contain the full description or an abbreviated one (hence the name). Long descriptions will be neatly clipped and not overflow our alert box.

Next, we have resetAlert. It's a rather simple function:


static void resetAlert(void)
{
	alertTimer = FPS * 3;
	alertMedal = NULL;

	alertRect.x = SCREEN_WIDTH;
	alertRect.y = 10;
	alertRect.w = 475;
	alertRect.h = 90;
}

All we're doing here is setting alertTimer to 3 seconds, setting the alertMedal to NULL, and then resetting the alertRect's `x`, `y`, `w`, and `h` values to SCREEN_WIDTH, 10, 475, and 90 respectively, to ensure the alert is drawn correctly. Setting alertRect's `x` to the value of SCREEN_WIDTH means it always start off at the right-hand side of the display.

We now come to drawMedalAlert:


void drawMedalAlert(void)
{
	if (alertMedal != NULL)
	{
		drawRect(alertRect.x, alertRect.y, alertRect.w, alertRect.h, 0, 0, 0, 255);
		drawOutlineRect(alertRect.x, alertRect.y, alertRect.w, alertRect.h, 255, 255, 255, 255);

		blitAtlasImage(medalTextures[alertMedal->type], alertRect.x + 45, alertRect.y + 45, 1, SDL_FLIP_NONE);

		drawText(alertMedal->title, alertRect.x + 90, alertRect.y + 5, 255, 255, 255, TEXT_ALIGN_LEFT, 0);

		app.fontScale = 0.7;

		drawText(abbrevDescription, alertRect.x + 90, alertRect.y + 45, 255, 255, 255, TEXT_ALIGN_LEFT, 0);

		app.fontScale = 1.0;
	}
}

This function is what draws our alert. We first check to see if alertMedal is not NULL, meaning that we have a medal alert to display. We then call drawRect and drawOutlineRect, feeding in our alertRect's `x`, `y`, `w`, and `h`, to draw the alert's background (black) and frame (white). Next, we draw the medal's texture, according to its `type`. We do so by rendering the AtlasImage in the medalTextures array at the index of `type`; other medal images when loaded during initMedals align with the type of medal in our enum, so they match up nicely. Our rendered medal texture is aligned to the left-hand side of the alert panel.

Next, we draw the alertMedal's `title` text. We draw it starting 90 pixels to the right of the left-hand edge, so that it doesn't render over the medal texture. After that, we reduce the font scale to 0.7 and render the text of abbrevDescription. This, we draw below the title. Notice something - as stated earlier, when rendering the abbreviate description we're drawing it at a scaled font size of 0.7. However, when we measured it for the abbreviation, we used a font scale of 1.0. This is done because it works a little better, and we don't have to get overly fussy with our edge calculations.

That's all our medal logic and rendering done. The last thing we need to cover in the function is loading the medals themselves. loadMedals covers this:


static void loadMedals(void)
{
	Medal *m, *prev;
	cJSON *root, *node;
	char *text;

	prev = &game.medalsHead;

	text = readFile("data/medals/medals.json");

	root = cJSON_Parse(text);

	for (node = root->child ; node != NULL ; node = node->next)
	{
		m = malloc(sizeof(Medal));
		memset(m, 0, sizeof(Medal));
		prev->next = m;
		prev = m;

		m->type = lookup(cJSON_GetObjectItem(node, "type")->valuestring);
		STRCPY(m->id, cJSON_GetObjectItem(node, "id")->valuestring);
		STRCPY(m->title, cJSON_GetObjectItem(node, "title")->valuestring);
		STRCPY(m->description, cJSON_GetObjectItem(node, "description")->valuestring);

		if (cJSON_GetObjectItem(node, "hidden"))
		{
			m->hidden = 1;
		}
	}

	cJSON_Delete(root);

	free(text);
}

A standard JSON data loading function. We're loading our JSON and then looping through the array of objects, creating a Medal for each one, and setting the fields. The created Medals are added to our Game's linked list. We're also testing if the "hidden" field exists in the JSON object. If so, we're setting the Medal's `hidden` value to 1. In our system, this field is optional, and its presence in the JSON means that the Medal will be flagged as hidden (regardless of the value in the JSON).

(notice when it comes to getting the medal `type`, we're calling a function named lookup (see the lookup tutorial for more details on how this works).

That's medals.c all covered. We can now look at the demo application we've built to make use of it.

Starting with game.c, we have one simple function - initGame:


void initGame(void)
{
	memset(&game, 0, sizeof(Game));
}

initGame simply memsets our `game` object (global to the application). We'll be adding more to this file in future.

Moving on to demo.c now. This is where we handle all the logic and rendering of our application.

The first function is initDemo:


void initDemo(void)
{
	spaceCount = 0;

	app.delegate.logic = logic;

	app.delegate.draw = draw;
}

We're setting a variable called spaceCount to 0. This variable will be used to count how many times we've pressed the Space bar. We're also setting app.delegate's `logic` and `draw` function pointers to the `logic` and `draw` functions of demo.c.

Looking at `logic` next:


static void logic(void)
{
	if (app.keyboard[SDL_SCANCODE_1])
	{
		app.keyboard[SDL_SCANCODE_1] = 0;

		awardMedal("key1");
	}

	if (app.keyboard[SDL_SCANCODE_RETURN])
	{
		app.keyboard[SDL_SCANCODE_RETURN] = 0;

		awardMedal("keyReturn");
	}

	if (app.keyboard[SDL_SCANCODE_SPACE])
	{
		app.keyboard[SDL_SCANCODE_SPACE] = 0;

		if (++spaceCount >= 3)
		{
			awardMedal("keySpace");
		}
	}
}

We're testing three keys. Firstly, we're testing if 1 has been pressed on the keyboard. If so, we're clearing the key, and then calling awardMedal, passing over "key1". This means that we'll be awarding a medal when the user presses 1. According to our Medals logic, if the medal with an id of "key1" hasn't been awarded yet, the alert will show.

We're then testing to see if Return has been pressed. If so, we're calling awardMedal, this time passes over "keyReturn".

Finally, we're testing if Space has been pressed. Notice that we're incrementing the value of spaceCount, testing if the value is 3 or greater, and then calling awardMedal, passing over "keySpace". So, we must press Space 3 times in order to unlock the keySpace medal.

That's all that's needed in our logic to process our medal unlocking. Pretty simple, eh?

The `draw` function follows:


static void draw(void)
{
	Medal *m;
	int y, r, g, b;

	y = 200;

	for (m = game.medalsHead.next ; m != NULL ; m = m->next)
	{
		r = g = b = 128;

		if (m->awardDate > 0)
		{
			r = g = 255;
			b = 0;
		}

		drawText(m->title, 200, y, r, g, b, TEXT_ALIGN_LEFT, 0);

		drawText(m->description, 240, y + 45, r, g, b, TEXT_ALIGN_LEFT, 0);

		y += 135;
	}
}

This function is straightforward. All we're doing is looping through the game medals and printing out their `title` and `description` on the screen. We're defaulting the text to a light grey (setting the values of `r`, `g`, `b` to 128). We're then testing the medal's awardDate. If it's greater than 0 (meaning, its been unlocked), we're changing `r` and `g` to 255, and `b` to 0, so that we render the text in yellow.

Just a couple more functions left to cover. Moving across to init.c, let's look at initGameSystem:


void initGameSystem(void)
{
	srand(time(NULL));

	initTextures();

	initAtlas();

	initFonts();

	initSound();

	initLookups();

	initGame();

	initMedals();
}

As well as our usual init calls, we're also calling initGame and initMedals, that we defined earlier.

Finally, we come to main.c, and our main function:


int main(int argc, char *argv[])
{
	long then;

	memset(&app, 0, sizeof(App));

	initSDL();

	initGameSystem();

	initDemo();

	atexit(cleanup);

	nextFPS = SDL_GetTicks() + 1000;

	while (1)
	{
		then = SDL_GetTicks();

		prepareScene();

		doInput();

		logic();

		doMedalAlerts();

		app.delegate.draw();

		drawMedalAlert();

		presentScene();

		/* allow the CPU/GPU to breathe */
		SDL_Delay(1);

		app.deltaTime = LOGIC_RATE * (SDL_GetTicks() - then);

		doFPS();
	}

	return 0;
}

It's in the main loop that we're calling doMedalAlerts and drawMedalAlert. The reason we're doing this here is because we always want to process and draw our medals, regardless of what happening in the application. This means, for example, that we don't need to worry about explicitly processing them on a title screen, during gameplay, and in other places. They'll always be processed and always be drawn, almost as if they are working at a system level.

And there we have it. Our Medal system is more or less done. We can load medals, unlock them, and display alerts.

In our next part, we'll look at how to integrate this into gameplay.

Purchase

The source code for all parts of this tutorial (including assets) is available for purchase:

From itch.io

It is also available as part of the SDL2 tutorial bundle:

Directly

If you do not wish to create an itch.io account, you can also purchase the tutorial bundle using PayPal, and then download the tutorials directly from the main tutorials page.

SDL2_Tutorials.tar.gz 56.76MB 23rd April 2022

Click here to see the list of files in the archive

Mobile site