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
SDL 1 tutorials (outdated)

Latest Updates

SDL2 Shooter 2 tutorial
Tue, 13th July 2021

SDL2 Widget tutorial
Fri, 18th June 2021

SDL2 Adventure tutorial
Tue, 8th June 2021

New tutorials
Tue, 11th May 2021

Orb source code
Sun, 25th April 2021

All Updates »

Tags

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

Books


Firmware

HF-Tech's chips have changed the world. Embedded into the heads of over 90% of the world's population, they have cured autism, dementia, provided intelligence boosts, and helped to ease some of the more mundane tasks in life. Daniel Blair, hacker and Workshop member, however is not convinced that everything is as rosy as it seems. But is he looking in all the wrong places..?

Click here to learn more and read an extract!

« Back to tutorial listing

— Creating a vertical shoot 'em up —
Part 9: Finishing touches

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

Introduction

Our main game is done, meaning all we need to do is throw in the finishing touches (and make a few gameplay tweaks). In this final part, we'll be looking at what we've added to complete the experience. Note that due to adding the widget system, there have been elements of refactoring. We'll not be looking at the widgets, the music, or the sound, as these have been seen in previous tutorials and to cover them all here would mean a very long final part. Instead, we'll be focusing on the specifics of this tutorial: the title screen, the highscore table, and the save routine.

Extract the archive, run make, and then use ./shooter2-09 to run the code. You will see a window open like the one above. Use the Up and Down arrow keys with Space or Return to navigate the menu. Use the Left and Right keys to change the volume values of sound and music, when the widgets are highlighted. To change a control, highlight the control then press Return or Space, followed by the key you wish to use for the control. Pressing Escape will cancel the change. Play the game as usual, and enter a highscore if you manage to get one. Games are saved to the file save.json in the same directory as the game itself. When you're finished, close the window to exit or select Exit from the title screen.

Inspecting the code

Even with skipping over the widgets, sound, and music, there is still quite a lot to get through in this final part. Let's look at the changes to defs.h first:


enum {
	CONTROL_LEFT,
	CONTROL_RIGHT,
	CONTROL_UP,
	CONTROL_DOWN,
	CONTROL_FIRE,
	CONTROL_MAX
};

We've added in a new enum to handle our controls, having one for each direction, as well as the fire control. These will be used during our configuration, as well as our game. We've also made some changes to structs.h:


typedef struct {
	Highscore highscores[NUM_HIGHSCORES];
	int controls[CONTROL_MAX];
	int soundVolume;
	int musicVolume;
} Game;

Our Game struct has seen three new fields added to it: controls is an array of ints that will be used to help with control configuration, while soundVolume and musicVolume will hold the details of our sound and music volumes. We'll see all these used a bit later on.

Now onto the main code. We'll start by looking at the title screen. This is defined in title.c. There are a good number of functions to cover, so we'll start with initTitle:


void initTitle(void)
{
	if (!wasInit)
	{
		wasInit = 1;

		logoSDL2 = getAtlasImage("gfx/sdl2.png", 1);
		logoShooter[0] = getAtlasImage("gfx/shooter-1.png", 1);
		logoShooter[1] = getAtlasImage("gfx/shooter-2.png", 1);
		logo2 = getAtlasImage("gfx/2.png", 1);

		setupWidgets();
	}

	showScores = 0;

	showTimer = SHOW_TIMEOUT;

	app.activeWidget = getWidget("start", "title");

	stopChannel(-1);

	app.delegate.logic = logic;
	app.delegate.draw = draw;
}

This is the first function that is called in `main` (in main.c) once everything has been setup. It replaces the call to initStage from that part of the code. The first thing that happens in initTitle is we're testing a flag called wasInit. If it's false (0) we'll know we want to do some initial setup. Our title logo is split into 4 parts, so that it can fit into our texture atlas. We're grabbing all 4 parts (the word 'shooter' is divided in 2) and assigning them to various fields. We're also making a call to setupWidgets, a local function that sets up our title screen's widgets. The wasInit flag is also set to 1, to tell the code not to bother to do this next time we call initTitle.

