Category: C++

Star Ruler 2 – Open Source 4X game

Star Ruler 2 – Open Source 4X game

Star Ruler 2This is a 4x game (Explore, Expand, Exploit, Exterminate) .  “Select from one of seven races – or craft your own – to explore dozens, hundreds, or even thousands of systems in a galaxy of your choosing. Expand across unique and varied planets and ultimately exterminate – or subjugate – any who stand in your way either in offline single player or up to 28 player multiplayer.” as gog.com put it.

But as well as being available on Gog.com or Steam, it’s also open source but that doesn’t include the music from the game.  So you can pay for the game on Gog.com/Steam or download the open source version and build it yourself.

The GitHub website contains the full source code needed to build Star Ruler 2, and all secondary scripts, data files and assets required to run it. It’s 45% C and 22.5% C++ according to GitHub with a sprinkling of Flash (arr ar- saviour of the Universe- er sorry).

 

 

A list of open source physics engines

A list of open source physics engines

Chipmunk Color matchIt’s not uncommon to have 2D games (and 3D) incorporate a physics engine. So when objects move and hit each other they behave realistically. The code that deals with “physical” interaction, objects bouncing or rolling off other objects is usually all parcelled up in a game physics engine.

Doing that means the programmer doesn’t have to worry about objects interacting. Your character moves into a room and knocks a vase; the vase falls over and breaks. Imagine how complex it would be if you had to program all the interactions. Instead, all objects in the room are predefined. As objects move and hit other objects they behave according to the predetermined rules. Balls drop to the floor and bounce. Breakable objects break.

An indie game studio called Tapir Games has put together a pretty comprehensive list of open source game physics engines. There’s even a couple in C though many are programmed in C++, C# and so on.

The picture comes from Chipmunk color match, one of the games using the (C library) Chipmunk physics library.

A portable Windows Devkit

A portable Windows Devkit

Tool icons
Image by mohamed Hassan from Pixabay

I spotted this the other day. A C and C++ development distribution for Windows called w64devkit. It’s less than 80 MB and you don’t need to install it so you could easily fit it onto a USB memory stick or download it.

As the author (Chris Wellons) says “Despite its simple nature and small packaging, w64devkit is almost everything you need to develop any professional desktop application, from a command line utility to a AAA game”. Note it doesn’t include source control, nor does it access the internet, though no doubt you could. So you could backup stuff say to GitHub or wherever.

I am fan of software like this that you can take with you on a laptop or a memory stick. You don’t always have to have a full dev system with multiple monitors, Visual Studio etc.

If you’re interested, do read the entire blog post.

 

The Wayback machine-slightly offtopic

The Wayback machine-slightly offtopic

There is a wonderful website (archive.org) that makes a backup of websites. It even has one of this blog, taken on April 30th. It’s remarkable.

The reason I mention it is because I was looking at the backup of cplus.about.com, a website that I managed (curated, wrote tutorials etc.) on “Programming in C, C++, C#” (and even Go) between 2006 and 2013.  One of the things I ran there was a set of programming challenges and by the end I’d done a whopping 70 of them. I came up with the idea, published it, then adjudicated entries.

This page has a list of 65 of them.  There may be more from a later date but no more than 70.

As I can now gain access to most of them, I’m going to rerun a few here. starting with the first which I’ll publish tomorrow.

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!

 

Bit of an oddity with VS Code

Bit of an oddity with VS Code

