Category: C

Using small delays in C with SDL ticks

Using small delays in C with SDL ticks

Asteroids game - player ship rotationRunning a game at 60 frames per second means that handling things like key presses can be interesting. In the game, I call various SDL functions and via a giant switch statement set flags. Then later in the game loop, those flags are used to determine actions

So if you press Q to rotate the player ship anti-clockwise (counter-clockwise to yanks!) without some limiting thing, it would whizz round through 900 degrees each second. (There are 24 rotation angles for the ship, each 15 degrees. 60 x 15 = 900) .

I use a very simple technique to limit it. SDL has a function called SDL_GetTicks that returns the number of ticks since SDL was initialized in the game, i.e. when it started running. A tick is 1/1000th of a second, i.e. a millisecond. By calling this function twice, you can measure a time period. It’s not as precise as the nanosecond CPU clock that I use but for the kind of delays I’m talking about it is more than sufficient.

This is the code that is called each frame in the game loop.

void RotatePlayerShip() {
	if (rotateFlag && (SDL_GetTicks() - rotTimer > 40)) {
		rotTimer = SDL_GetTicks();
		if (rotateFlag == 1) // CounterClockwise 
		{
			Player.dir += 23;
			Player.dir %= 24;
		}
		else
			if (rotateFlag == 2) // Clockwise
			{
				Player.dir++;
				Player.dir %= 24;
			}
	}
}

Because the game loop syncs to the vertical fly-back, the time between two successive calls of this would be about 16.666 milliseconds. (=1000/60), but the check to see if 40 ticks have passed slows it down to 25 x 15 = 375 degrees rotation per second, i.e. just over one complete revolution which is more manageable than 900/360 = 2.5 full rotations. Plus if you wish rotation speed to be faster just change the 40 to a lower value.

This measured time delay is used quite a few times in the game. You could use it as a means to make the game get harder by having shorter delays on say aliens moving or firing.

How to Draw a circle in C

How to Draw a circle in C

Asteroids-with shield-round-player-shipIn the asteroids game, when you press the s button to put up a shield, it draws a circle.  I must confess, I didn’t know how to draw a cuircle so looked it up and found an example on StackOverflow. You can use code from StackOverflow, licensed under a MIT license.  I include the link to StackOverflow in the game code (in the chapter 48 zip file) in a comment.

Here’s the code in the game.

void DrawCircle(SDL_Renderer *Renderer, int _x, int _y, int radius)
{
	int x = radius - 1;
	int y = 0;
	int tx = 1;
	int ty = 1;
	int err = tx - (radius << 1); // shifting bits left by 1 effectively
								  // doubles the value. == tx - diameter
	while (x >= y)
	{
		//  Each of the following renders an octant (1/8th) of the circle
		SDL_RenderDrawPoint(Renderer, _x + x, _y - y);
		SDL_RenderDrawPoint(Renderer, _x + x, _y + y);
		SDL_RenderDrawPoint(Renderer, _x - x, _y - y);
		SDL_RenderDrawPoint(Renderer, _x - x, _y + y);
		SDL_RenderDrawPoint(Renderer, _x + y, _y - x);
		SDL_RenderDrawPoint(Renderer, _x + y, _y + x);
		SDL_RenderDrawPoint(Renderer, _x - y, _y - x);
		SDL_RenderDrawPoint(Renderer, _x - y, _y + x);

		if (err <= 0)
		{
			y++;
			err += ty;
			ty += 2;
		}
		else 
		{
			x--;
			tx += 2;
			err += tx - (radius << 1);
		}
	}
}

it’s as simple as that! To make it more interesting, it is called each frame with the shield throbbing  by increasing  the radius from 38 to 46 pixels by 2 then restarting at 38 again. Here’s the code for that. Note that when the shield energy is below 10, it no longer works.