We're then setting another flag called showScores to 0. The showScores flag is used to flip between displaying the title itself and the highscore table. This is used in conjunction with showTimer, which we're setting to SHOW_TIMEOUT (defined as 7 seconds in title.h). We're then setting our currently active widget to the "Start" widget and telling all our sound channels to stop playing. We have a sound effect that plays on a loop when the Supply Ship shows up, so this is needed in cases when the player is killed while it is active or quits the game. Finally, we're setting the app delegate's `logic` and `draw` function pointers.

We'll move straight onto the `logic` function now:


static void logic(void)
{
	reveal = MIN(reveal + app.deltaTime, 500);

	showTimer = MAX(showTimer - app.deltaTime, 0);

	if (showTimer == 0)
	{
		showScores = !showScores;

		showTimer = SHOW_TIMEOUT;
	}

	doBackground();

	if (!showScores)
	{
		if (app.keyboard[SDL_SCANCODE_UP] || app.keyboard[SDL_SCANCODE_DOWN])
		{
			showTimer = SHOW_TIMEOUT;
		}

		doWidgets("title");
	}
	else
	{
		if (app.keyboard[SDL_SCANCODE_RETURN] || app.keyboard[SDL_SCANCODE_SPACE])
		{
			app.keyboard[SDL_SCANCODE_RETURN] = app.keyboard[SDL_SCANCODE_SPACE] = 0;

			showTimer = SHOW_TIMEOUT;

			showScores = 0;
		}
	}
}

You'll notice when the game first starts that the title logo parts reveal themselves from top to bottom. This is controlled by the `reveal` variable (initially set to 0). Here, we're increasing the value of the variable and limiting it to 500, to stop is eventually becoming too high and wrapping around. Next, we're decreasing the showTimer varaiable and limiting it to 0. If the value hits 0, we're going to flip our showScores flag. As we're setting showScores to the inverse of showScores, this means it will toggle between 0 and 1. This means that after our showTimer has hit 0, we'll be swapping between showing the title and showing the highscore list. With that done, we're resetting showTimer to SHOW_TIMEOUT.

We're calling a function called doBackground next. This is part of some refactoring that was done to drive the background and stars, as the logic is shared in a few places in the code. It's effectively the doBackground and doStars calls that existed in stage.c.

