Category: Game

C++ Template Metaprogramming Game

C++ Template Metaprogramming Game

Snake
Image by OpenClipart-Vectors from Pixabay

Templates in C++ are a useful feature. Without them you’d not have template functions, or more usefully template classes like vector etc.  But there is an even more useful feature called template metaprogramming. It’s a very advanced and clever feature; one I have never done and I don’t think anyone could say they’ve mastered C++ unless they are good at it.

Here’s an example of the simplest example I could find. It comes from here and what it does is generate factorials of numbers at compile time. So when you run it it comes back with the answer immediately.

// factorial.cpp

#include <iostream>

template <int N>                                                                 // (2)
struct Factorial{
    static int const value = N * Factorial<N-1>::value;
};

template <>                                                                      // (3)
struct Factorial<1>{
    static int const value = 1;
};

int main(){
    
    std::cout << std::endl;
    
    std::cout << "Factorial<5>::value: " << Factorial<5>::value << std::endl;    // (1)
    std::cout << "Factorial<10>::value: " << Factorial<10>::value << std::endl;
    
    std::cout << std::endl;

}

But if you think that is clever how about a game where every time you compile it, it makes a move and remembers the move between turns? A developer called Matt Bierner has developed a snake game using template metaprogramming.

So I downloaded it into my Ubuntu, installed Clang and clang tool just for good measure and compiled. This is the output. Iv’e snipped a lot out after the first two. Ot’s very clever, in this case, not much use but I doubt if there is any other programming language in which you could do this. The compile plays the game, running it just outputs the results. Yes it’s not exactly practical but still…

david@davidvm:~/STT-C-Compile-Time-Snake-master/stt-snake$ clang++ -std=c++1y main.cpp -o snake ; ./snake
------------------
╺╺╺╺╺╺╺╺╺╺
╺╺╺╺╺╺╺╺╺╺
╺╺╺╺╺╺╺╺╺╺
╺╺╺╺╺╺╺╺╺╺
╺╺╺╺╺╺╺╺╺╺
╺╺╺╺╺▶*╺╺╺
╺╺╺╺╺╺╺╺╺╺
╺╺╺╺╺╺╺╺╺╺
╺╺╺╺╺╺╺╺╺╺
╺╺╺╺╺╺╺╺╺╺
------------------
╺╺╺╺╺╺╺╺╺╺
╺╺╺╺╺╺╺╺╺╺
╺╺╺╺╺╺╺╺╺╺
╺╺╺╺╺╺╺*╺╺
╺╺╺╺╺╺╺╺╺╺
╺╺╺╺╺▶▶╺╺╺
╺╺╺╺╺╺╺╺╺╺
╺╺╺╺╺╺╺╺╺╺
╺╺╺╺╺╺╺╺╺╺
╺╺╺╺╺╺╺╺╺╺
....
-- You Are Dead --
╺╺╺╺╺╺╺╺╺╺
╺╺╺╺╺╺╺╺╺╺
╺╺╺╺╺╺╺╺╺╺
╺╺╺╺╺╺╺╺╺╺
*╺╺╺╺╺╺╺╺╺
╺╺╺╺╺╺╺╺╺╺
╺▼╺╺╺╺╺╺╺╺
╺█▲╺╺╺╺╺╺╺
╺▼▶╺╺╺╺╺╺╺
╺╺╺╺╺╺╺╺╺╺
More thoughts on the design of Rogue like

More thoughts on the design of Rogue like

Unicorn hackSometimes I walk up around 3:00 AM and my mind is abuzz with things like this. Last night was one such night. The first thought was I should stop calling it a Roguelike. There’s a certain set of conventions with those and I don’t want to be limited by that.

For instance here’s an article about things you should or shouldn’t do in designing Roguelikes.

The game (for the next Ebook) is not going to be an all singing all dancing version but will be an MVP in the parlance. That’s Minimum Viable Product,

So if I’m going to divert away from the ‘standard’ then it needs a name. Something evocative like Dungeon Trawler but shorter more catchy.  So I’m going with V.O.R. (Vaults of Ruin) or maybe just Vor,