void DisplayShield(SDL_Rect * target) {
	if (shieldFlag && shieldStrength >10) {
		SDL_SetRenderDrawColor(renderer, 0xff, 0xff, 0xff, 0xff);
		DrawCircle(renderer, target->x + (SHIPWIDTH/2), target->y + (SHIPHEIGHT/2), shieldRadius);
		shieldRadius += 2;
		if (shieldRadius == 46) {
			shieldRadius = 38;
		}
	}
	if (shieldStrength < 100) {
		TextAt(target->x + 10, target->y + 58, sltoa(shieldStrength), 0.67f);
	}
}

The number under the player ship is the shield energy which drains while the shield is being displayed and recharges back up to 100 when you take your finger off the shield button. The number is only shown when the value is less than 100.

Open source repositories are worth a trawl

Open source repositories are worth a trawl

Repository
Image by Jagrit Parajuli from Pixabay

How many C language projects do you think there are on GitHub? If you put language:C in the search box, you get the astonishing figure of 980,752! That would take some trawling through.

There are other search terms you can use as well. Click the cheat sheet link on the bottom left of the page and it will popup a form explaining how to filter for various things.  You are probably as well reading the GitHub search help. There’s a lot more to search there.

Confusingly the searches sometimes seem to come up with different values. I’ve seen it vary between 578,000 and over a million!   Add game to the search and there’s only 31,426 projects! Only…

Should you use #pragma once?

Should you use #pragma once?

Pragma as found by google image searchThe traditional way of using an include guard is to put all of the header inside a #ifdef like this.

#ifndef hr_time
  #define hr_time
  #include <linux/time.h>
  #include 

// rest of code here
#endif

However the modern way is to put this at the top of the header file.

#pragma once

And this seems supported by most compilers I’ve tried. Certainly Visual Studio C/C++, gcc and clang all work.

In fact when you add a new file and choose header in Visual Studio, it put the #pragma once in automatically for you!

Given that those three C compilers are the main ones I use, I much prefer this pragma and use it.  But I would be interested in hearing of any C compilers that don’t  use it.

 

Publishing excerpts from my 2nd ebook

Publishing excerpts from my 2nd ebook

learn C Games Book coverI’m changing horses in midstream so this won’t appear as it’s been done so far. Rather than let it go to waste, I’ll be publishing it in parts here. My next book will be Learn C Games Programming on the Raspberry Pi.

Installing SDL2 on Ubuntu/Debian

The SDL2 library is an open source library available from the libsdl.org website. However in Ubuntu it’s fairly easy to install. We do need not just the binary files but the headers so we can include them.
On Ubuntu (and Debian system) the apt tool maintains a cache of files. You can search these from a terminal with this command.
apt-cache search libsdl2
On my PC this output.
libsdl2-2.0-0 – Simple DirectMedia Layer
libsdl2-dev – Simple DirectMedia Layer development files
libsdl2-doc – Reference manual for libsdl2
libsdl2-gfx-1.0-0 – drawing and graphical effects extension for SDL2
libsdl2-gfx-dev – development files for SDL2_gfx
libsdl2-gfx-doc – documentation files for SDL2_gfx
libsdl2-image-2.0-0 – Image loading library for Simple DirectMedia Layer 2, libraries
libsdl2-image-dev – Image loading library for Simple DirectMedia Layer 2, development files
libsdl2-mixer-2.0-0 – Mixer library for Simple DirectMedia Layer 2, libraries
libsdl2-mixer-dev – Mixer library for Simple DirectMedia Layer 2, development files
libsdl2-net-2.0-0 – Network library for Simple DirectMedia Layer 2, libraries
libsdl2-net-dev – Network library for Simple DirectMedia Layer 2, development files
libsdl2-ttf-2.0-0 – TrueType Font library for Simple DirectMedia Layer 2, libraries
libsdl2-ttf-dev – TrueType Font library for Simple DirectMedia Layer 2, development files

We’ll eventually need libsdl2, libsdl2-image for graphics support and libsdl2-mixer for sounds. We’ll also need libsdl2-dev so let’s start with that. Run this command . It will probably ask for your password.