We're then testing the showScores flag. If it's 0 (we're displaying the title logo itself), we're going to check if the player is pressing the Up or Down arrow keys to navigate the menu. If so, we're going to reset our showTimer to SHOW_TIMEOUT. This is important in order to stop the title screen from flipping over to the highscores while we're interacting with it. We're also telling the game to handle our title screen widgets. If showScores is 1, meaning we're displaying the highscore table, we're going to check if the player has pressed Return or Space. If so, we're going to zero those two keys, reset the showTimer, and then set showScores to 0. In effect, pressing Return or Space on the highscore display will return to the logo display. We're zeroing the key presses so as to avoid invoking the title widgets right away.

That's our logic done, so we can look at how the rendering is all handled. Our `draw` function is naturally where we're doing this:


static void draw(void)
{
	drawBackground();

	if (!showScores)
	{
		drawTitle();
	}
	else
	{
		drawScores();
	}

	app.fontScale = 0.5;

	drawText("Copyright 2021, Parallel Realities. All Rights Reserved.", SCREEN_WIDTH / 2, SCREEN_HEIGHT - 30, 160, 160, 160, TEXT_ALIGN_CENTER, 0);

	app.fontScale = 1.0;
}

The first call to drawBackground is part of the shared background logic and rendering refactoring that now lives in background.c. Like doBackground, this function is called in a number of places. We're then testing our showScores flag to determine what we want to draw. If showScores is 0, we're going to call drawTitle, to render our logos and widgets. If it's 1, we're going to call drawScores to render our highscore list.

drawTitle is a simple function:


static void drawTitle(void)
{
	drawLogo(logoSDL2, (SCREEN_WIDTH - logoSDL2->rect.w) / 2, 150);

	drawLogo(logoShooter[0], (SCREEN_WIDTH / 2) - logoShooter[0]->rect.w, 275);

	drawLogo(logoShooter[1], (SCREEN_WIDTH / 2), 275);

	drawLogo(logo2, (SCREEN_WIDTH - logo2->rect.w) / 2, 400);

	drawWidgets("title");
}

We're basically drawing the logo parts that we grabbed in initTitle, as well as the widgets. Each logo part is rendered using a call to drawLogo (more on this in a bit). The "SDL2" and "2" logos are drawn centered horizontally, by subtracting their widths from the screen width and dividing by 2. For the two "Shooter" parts, we're drawing the first part at the horizontal center, less the value of the logo's width. For the second part, we're rendering at the horizontal center. This will result in the Shooter logo parts rendering alongside one another, centered around the middle of the screen.

Our drawLogo function is what handles the revealing:


static void drawLogo(AtlasImage *atlasImage, int x, int y)
{
	SDL_Rect src, dest;

	src = atlasImage->rect;
	src.h = MIN(src.h, reveal);

	dest.x = x;
	dest.y = y;
	dest.w = atlasImage->rect.w;
	dest.h = src.h;

	SDL_RenderCopyEx(app.renderer, atlasImage->texture, &src, &dest, 0, NULL, SDL_FLIP_NONE);
}

We're passing in to the function the atlasImage we want to use, and the `x` and `y` coordinates we want to draw at. We're then copying the atlasImage's `rect` data (the coordinates of the image in the texture atlas) into another SDL_Rect called `src`. After that, we're updating `src`'s `h` (height) value to the smaller value between `src`'s `h` and `reveal`, using the MIN macro. In other words, if the value of `reveal` is less than the value of `src`'s `h`, we'll use that value. We're then setting up an SDL_Rect call `dest`, assigning its `x` and `y` values as the `x` and `y` we passed into the function, its `w` (width) as the atlasImage's width, and its `h` (height) as the same value as `src`'s `h`. We're then throwing this information at SDL_RenderCopyEx, to tell it to draw the image.

In short, we're clipping the image's height to the value of `reveal`. As `reveal` increases, more of the image is displayed.

That's the title logo handled, so let's look at how we're rendering our highscore table. We're doing this in drawScores:


static void drawScores(void)
{
	int i, y, r, g, b;
	char text[16];

	app.fontScale = 1.5;

	drawText("TOP 10 SHOOTERS", SCREEN_WIDTH / 2, 70, 255, 255, 255, TEXT_ALIGN_CENTER, 0);

	app.fontScale = 1.0;

	y = 200;

	for (i = 0 ; i < NUM_HIGHSCORES - 1 ; i++)
	{
		r = g = b = 255;

		if (&game.highscores[i] == newHighscore)
		{
			b = 0;
		}

		memset(text, 0, sizeof(text));

		sprintf(text, "%d.", i + 1);

		drawText(text, 125, y, r, g, b, TEXT_ALIGN_LEFT, 0);

		drawText(game.highscores[i].name, 225, y, r, g, b, TEXT_ALIGN_LEFT, 0);

		sprintf(text, "%03d", game.highscores[i].score);

		drawText(text, 675, y, r, g, b, TEXT_ALIGN_RIGHT, 0);

		y += 65;
	}
}

The first thing we're doing is increasing the size of our font to 1.5, to make it a bit larger, rendering the "TOP 10 SHOOTERS" text in the middle of the screen, and then resetting the font size. We're then setting a variable called `y` to 200, which is where we'll start rendering our scores. After that, we're setting up a for-loop to draw all our scores. Note how we're using NUM_HIGHSCORES - 1. NUM_HIGHSCORES is defined as 11, but we only want to draw the first 10 scores. We're then setting three variable called `r`, `g`, `b` to 255. These are the red, green, blue (RGB) values that we'll be drawing our text in. By default, we'll be rendering all the scores in white. After this, we're testing each score structure against a variable called newHighscore (a static variable in title.c) to see if the two are equal (reference testing). If they are, we'll set the value of `b` (blue) to 0, so that the text renders in yellow (since `r` and `g` will still be 255). This is done in order to highlight the score a player just earned, so they can see it after entering their name.

We're then rendering each score line, using the set RGB values. We're first rendering the position (using sprintf with a char array called `text`), then the name associated with the highscore, then the score itself, formatted as 3 digits. We're finally increasing the value of `y` to render the next score below the current one.

That's almost it for title.c. We'll take a look at one more function quickly that's associated with the "Start" widget:


static void start(void)
{
	reveal = 500;

	newHighscore = NULL;

	initStage();
}

When invoked, the Start widget will call the `start` function. It will set the value of the `reveal` variable to 500, so that the logo is fully revealed, NULL the newHighscore pointer so that the recent highscore is no longer highlighted, and then call initStage to start the game.

Highscores is the next major thing that we've added to this part. We've done all the work for this in highscores.c, which before now only featured a handful of functions. We'll look at what happens when a player earns a highscore, starting with initHighscoreEntry:


void initHighscoreEntry(void)
{
	game.highscores[NUM_HIGHSCORES - 1].score = stage.score;

	app.activeWidget = getWidget("name", "highscore");

	// force input focus
	app.keyboard[SDL_SCANCODE_SPACE] = 1;

	if (!wasInit)
	{
		wasInit = 1;

		setupWidgets();
	}

	stopChannel(-1);

	app.delegate.logic = logic;
	app.delegate.draw = draw;
}

When a player gets a highscore, we'll assign their score to the final entry in the highscore table (entry #11). We're making use of an input text widget for entering the player name, so we'll call getWidget to grab the widget and make it App's activeWidget. Following this, we'll set the Space key as having been pressed. Our InputWidgets rely on the user having pressed Space or Return when they are highlighted, in order to allow for text input. Manually setting the Space key as being pressed is a small hack to force the input to happen. With that done, we're checking if we need to setup our widget by testing the wasInit flag, stopping all the sound channels playing (again, to turn off the looping sound effect), and setting up our `logic` and `draw` delegates.

Our `logic` function is simple enough to understand:


static void logic(void)
{
	doBackground();

	doWidgets("highscore");
}

We're merely updating the background by calling doBackground and also processing all our "highscore" widgets.

The `draw` function is just as simple:


static void draw(void)
{
	drawBackground();

	app.fontScale = 1.25;

	drawText("Congratulations!", SCREEN_WIDTH / 2, 100, 255, 255, 255, TEXT_ALIGN_CENTER, 0);

	drawText("You've earned a highscore!", SCREEN_WIDTH / 2, 160, 255, 255, 255, TEXT_ALIGN_CENTER, 0);

	app.fontScale = 1.0;

	drawText("Enter your name below:", SCREEN_WIDTH / 2, 300, 255, 255, 255, TEXT_ALIGN_CENTER, 0);

	drawWidgets("highscore");
}

We're calling drawBackground to render our background, and drawing a series of text strings at various sizes using our drawText function. Finally, we're calling drawWidgets to render our "highscore" widgets. This will consist only of the InputWidget.

Our InputWidget makes use of a function called `name` for handing its logic (when the player has pressed Return or Escape after entering text):


static void name(void)
{
	InputWidget *iw;
	int i, score;
	Highscore *newHighscore = NULL;

	iw = (InputWidget*) app.activeWidget->data;

	if (strlen(iw->text) > 0)
	{
		STRCPY(game.highscores[NUM_HIGHSCORES - 1].name, iw->text);
	}
	else
	{
		STRCPY(game.highscores[NUM_HIGHSCORES - 1].name, "ANONYMOUS");
	}

	score = game.highscores[NUM_HIGHSCORES - 1].score;

	qsort(game.highscores, NUM_HIGHSCORES, sizeof(Highscore), highscoreComparator);

	for (i = NUM_HIGHSCORES - 1 ; i >= 0 ; i--)
	{
		if (game.highscores[i].score == score)
		{
			newHighscore = &game.highscores[i];
		}
	}

	saveGame();

	initTitleScoresDisplay(newHighscore);
}

The first thing we're doing is grabbing the InputWidget from the app's activeWidget `data` field. We're then testing the length of the text that has been input. If it's greater than 0, we're copying the text into highscore 11's `name` field. Otherwise, we're setting the name to "ANONYMOUS" (note that we're not concerned about someone entering a name as pure spaces). With the name set, we're then making a copy of the score at positon #11. The reason we're setting the player's highscore into positon 11 is so that we can simply use `qsort` to reorder the score table. This cuts down on the micromanagement of reordering the score table manually, looking for the correct place to enter the score, and then shifting all the elements about. After calling `qsort`, the score in position 11 will then be moved into the correct place. What we want to do next is find out which highscore structure holds the score that was just entered. We can't grab a reference to it before using `qsort` and expect to then find it in the right place; our reference to element #11 will always point to element #11. We therefore walk through our array in reverse order, looking for the score that matches the one entered. When we find it, we'll assign it to a pointer called newHighscore.