So onto design aspects. Here’s a list of the features:

  • 10-15 different Monster types with differing melee, range weapons and magic. Can have packs of them, not just one. There is only one player. Should be fun!
  • Simple set of castable spells using a Mana value. It is used up casting spells but regenerates slowly as you move. It can be replenished quicker by consuming potions.
  • No food or water but the character has an energy rating. This is depleted by movement and fighting. Rest or sleep oe rating food replenishes it but I don’t want it to be a major thing. I’m not having deep dungeons with 25 or more levels, but 12 levels maximum.
  • Weapons are sword, dagger or bow. Can switch between them.
  • A few powerful magical treasures.
  • Turn based not real-time. Asteroids is real-time but movement will be restricted to so many squares for you and monsters. You probably won’t be able to outrun the faster moving monsters.
  • Limited visibility can make things interesting. It means the game has to calculate what squares are visible each move.

I was tempted to do away with grid movement; for instance in the Asteroids game, they can move at any angle and velocity and are not tied to a grid. But that might be a bit too complicated so movement will be grid limited and Up/Down, Left/Right and maybe diagonal.

The screenshot is from an open source (.NET Core/C#) web rogue game called Unicornhack.

 

 

Now this is interesting – Interactive Fiction

Now this is interesting – Interactive Fiction

Choicve of Games Interactive FictionIt’s not really a thing done in C, although you could do. I came across a site that offers commercial Interactive Fiction. As they put it “text-based, multiple-choice games. ” and “By using text, we can interact with the imagination in different ways from a graphics-based game. We can also allow game designers to quickly and inexpensively produce games in comparison with graphics-based games.”.

Their games aren’t free but aren’t that expensive either typically $5-$8 or thereabouts and you can get them on mobile as well as via Steam. A recent game they’ve just launched has 1.2 million words of text (that includes the game scripts) which is phenomenal considering that most novels are 50,000-90,000 words.  Their games use their own open source scripting language called ChoiceScript which is a very simple programming language.  You can read their online manual (over three web pages) which should take maybe 20 minutes long. You can also play some of their games partly or fully free on the web.

The games are put together through a series of scripts. There’s also a free IDE for creating the scripts from a 3rd party. If you think writing a book is hard then writing an IF (Interactive Fiction) game must be like that but on steroids.

Games like the 1.2 million words one have multiple paths through with different plot lines which aids replayability. This isn’t anything like the Fighting Fantasy books (Name drop: I worked on a football game for Ian Livingstone in the mid 90s) because ChoiceScript has variables. This means that characteristics can improve over time and you can make decisions using <. >, <=, >=,==,!= just like in C etc. It doesn’t have arrays (there seems to have been some attempt at adding them in 2015 but I suspect it didn’t work) but there are subroutines and Goto which lets you create a structure.

You can add graphics but the games I’ve looked at don’t use them much if at all. The pictures are painted with words and this company have a very wide variety of games on sales including RPG, superheroes, science fiction, mysteries, war and pirates amongst others. The game mechanics are multiple-choice questions which doesn’t sound very glamorous but its like reading a book; your mind fleshes out the backdrop. The original Colossal Cave Adventure game is an example of Interactive Fiction and not coincidentally the Awards for Interactive Fiction are called the XYZZY Awards.

As the saying goes “Everyone has a novel in them”. IF is one way to bring it out…

 

My other side project continues

My other side project continues

Smartphone
Image by Gerd Altmann from Pixabay

This is the social mobile multiplayer game I have mentioned before. The initial game creation program is mostly working. I say mostly because I will still be adding to it. It does however create all of the game data in about 30 seconds for a game that can hold up to 10,000 players. It then creates the output files which are read by the mobile apps. These apps have yet to be created but I’ve decided to do some early testing using non-mobile apps that I’m working on.

What I want to do is prototype the mobile app, not particularly visually but functionally. To this end I’m creating a C# client desktop app that does everything that the mobile app will do. It can read the data (directly rather than via a webserver) and let me create new orders and upload them back to the server (or in this case my development PC).

This client will be crude and not great looking but lets me test that data is coming and going correctly. I use JSON for everything, as a data transfer format as well as storing all game data at rest as opposed to a database. It lets me hold all game data in dictionaries (with a bit of tweaking it is possible to save/load lists of objects to JSON. After loading I convert them to Dictionaries using an Id field.

                var bytes = File.ReadAllText(Lib.PeopleFilename);
                var list = new List();                
                list = JsonSerializer.Deserialize<List>(bytes);
                persons = list.ToDictionary(x => x.Id);

It works and is quick. The downside of using a Dictionary is that it occupies more bytes per element than a List. How many? Well it’s never easy to figure. .NET does not really encourage discovering how things are implemented. This GitHub project by developer Ludovit Scholtz shows the memory used by various .NET Generic Collection Types (HashTable,  Dictionary, ConcurrentDictionary, HashSet, ConcurrentBag, Queue and ConcurrentQueue) with various string lengths in a TestObject which as string, an int and a DateTimeOffset.

Storing a million objects in a Dictionary <int,TestObject> with a null string occupies 48,222,240 bytes so roughly 48 bytes per entry. I believe a List is closer to 20 bytes overhead per element. So for slightly more than double the memory use, using a Dictionary gives a tangible performance yield.

,

So I’ve decided- graphics it is for the roguelike

So I’ve decided- graphics it is for the roguelike

Dawnlike on OpenGameart
Dawnlike on OpenGameArt.org

I did a quick search for free rogue graphics yesterday and found an astonishing quantity of rogue type graphics in sizes varying from 8 x 8 (pixels), 10 x 10, 16 x 16, 32 x 32 and 64 x 64. I haven’t quantified these sizes exactly but the 16 x 16 ones seems to be the most frequent and so that’s what I’ll pick.  This post on Reddit provided links to many free (and some paid), most on the OpenGameArt website.

As a programmer sorting out graphics, it can be a very time consuming thing to do, so expect to spend a lot of time on it. You’ve got to satisfy yourself that you have enough graphics.  Not just for terrain (e.g. dungeons and cities) but also for monsters. There are artists who will draw you more on sites like fiverr.com but that’s all cost.  If you can draw or recolour then that’s a major plus.

Recolouring is another problem. With game graphics, you ideally want them all from the same source or else you’ll have the problem of mismatched sets. Nothing jars visually more than mixing graphics with different palettes. I’m no artist but even I can tell when something works and when it doesn’t.

Also there’s the question of perspective. The Dawnlike graphics are a sort of mix of from above but with a slant so you see front walls. Whereas something like the Kenney rogue game pack is front on. So you have to decide which you are going to go with.

My ideal game would be one of my favourites- Ultima 3. This is probably because its the only Ultima that I have played right through to the end and finished it! It was also the first. It took me about three months of one hour’s play a night. And I took copious notes. But as you can see its a bit more than a rouge like game! Those screenshots are from a CBM-64 which had a 320 x 200 screen (the image below is a composite of nine screens) borrowed from https://imgur.com/gallery/UvrzmBt. You can of course get the PC version sof Ultima III (and I and II) from gog.com.  (Note these are straight links not affiate. I receive nothing from them). I did buy Ultima I-VI from gog.com.

Ultima 3 screens

Rogue like – do you use graphics or text?

Rogue like – do you use graphics or text?

Rogue games search The original rogue used graphics. This was back in the era of terminals and home computers and graphics could be quite limited. So there’s a tradition of using text. However if you do a google image search for rogue game like I did here, you can see that while many of them are text there are a couple that are graphics.

So the question is do you use graphics or text?

Text has the advantage that its just there. All you have to do is choose the appropriate character.

Plus if you use Unicode (always a bit of a pain in C but doable) then you have access to hundreds of thousands of different characters. Like this one:

👾. Which is actually these

&#128126;

&#x1F47E;

More information about this one from here.

Graphics on the other hand can be a lot more colourful but you have to get them drawn, or acquire them from somewhere like kenney.nl. So not an easy one to decide. If I had the resources I’d use graphics, but I’ll keep to the tradition of using Text.

A tip. When you have a question like “What characters are used in rogue” just try it. There is so much information on the web that there’s a good chance that someone will have done it. I’m finding this more and more and sure enough, I found this on Reddit. How would you have ever found that out before the web existed?

So much fun from 16 x 16-tixy.land

So much fun from 16 x 16-tixy.land

tixy.landIf you are looking for inspiration for games creation, take a look at tixy.land. It’s a 16 x 16 square of dots whose colour is determined by a user entered JavaScript function. If you click the page, you’ll see new patterns. This was created by a developer Martin Kleppe and you can see other examples in this twitter thread..

The function is limited to 32 characters but even so that gives you a lot of possibilities. Most patterns are dynamic, changing as you watch. It’s quite fascinating.  The pattern shown in the screen shot is from Math.tan(t*(100-y*x)/9). and the actual url (including the code is)

https://tixy.land/?code=Math.tan%28t*%28100-y*x%29%2F9%29

The %28 etc are the HTML encoding of (, while %29 is ) and %2f is /.

You can edit any function on the page so try substituting sin, cos instead of tan. Also abs works as well.

So I’m playing Rogue… in my browser

So I’m playing Rogue… in my browser

RogueThe internet archive (yes them again!) not only has archives of most things I’ve done, but they also have an archive of 7000 games from the Dos era that you can play in your browser. You don’t have to install anything, just click on it and it installs the DosBox emulator for the browser and runs it.

Thankfully they have provided a filter so you can search . Looking through the first page I spotted Rogue and Warlords II, two of my old favourites. The screenshot is me after just having bumped of an Emu. That white square in a corridor between the bottom two rooms.

The collection has loads of all classics; it’s a very nice bit of work. Games from this era (very roughly the 90s) tended to be 2D. It wasn’t until the mid 90s that 3D games like Quake and Doom appeared.

I did a search for Empire in the text box and it found Empire Deluxe (a game I have and occasionally play 27 years after I bought it) plus a load of other games like Master of Orion.

Back in the day I worked as a game designer for MicroProse (yes the Civilization people) from 1992-1993 and though I never met Sid Meier, i did cross swords (metaphorically) with the other cofounder Wild Bill Stealey at a company BBQ (in the UK) by er failing to catch a baseball.

Games back then still came on floppy disk. Installing a game from 18 disks was not a fun task….

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).

 

 

How to implement a Roguelike

How to implement a Roguelike

Roguelike dungeon
From Wikimedia

A roguelike is a character based fantasy game. By character I mean @^! not an individual as such! A question on the C SubReddit had asked about Project ideas for simple applications and someone had suggested a Roguelike. It’s not a bad idea but probably quite a bit more than just a simple project.

So I suggested breaking it down into stages. Here’s what I said.

Rather than a roguelike in one go (that’s a actually quite a bit of code) so do it in these stages.

  1. A Dungeon level generator. Create rooms and link them by corridors.

  2. Generate a bunch of levels – link them via randomly stairs, pits, transporters.

  3. Add random monsters and treasures in rooms.

  4. Implement a moving player able to navigate through the levels.

  5. Add combat. Weapons, range weapons, spell casting. Add monster hit points.

  6. Turn it into a polished game. Add everything else needed. Permadeath, collecting treasures. Moving monsters.

  7. (Optional) Make it multiplayer and allow PvP.

PvP means allow Player v Player combat. Doing it multiplayer is actually quite a lot of work which is why I made it an option. Rogues are often created using simple ASCII chars for monsters and treasures. Some programmers have used graphics and there are plenty of free graphics sets for 8 x 8 or 16 x 16 pixel sized monsters etc. like the Kenney.nl microrogue set. Shown in action below.

Kenney.nl micro rogue set in action

I am tempted to make this the 3rd game idea for the Raspi game book. 30 years ago I created a multiplayer postal game Quest that is still running albeit on the web not by post. That included a dungeon generator. It wasn’t in C but it’s easy enough to translate Turbo Pascal to C.