PC Games
• Orb Tutorials
• 2D shoot 'em up Latest Updates
SDL2 Versus game tutorial
Download keys for SDL2 tutorials on itch.io
The Legend of Edgar 1.37
SDL2 Santa game tutorial 🎅
SDL2 Shooter 3 tutorial
Tags • android (3) • battle-for-the-solar-system (10) • blob-wars (10) • brexit (1) • code (6) • edgar (9) • games (43) • lasagne-monsters (1) • making-of (5) • match3 (1) • numberblocksonline (1) • orb (2) • site (1) • tanx (4) • three-guys (3) • three-guys-apocalypse (3) • tutorials (17) • water-closet (4) Books The Attribute of the Strong (Battle for the Solar System, #3) The Pandoran War is nearing its end... and the Senate's Mistake have all but won. Leaving a galaxy in ruin behind them, they set their sights on Sol and prepare to finish their twelve year Mission. All seems lost. But in the final forty-eight hours, while hunting for the elusive Zackaria, the White Knights make a discovery in the former Mitikas Empire that could herald one last chance at victory. |
— A simple turn-based strategy game — Note: this tutorial assumes knowledge of C, as well as prior tutorials.
Introduction There's plenty that our game can do at this point. However, our HUD and UI could use some love. So, in this part we're going to add in messages and some basic controls. Extract the archive, run cmake CMakeLists.txt, followed by make, and then use ./sdl2TBS14 to run the code. You will see a window open like the one above, showing three wizards in a large room, surrounded by walls, as well as a number of ghosts. Play the game as normal. The purple buttons in the bottom-right allow for various actions to be performed From left to right: Prev unit, centre on current unit, next unit, display move range (toggle), display attack range (toggle), end turn. Notice also how messages are displayed for various actions, such as attacking, taking damage, and interacting with items. Once you're finished, close the window to exit. Inspecting the code This part will be fairly long, since we're doing all the HUD work in one go. However, it's not actually very complicated; there's just a lot of it! Starting with structs.h:
We've added a CommandButton struct, to represent the buttons on the HUD that can be clicked. `x`, `y`, `w`, `h` are the location and dimensions of the button, while `active` will specify whether the button is active (used for things like the move and attack ranges, to give visual feedback to the player). `texture` is the button's icon. Next, we have Message:
This is a simple struct to hold the details of a message displayed on the HUD. `text` is the message detail itself, while `color` is the colour of the text. Lastly, we've updated Stage:
We've added in our Messages linked list (as messageHead and messageTail). Now, let's head over to hud.c Buckle up, as this will be a long section, as we detail all the updates to this file. Starting with initHud:
We're loading a bunch of new textures: commandButtonTexture, commandButtonHighlightTexture, and commandButtonActiveTexture. Next, we're setting a variable called `x` to a position on the screen that will allow us to draw all our command buttons (the right-hand side of the screen, less commandButtonTexture's width (w), multiplied by the number of buttons, plus some padding for each). We then enter in a for-loop, to setup our command buttons (commandButtons, an array of size CI_MAX, in hud.c). For each one, we're memsetting it, loading setting its `texture`, its `x`, `y`, `w`, and `h`, and then increasing the value of `x` by the width of commandButtonTexture, plus some padding. This means that each button we create will lie to the right of the previous (we could've gone backward here, but it makes the code a bit harder to read). With our buttons done, we setup the linked list for our message, and set variables called totalMessage, messageNum, and messageTimer to 0. These variables will control our message cycling, as you will have seen when several events occur during the ghosts' turn (such as multiple attacks). We'll see all these in action in a bit. doHud follows:
We're now calling new several functions: doCommandButtons, doMessages, and doHoverEntitySelect. We'll start with doCommandButtons:
This function is where we handle the interactions with our command buttons. We first set a variable called hoverCommandButton to NULL. This is a pointer to the command button that the mouse is currently over, and will draw the yellow rectangle you see. We then enter into a for-loop, to check each button. For each one, we test to see if the mouse pointer is over it (by way of the `collision` function), and assign it as hoverCommandButton. We then test to see if the left mouse button has been pressed. If so, we'll check which command button the player has clicked, via a switch statement. These should all be self-explanatory, as cases are calling many functions that we've seen before (other than CI_END_TURN that calls clearHudMessages). With our buttons checked, we set both CI_SHOW_MOVES and CI_SHOW_ATTACK command buttons `active` flags to 0. We then test the state of Stage's showRange. If its SHOW_RANGE_MOVE, we set CI_SHOW_MOVES's `active` flag to 1. If it's SHOW_RANGE_ATTACK, we set CI_SHOW_ATTACK's `active` flag to 1. The reason we do this is to keep things consistent with the rest of the game. Since the player can also cycle the units' action by clicking on them, we need the UI to reflect this state probably. This step helps to keep things in sync. That's doCommandButtons handled. As you can see, we're just checking if we've clicked on a button, and are calling various (already existing) functions in response. Now, let's look at doMessages:
This function will process our messages, cycling them at an interval. We first test to see how many total messages we have (totalMessages). If it's more than 0, we'll decrease the value of messageTimer. Once that falls to 0 or less, we'll increase the value of messageNum, and also move to the next message in our linked list. currentMessage points to a message in our linked list, so updating currentMessage to currentMessage's `next` will move along the list. We next check to see we've not reached the end of the list, by testing if currentMessage is NULL. If so, we'll return to the start of the list and also set messageNum to 1. Finally, we'll update messageTimer to FPS * 1.5, so that each message is displayed for one-and-a-half seconds. In short, this function will cycle our messages by moving along our message linked list, at a fixed interval. messageNum is used in the display of the messages, as we'll see in a little while. Next, we come to addHudMessage:
This function is quite similar to addDamageText, in that it takes a formatted string. It also takes RGB values, so we can colour the message. We malloc and memset a Message (as `m`) and add it to our linked list, then set all the Message data (`text` and `color`). Next, we test if totalMessages is 0 (meaning this is the first message in the list). If so, we'll set currentMessage to point at `m`, and set messageNum to 1, so that we can start displaying the messages from the beginning. Finally, we increment the value of totalMessages, so we know how many messages we currently have. clearHudMessages is up next:
A simple function. This just empties our messages linked list, resets the linked list, and sets totalMessages and messageNum to 0. So, yes, it just clears all our HUD messages and resets the state! doHoverEntitySelect follows:
This function will set Stage's hoverEntity to the entity at the map location that the mouse is currently hovering over. We're using getEntityAt here, to ensure that a solid entity will take priority. That's our logic steps for the HUD down, so we can now move onto the rendering phase. Starting with drawHud:
We're now calling a few new functions: drawMessage, drawCommandButtons, and drawHoverEntityInfo. These functions will only be called if Stage's `animating` flag isn't set. Additionally, we're only calling drawSelectedTile if we're not hovering over a command button. Things look a bit ugly if we do so. First, let's look at the updates we've made to drawSelectedTile:
We've made a change to this function to now change the colour of the selected tile texture when we draw it (assigned to RGB values). For this purpose, we're testing whether the selected tile is either in the unit's move range or attack range. If the selected tile lies within both, we'll be setting a yellow colour. If it's only in the move range, we'll be setting a blue colour. Finally, if it's only in the attack range, we'll be setting a red color. We're then using SDL_SetTextureColorMod to update the colour of the selected tile texture. The purpose of this is to give a better hint to the player about what range the tile they're hovering over lies within, without them needing to toggle the range displays. If it's not in a range at all, we'll not draw anything. A small update, but one some players might appreciate. Next, comes drawMesages:
A simple function. We first test to see if totalMessages is greater than 0, then draw a transparent black rectangle at the positon we'll draw our message, to increase readability. Next, we're using `sprintf` to create the message text. Here, you can see where we're using messageNum. This variable will inform the player which message out of the total they are viewing. This helps us to know how many of the messages we've seen when it cycles back around, so the player doesn't need to wonder if they've seen all of the messages in the list. Next, we have drawCommandButtons:
This function is basically responsible for drawing our UI elements. As you can see from the function, the command buttons are actually a composite, with the base image being rendered and the actual icon image being drawn on top. Depending on whether the button's `active` flag is set (for move and attack buttons), we'll either draw commandButtonActiveTexture or commandButtonTexture. We'll then render the command button's image. Finally, we test to see if the command button we're processing is the one our mouse is hovering over (hoverCommandButton). If so, we'll also render commandButtonHighlightTexture. This is the texture that puts the yellow square around the command button. So, in conclusion, this function draws our command buttons by simply layering different images on top of one another. This means we don't need to have multiple images of different states. One last function to look at, and hud.c is done. drawHoverEntityInfo is an easy one to follow:
This is the function that draws the name of the entity that we're hovering over, just above the command buttons. We first test that hoverEntity is not NULL, then setup two variables, `x` and `y`, as the position we'll draw the name of the entity. Like our damageText, we're first rendering the name in black, offset by 4 pixels. We then draw the text in white, in the original location, so that we have a shadow effect, making it a bit easier to read. Wow! That was a lot! But all our HUD functionality is now available to us, and works like a charm. Just a few bits left to do and this part is all wrapped up. So, we'll look at where we're using addHudMessage and clearHudMessages. First, in ghosts.c, we've updated die:
We're calling addHudMessage to say that the ghost was destroyed, all in white. Moving over to items.c, we've updated healthTouch:
We're adding a message to say that consuming those lovely pancakes has restored some HP. We're adding the message with a light blue colour. ammoTouch has also been updated:
We're adding a message to say the magic crystal restored some ammo, again with a light blue colour. Now for mages.c. We've updated the die function:
Oh! A bad message here saying that one of our wizards has been killed. This message is being added in red, to show something terrible has happened. Over in player.c, we've updated doControls:
Whenever we end our turn, we want to clear the HUD messages. We're not doing this in endTurn, as that would mean that when the AI hands back control to the player, all the events that occurred would be lost, so we wouldn't know what happened during the ghosts' go. attackTarget has seen several updates:
If we're unable to attack the target, we're going to supply a message to the player to inform them why. This could be that we don't have any AP, that we don't have any ammo, or that the target cannot be attacked (line of sight check failures, etc). doMoveUnit has been updated:
When we decide to move a unit, we're going to clear the hud messages, so that we can work with a clean slate. We don't want loads of messages stacking up that we've already seen. Finally, in units.c, we've updated takeDamage:
Depending on the side of the unit that took the damage (the player or the AI), we'll display a message to say the unit was hurt. The colour of the message will depend on the side of the unit. If it's the player, we'll display it in red. Otherwise, it will be shown in white. Our HUD is done! We've now got a way to display messages, control the game using on-screen icons, and see data about objects on the field. Once again, we're stepping closer to completion. What we should do now is generate a better map. Right now, we're just surrounding the stage in walls and then randomly placing other walls. In the next part, we're going to use cellular automata to create a better, more interesting layout. 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: |