Our score has now been entered into the table, has been ordered into the correct position, and we have a reference to the structure. We call saveGame to save out the scores and game configuration, and then call a function called initTitleScoresDisplay, passing in the newHighscore reference. initTitleScoresDisplay actually lives in title.c, so we'll quickly return to that file to see how that works:


void initTitleScoresDisplay(Highscore *highscore)
{
	newHighscore = highscore;

	initTitle();

	showScores = 1;
}

We're assigning newHighscore to value of the Highscore reference (`highscore`) we've passed in (you should recall seeing newHighscore being used in the highscore display earlier). We're then calling initTitle to setup the title screen as normal, but setting showScores to 1. This will mean that we're going to show the highscore table right away, rather than the logo.

Now, let's look at game.c. Again, this is another file that was quite bare before this update. The sole function, initGame, used to call initHighscores and do nothing more. game.c now does a lot more. We'll start with looking at initGame:


void initGame(void)
{
	initHighscores();

	game.soundVolume = MIX_MAX_VOLUME;

	game.musicVolume = MIX_MAX_VOLUME;

	game.controls[CONTROL_LEFT] = SDL_SCANCODE_LEFT;

	game.controls[CONTROL_RIGHT] = SDL_SCANCODE_RIGHT;

	game.controls[CONTROL_UP] = SDL_SCANCODE_UP;

	game.controls[CONTROL_DOWN] = SDL_SCANCODE_DOWN;

	game.controls[CONTROL_FIRE] = SDL_SCANCODE_LCTRL;

	loadGame();

	setSoundVolume(game.soundVolume);

	setMusicVolume(game.musicVolume);
}