sudo apt-get install libsdl2-dev

That downloaded and installed 73 MB of files.   More to follow

Added the sources of another game

Added the sources of another game

Basic Computer games bookThis was a text mode game, my idea being to do something like the old Star Trek BASIC game but better. I called it Star Empires and it’s on GitHub, just follow the link to GitHub on the C Games sources link.

The zip file includes both C and a C++ version. Both will compile with Visual C++ 2019 Community edition. There is a minor compile error, a = that should be == in the C++ source. I ill get round to fixing it and uploading a replacement.

I do get a bit of pleasure (more like an exercise in masochism!) converting old BASIC games to C. I’m looking at the two Creative Computing books (and while 95% of the games are not exactly great (well lets be generous and say they were good 45 years ago!) but there’s one or two that might be worth the effort! I bought these in 1982 lost those and then bought them a few years back again.

Plus when you think how the games industry has matured since the late 70s and 80s, and many of those early programmers will have cut their teeth on games like that before learning more advanced stuff, so  lets not be too harsh!

 

A rather powerful C Graphics library

A rather powerful C Graphics library

Raylib libraryI’m not going to be departing from SDL2 any day soon, but if I were starting from scratch, I would seriously consider raylib.  It ticks many boxes!

  • Written in C(C99). Tick.
  • Cross platform including Raspberry Pi desktop. Tick.
  • Open source and liberal licensing tick.
  • Full 3D support with animated models. Tick.
  • Extensive Sound support. Tick.
  • Very open license that even allows static linking with closed software. Tick.
  • Lots of examples. Tick.

There’s even a set of open source games on GitHub. including several that you can play in your browser (HTML5). Documntation is in the form of a 36-page Wiki. I took a quick glance through there and was impressed with some of the features. For example, OpenGl can be used directly and not through X11 though that is also available.

Plus full marks for including struct sizes on the data structures page. That’s not something you often see, nor is instructions for configuring Visual Studio, Visual Studio Cocde, Codeblocks, Eclipse and Sublime Text. The cheat sheet (which you can also download as a pdf) gives an idea of the number of functions in Raylib. They cover five pages!

Browsing the source code of old and commercial games

Browsing the source code of old and commercial games

 

Archive photos
Image by Pexels from Pixabay

This page on a website called WikiZero has a long and very extensive list of games whose source code is available. That doesn’t always mean you can build the game. Many games are very old and in BASIC or assembly (.g. Elite is available in various forms).

It might have been created for a different platform or more likely the source code is available but the graphics and sound assets aren’t, unless you have bought the game, perhaps from sites like gog.com and so have them.

One thing to be aware of, many of the links on WikiZero go to the excellent wayback machine which is part of archive.org. This is under threat by some commercial publishers because they have lent ebooks during the Covid lockdown period without any limitation.  So if you are interested in anything I suggest you check it out sooner rather than later, just in case.

For instance here is the C source code for a TRS-80 game from 1979 called Paravia. It looks like a much expanded version of the Classic Computer game Hammurabi.  Note the wayback machine can take a few seconds to retrieve a webpage. They have a very large chunk of the web’s websites in there…

Goto is considered bad programming in C but

Goto is considered bad programming in C but

goto exit signThere is one case for using goto when you have nested loops and you’d like to jump all the way out. The goto statement was very popular in BASIC but often resulted in programs being like spaghetti with gotos all over the place.

Here’s a contrived example where I have used a goto.

#include <stdio.h> 

int array[10][10][10];
int main() {
    // Populate array
    for (int y=0;y<10;y++)
      for (int x=0;x<10;x++) 
        for (int z=0;z<10;z++) {
          if (array[x][y][z]==0)
            goto exit;
    }
exit:;
}

In my C programs, for-loops are the most popular followed by while-loops, do-while loops and gotos are hardly ever used at all.