When I first started using it, the C++ extension, and configuring for C++, I got a tasks.json one which was suited for gcc, but recently when I install it, (and the C/C++ Extension for Visual Studio Code, the only choices seem to be these. What happened to the the ones for clang/gcc? The one on the right is what I’m expecting. Even with a C/C++ file open as the instructions here say, I’m getting the one on the left.

VS Code ConfigureVs Configure C++
It’s possible that I’m getting this because I’m using the headmelted and VsCodium versions on a Raspberry Pi.

There’s a bit of a question mark about using the official extension on non-official build of Visual Studio. Headmelted allows it, but VsCodium has its own marketplace.

It’s easy enough to copy tasks.json over so not really a problem but just a minor irritation.

John Conways Game of Life

John Conways Game of Life

Golly - Life simulatorAn English mathematician John Conway (who died not that long ago) came up with a very simple cellular automaton that he called Life. This was back in the 1970s and I remember finding his original article in Scientific American while at University.

We had no internet then and I whiled away 10 or so hours trying to make my version of Life run faster. Given that this was 1978 and it was written in BASIC, it’s not surprising that it only did a couple of generations per second on a mainframe. They didn’t give us much CPU time and it was an ICL 1900. My iPhone is probably more powerful!

The rules are simple enough to implement but it’s unlikely you’ll outperform Golly which is what the image shows. That’s written in C++ and has been under near continuous development for the last 15 years.

But part of the fun is writing your own life simulator and watching the patterns explode. I’d call it the minecraft of its day given the amount of computing time spent on this since the 1970s. There are some amazing creations all following these three simple rules.

  • Any live cell with two or three live neighbours survives.
  • Any dead cell with three live neighbours becomes a live cell.
  • All other live cells die in the next generation. Similarly, all other dead cells stay dead.

The grid is just a simple bit field. Each cell is either on or off and the rules determine if new cells are created or if patterns die out.

There are innumerable ones on the web. Here for example is a C/SDL version. Note, it uses SDL1. When I get the time, I’ll build and run it. Comments are in French!

Using printf type variable parameters in your function

Using printf type variable parameters in your function

The C programming languagI needed this in a bit of debug code. I wanted it to work like printf where there’s a format string containing one or more % format specifications and then write this into a buffer and dump it where ever.

C has a library stdarg which lets you do this. It’s not the most intuitive but it’s definitely worth understanding.

What I’m wanting to do is a function that does something like this (assume s1,s2 and s3 are char *).

sprintf(buffer,"Some string values %s %s %s",s1,s2,s3);
doSomething(buffer);

But in my own function and with the ability to have 0,1,2 or how ever many parameters without having to write a separate function for each. Kind of what printf does.

Here’s the code:

 

#include <stdarg.h>
void op(char* s, ...) {
	char buffer[50];
	va_list argptr;
	va_start(argptr, s);
	vsprintf_s(buffer,sizeof(buffer),s,argptr);
	OutputDebugStringA(buffer);
	va_end(argptr);
}

The … represent the variable number of parameters. it’s called the variadic operator. To access the actual parameters needs the various va_ macros and types. For instance va_list is a type that manages the list of parameters. The va_start macro takes the list and the parameter before the list. vsprintf_s is the Microsoft secure version of vsprintf. Both are the variable parameter equivalent of sprintf/sprintf_s.

OutputDebugString is the Windows debug string function. Finally the va_end tidies up everything.

So you use this just like printf, except the output goes to the Debug channel and can be picked up in Visual Studio (if debugging) or by running the SysInternals free DebugView utility.

Note, the original version of this used OutputDebugString but I found it was outputting gibberish. I correctly guessed that it was linking to OutputDebugStringW ; the MBCS version and changing it to OutputDebugStringA (the ASCII version) fixed it. Something to watch out for on Windows. 

The Joys of C++

The Joys of C++

Maze
Image by Arek Socha from Pixabay

My progress on the C++ asteroids game took a little detour down a one way street. The problem I hit was until then I thought I was being clever by passing in a reference to another class in the constructor. That worked fine until I started implementing array classes.

The issue I got was using my constructor meant that the default constructor was deleted. This happens in any class where you add your own constructor as all the special functions are deleted. You then have to add your own Move or Copy assignments if you are doing things that invoke them. Like iterating through an array (or vector in my case). Although I use Bullet and Asteroid classes, I manage  collections of them through an Asteroids and a Bullets class.

Plus I’d decided that vector class wasn’t perhaps the best class to use. This thing runs at 60 fps, so adding and deleting elements from a vector seems a bit wasteful. Instead by using a std::array, and constructing all elements in it when the managing class is instantiated, all I have to do is scan for the first element with an active flag set false. (all are set false when constructed), set a few fields for velocity and position and there it is on screen.

Is this premature optimisation? I don’t think so. One of the things that programmers are told NOT to do!

So I have cleaned up my constructors now. They are parameterless and no special functions are deleted. It’s this kind of stuff that can do your head in and one of the reasons why I think C++ is considered a harder language to master.  I’m certainly a long long way from that.

The maze? Just a metaphor for C++ programming!

A small C++ Tip. Return values from Constructors

A small C++ Tip. Return values from Constructors

C++ LogoYou can’t return anything from a constructor.  One way is to use exceptions but those can bring their own issues. Google’s C++ guidelines actually stipulate no exceptions and I’ve heard it from others as well that they prefer not to use them. Some people avoid it by having a mostly empty constructor and then an init() method to do the real initialisation and return a success/fail state.

But there is a simple trick that you can use, just return the state as a reference. Here’s an example. If you want to return more values, use a struct.

#include <iostream>
using namespace std;

class Simple {
public:

    Simple(bool& failure) {
        failure = true;
    }

    ~Simple() {
    }
};

int main() {

    bool fail_flag = false;
    Simple f(fail_flag);
    if (fail_flag)
        cout << "failed " << endl;
    else
        cout << "Success" << endl;
}