We're still calling initHighscores, but now we're setting the defaults for Game's various fields. By default, our sound and music volumes will be set to maximum (MIX_MAX_VOLUME), and our game's controls will default to the arrow keys, plus the left control key to fire. With this done, we're calling a function called loadGame, then finally updating our sound and music volumes (via setSoundVolume and setMusicVolume) with the values that have been set.

The reason we're setting the defaults and then calling loadGame is that the save game file might not exist. Therefore, nothing is changed and the defaults are used. In effect, loading the game overrides the default values we've just set. Our loadGame function itself is quite simple:


static void loadGame(void)
{
	int i;
	char *data;
	cJSON *root, *node;

	data = readFile(SAVE_GAME_FILENAME);

	if (data != NULL)
	{
		root = cJSON_Parse(data);

		node = cJSON_GetObjectItem(root, "controls");
		game.controls[CONTROL_LEFT] = cJSON_GetObjectItem(node, "left")->valueint;
		game.controls[CONTROL_RIGHT] = cJSON_GetObjectItem(node, "right")->valueint;
		game.controls[CONTROL_UP] = cJSON_GetObjectItem(node, "up")->valueint;
		game.controls[CONTROL_DOWN] = cJSON_GetObjectItem(node, "down")->valueint;
		game.controls[CONTROL_FIRE] = cJSON_GetObjectItem(node, "fire")->valueint;

		node = cJSON_GetObjectItem(root, "volumes");
		game.soundVolume = MAX(MIN(cJSON_GetObjectItem(node, "sound")->valueint, MIX_MAX_VOLUME), 0);
		game.musicVolume = MAX(MIN(cJSON_GetObjectItem(node, "music")->valueint, MIX_MAX_VOLUME), 0);

		i = 0;

		for (node = cJSON_GetObjectItem(root, "highscores")->child ; node != NULL ; node = node->next)
		{
			STRCPY(game.highscores[i].name, cJSON_GetObjectItem(node, "name")->valuestring);
			game.highscores[i].score = cJSON_GetObjectItem(node, "score")->valueint;

			i++;
		}

		cJSON_Delete(root);

		free(data);
	}
}

We're first attempting to read a file called "save.json" (from the define SAVE_GAME_FILENAME). If the data returned from this function isn't NULL (which it will be if the file doesn't exist), we'll parse it into a JSON object using cJSON_Parse, assign it to a variable called `root`, and then set to work extracting the data we want.

We'll start by extracting a JSON object call "controls" from `root`, assigning it to a variable called `node`. This object holds our control configuration. We'll look up items in the `node` JSON object called "left", "right", "up", "down", and "fire" and assign the int value of each to the appropriate index in Game's `controls` array. The ints are equvialent to the values of SDL_SCANCODEs for the keys they represent.

Next, from the `root` object we'll grab an object called "volumes" and once again assign it to `node`. This holds the information about our sound and music volumes. For our game's soundVolume and musicVolume, we'll grab items from `node` called "sound" and "music". One thing we're doing before assigment is using the MIN and MAX macros to ensure the values don't go below 0 or above MIX_MAX_VOLUME.

We're then moving onto fetching out highscore data. We're setting a variable called `i` to 0, then grabbing a JSON array called "highscores" from the root. Using a for-loop, we're able to fetch all the child objects from the "highscores" JSON array, and copy the "name" and "score" values into our game's `highscores` array, incrementing `i` as we go, to move onto the next highscore entry. Note that we're not performing any error checking here; we're assuming that there will be no more than 11 highscores to fetch.

With our configuration and highscores loaded, we can then delete the JSON object by calling cSJON_Delete and passing in `root`, and also free the text data that was loaded.

The other function in game.c is saveGame. We've already seen this being called when a player enters a highscore. Again, this function is rather simple:


void saveGame(void)
{
	int i;
	cJSON *root, *controls, *volumes, *highscores, *highscore;
	char *out;

	controls = cJSON_CreateObject();
	cJSON_AddNumberToObject(controls, "left", game.controls[CONTROL_LEFT]);
	cJSON_AddNumberToObject(controls, "right", game.controls[CONTROL_RIGHT]);
	cJSON_AddNumberToObject(controls, "up", game.controls[CONTROL_UP]);
	cJSON_AddNumberToObject(controls, "down", game.controls[CONTROL_DOWN]);
	cJSON_AddNumberToObject(controls, "fire", game.controls[CONTROL_FIRE]);

	volumes = cJSON_CreateObject();
	cJSON_AddNumberToObject(volumes, "sound", game.soundVolume);
	cJSON_AddNumberToObject(volumes, "music", game.musicVolume);

	highscores = cJSON_CreateArray();

	for (i = 0 ; i < NUM_HIGHSCORES ; i++)
	{
		highscore = cJSON_CreateObject();
		cJSON_AddStringToObject(highscore, "name", game.highscores[i].name);
		cJSON_AddNumberToObject(highscore, "score", game.highscores[i].score);

		cJSON_AddItemToArray(highscores, highscore);
	}

	root = cJSON_CreateObject();
	cJSON_AddItemToObject(root, "controls", controls);
	cJSON_AddItemToObject(root, "volumes", volumes);
	cJSON_AddItemToObject(root, "highscores", highscores);

	out = cJSON_Print(root);

	writeFile(SAVE_GAME_FILENAME, out);

	cJSON_Delete(root);

	free(out);
}

When saving the game, we'll end up creating the JSON object that we load in the loadGame step. For this, we need to create "controls", "volumes", and "highscores" objects. Let's start from the top.

We're calling cJSON_CreateObject and assigning it to a variable called `controls`. We're then calling cJSON_AddNumberToObject several times, passing in the `controls` variable, an item name, and a value. We're doing so for "left", "right", "up", "down", and "fire", setting the value of the relevant index in Game's `controls` array. In effect, we're creating an entry in our JSON object with a key-value pair for each of our controls. This can later be read by the loadGame function to extract it.

We're next creating a JSON object and assigning it to a variable called `volumes`, to which we're adding two numbers - game's soundVolume and musicVolume, with the keys "sound" and "music" respectively. This object will hold our audio volumes.

Following this, we're creating a JSON array and assigning it to the `highscores` variable. This array will hold all our highscores. We're then using a for-loop to iterate our highscores (0 to NUM_HIGHSCORES). For each one, we're creating a JSON object (as `highscore`), and populating it with the highscores's name and the score itself, using "name" and "score" as the keys. That done, we're adding the `highscore` JSON object to the `highscores` JSON array.

Now with our controls, volumes, and highscores JSON objects and arrays made, we need only add them to the root object. We create one more JSON object, assigning it to a variable named `root`, and then add the `controls`, `volumes`, and `highscores` JSON objects and array to it, using "controls", "volumes", and "highscores" as the keys. The last step is to save the JSON data. We do this by calling cJSON_Print and passing the `root` JSON object into it. This will produce a JSON string, which we assign to a variable named `out`. We then call our writeFile function, passing in the filename (SAVE_GAME_FILENAME - save.json) and the string to save. Finally, we clean everything up by calling cJSON_Delete (passing over `root`) and freeing the string data (out).

That's the core changes and updates for this final part done. Before we wrap up, we'll touch briefly on some of the gameplay changes we made and discuss why they were done. Returning to structs.h, we've added a new field to Fighter:


typedef struct {
	double reload;
	int reloadRate;
	double speed;
	int invokeSidearm;
	int charge;
} Fighter;

`charge` will be used to hold the number of powered-up shots that our fighter can fire when the player collects an (R) power-up pod. The reason for this change is because the player's rate of fire can become very high once they collect 3 tokens. It makes them largely invincible and the bosses are a joke; you just hold fire, dodge a small amount, and the battle is over in a few seconds. Faster, if you have both sidearms. `charge` will count down everytime a shot is fired. Once it hits 0, the power-up's power is exhausted and the player's rate of fire returns to normal.

We can see the power-up charge logic being applied in activatePowerUp, in powerUpPod.c:


static void activatePowerUp(Entity *self, PowerUpPod *p)
{
	Fighter *f;

	switch (p->type)
	{
		// snipped

		case PP_RELOAD_RATE:
			f = (Fighter*) player->data;
			f->reloadRate = MAX(f->reloadRate - 4, MAX_FIGHTER_RELOAD_RATE);
			f->charge = MIN(f->charge + 100, 250);
			break;

		default:
			break;
	}

	self->health = 0;
}

Now, when the player receives a PP_RELOAD_RATE type pod, we'll increase the Fighter's `charge` by 100 (limited to 250). doPlayer in player.c has also been updated to make use of the `charge` field:


static void doPlayer(Entity *self)
{
	Fighter *f;

	f = (Fighter*) player->data;

	// snipped

	if (app.keyboard[game.controls[CONTROL_FIRE]] && f->reload == 0)
	{
		fireBullet();

		f->reload = f->reloadRate;
		f->invokeSidearm = 1;
		f->charge = MAX(f->charge - 1, 0);

		if (f->charge == 0)
		{
			f->reloadRate = INITIAL_RELOAD_RATE;
		}

		playSound(SND_PLAYER_FIRE, CH_PLAYER);
	}

	// snipped
}

Now, when the player fires, we'll decrease the value of the Fighter's `charge`, limiting it to 0. Once it hits 0, we'll reset the Fighter's reloadRate to INITIAL_RELOAD_RATE (16).

So as not to leave the player in the dark about how much `charge` they have remaining, we've added it to the HUD (hud.c), in drawScoreBar:


static void drawScoreBar(void)
{
	char text[16];

	// snipped

	app.fontScale = 0.5;

	sprintf(text, "Charge: %03d", ((Fighter*) player->data)->charge);
	drawText(text, 10, 40, 255, 255, 255, TEXT_ALIGN_LEFT, 0);

	sprintf(text, "Wave: %02d", stage.waveNum);
	drawText(text, SCREEN_WIDTH - 10, 40, 255, 255, 255, TEXT_ALIGN_RIGHT, 0);

	sprintf(text, "Shield: %d", MAX(player->health - 1, 0));
	drawText(text, 10, 70, 255, 255, 255, TEXT_ALIGN_LEFT, 0);

	app.fontScale = 1.0;
}

We're rendering the Fighter's `charge`, as well as information about the wave and remaining shield, in a smaller font.

Another gameplay change that we've made is not to allow the Supply Ships to show up during boss battles. When they did so, it become too easy for the player to fully power themselves up during the encounter (especially during the first battle) and once again do away with the boss in no time. The rest of the game then becomes a cakewalk and all challenge is lost. Restricting the supply ships to the regular alien waves encourages the player to make sure they are prepared for the boss ahead of time. We've tweaked doStage in stage.c to handle this:


static void doStage(void)
{
	nextSupplyShipTimer -= app.deltaTime;

	if (nextSupplyShipTimer <= 0)
	{
		if (stage.boss == NULL)
		{
			initSupplyShip();
		}

		nextSupplyShipTimer = SUPPLY_SHIP_INTERVAL;
	}

	stage.hasAliens = 0;

	stage.boss = NULL;

	doBackground();

	doEntities();

	doBullets();

	doEffects();

	if (player->health <= 0)
	{
		gameOverTimer -= app.deltaTime;

		if (gameOverTimer <= 0)
		{
			if (hasHighscore())
			{
				initHighscoreEntry();
			}
			else
			{
				initTitle();
			}

			resetStage();
		}
	}
	else if (!stage.hasAliens)
	{
		clearDeadEntities();

		if (stage.waveNum % 10 == 0)
		{
			initBoss();
		}
		else
		{
			nextWave();
		}
	}

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

		app.activeWidget = getWidget("resume", "pause");

		paused = 1;
	}
}

Now, once the nextSupplyShipTimer reaches 0, we're first checking if a boss is present by testing Stage's `boss` pointer, and only creating the supply ship if it's NULL. Otherwise, we'll skip the Supply Ship creation and just reset the nextSupplyShipTimer as usual.

The final thing to remark upon is one very important function - checking if the player has a highscore! Once the player is killed and the gameOverTimer has hit 0, we're calling a function named hasHighscore. If this returns true, we'll call initHighscoreEntry to show the highscore entry screen. Otherwise, we'll jump back to the title screen. The hasHighscore function is as simple as you might expect:


static int hasHighscore(void)
{
	int i;

	for (i = 0 ; i < NUM_HIGHSCORES - 2 ; i++)
	{
		if (stage.score >= game.highscores[i].score)
		{
			return 1;
		}
	}

	return 0;
}

All we're doing is checking to see if the player has a highscore greater than or equal to the existing scores. However, one thing to take note of is that we're only testing the first 9 scores. We clearly don't want to test if the player's score is tied with entry #11, as that will never show up. However, we don't want to test score 10 either, as new scores that tie with existing scores will be added after the existing one, due to the sorting method. If someone therefore ties with position #10, they will never be displayed as their score will end up in position #11.

And there you have it, an upgraded sequel to our basic SDL2 Shooter game. We have enemy attack patterns, power-ups, and bosses. It's definitely a worthy sequel, I'm sure you'll agree. A third and final game to complete the trilogy will arrive one day, and will likely focus on free range movement around a space battlefield. For now, I hope that this has been useful and that it will help to answer any questions you had about how to make things like power-ups, bosses, and enemy waves.

Purchase

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

It is also available as part of the SDL2 tutorial bundle (with on-going updates):

Comments

Mobile site