Author: David

How to use indexed sequential files

How to use indexed sequential files

Files
Image by Pontep Luangon from Pixabay

This was a big thing long before PCs existed but you don’t see it so much nowadays.  Say we have a lot of static data, perhaps text strings which can vary in length from a few bytes to hundreds of bytes long. What is an efficient method to store them, i.e. in both space and time?

The answer is ISAM (Indexed Sequential Access Method)  which sounds more complicated than it is. We will use two binary files- one is the data file and one is the index file. The data file holds the raw text strings. We’ll write the raw strings using the C file write. At the same time as write them, we also build up an array of structs. This struct will look something like this:

typedef struct {
  int id;
  unsigned long offset;
  unsigned long length;
} indexRec;

The id could be a char * string. It’s just a way to search for and find the data.

As each text string is written to the data file we populate a struct with the file offset and length. Eventually after all strings are written you can write the arrays of structs to the  index file.

Then anytime you wish to read text strings back, load the structs into an array in ram and scan for the matching id then call fgetpos with offset (this moves the file pointer to the specified byte offset) and read in the length number of bytes from the data file.

An even simpler approach

If you just use an index number then you can scrap the id field and instead store the index file as a collection of offset and length fields. To read string #100 just do a fgetpos to byte at 100 * 8 (four for the size of offset plus four for the size of length)  in the index file, read the eight bytes for offset and length then do a fgetpos in the data file to the offset and read in length bytes as before. Very efficient and very fast. Just two reads in two files and one of those is only eight bytes.

If you wish to change the text strings in the data file, use the same method to retrieve them. If the new string is smaller then just write it and change the length field of the index record and rewrite it. If the new string is longer than the old, write it on to the end of the data file and change the index offset and length fields and rewrite them in the index file.

Both of these edit methods (shorter or longer string edits) will ‘lose’ bytes in the data file. When replacing with a shorter string and adjusting the length, the extra bytes that were in the previous string are no longer referenced. With a longer edit the entire previous string is no longer referenced.

Reclaim lost bytes

However it’s very easy to compact the data file and reclaim these lost bytes. Just process the index file and read each string and write them on the end of a new initially-empty file.  You also change each index file record to have the new offset and length of each string in the new data file. Once it’s rewritten just delete or backup the old data file and rename the new data file to be the one used from now on. Depending on how often the data file is edited, you will need to “compact it” every few days or weeks. But compacting is a pretty quick process, even for mega byte or larger sized files.

I used this technique albeit in Turbo Pascal not C to store game data for postal games I wrote back in the late 1980s. Games that are still run today but on the internet, not by post. For example in a map location there can be several parties of adventurers. The file record for that location has a file pointer to the start of a chain of party file ptr records. Each index file of adventurer parties has a binary file offset to the party in a binary file and a file ptr (or -1 if the end) of the next party’s file pointer. Like a pointer linked list but using file pointers instead of real pointers. Similarly the map location has a file pointer to a dungeon if one exists in this location (or -1 if it doesn’t).

This technique kept the map file fairly small but there were lots of binary file pairs for parties, dungeon, characters (in parties), and towns and shops in towns. Who needed a database? I didn’t… (That’s cos databases didn’t really exist back in the day. Had they existed I might have used them… maybe).

The minus one problem

In the struct definition, you’ll notice that I use unsigned longs for file pointers and length. There is no -1 for unsigned longs. It’s 4294967295. Using this as an end of chain pointer is ok because it is never going to be used as an offset. If I had used signed numbers then I could have used -1 but remember when I wrote this, it ran on a 16 bit computer so I used 65535 instead of -1. I could easily get binary files 40 Kb or 50 KB in size, so a signed number would have overflowed after 32767 bytes.

How to use some advanced data structures in C

How to use some advanced data structures in C

Linked Lists
From Wikimedia Commons

In my eBook, I used only structs and arrays. In fact the commonest “structure” was an array of structs. That was used for bullets, asteroids and aliens ships.The benefits of that are it’s easy to process; I started out by using it as an array and eventually switched to using a pointer to each struct “walking” the pointer through the array, jumping it if you like from struct to struct. Very simple and ideal for a game like asteroids.

You don’t need complexity because that slows things down and the only constraint in the design was making sure I could run everything at 60 frames per second..

C doesn’t come with anything more complex, yet computer science has determined many many advanced data structures that have their uses.

If you were programming a dungeon exploration game, an array might not be the best way to store the dungeon. You’d have multiple levels where each level consist mainly of rooms and corridors. How might you store that? Also there’d be monsters, treasures, traps, transporters and so on in the dungeon.  How would you traverse this structure, guaranteeing there’s a path so that every room can be reached?

Coirridor
Image by Rudy and Peter Skitterians from Pixabay

You might use an array to hold each level but how would you connect levels? Thinking about it I probably wouldn’t. I’d have staircases connecting corridors, traps that let you fall through to a room or corridor below, a transporter that lets you appear in a room or corridor above.

C is flexible enough to support a structure like this but you would have to code all the storage yourself. One way round it is to find an open source library like SGLIB. One reason I chose this is because it lets you create container data structures.

Sglib is fairly low level. It includes code for sorting arrays, for manipulating singe, double and sorted linked lists, red-black trees and hashed containers. As they say “A hashed container is a table of fixed size containing another (we say base) container in each cell. Once an object is going to be inserted into the hashed container, the hash function is used to determine the cell where it belongs and then the object is inserted into the base container stored in this cell. The base container is usually a list, however it can be a sorted list, double linked list or a red-black tree as well. Sglib’s hashed container is parameterised by the name of the base container.”

There are examples provided in the documentation as how to use each type of data structure.

 

What is the best way to include text?

What is the best way to include text?

Words
Image by Free-Photos from Pixabay

One of the games I’m working on needs to include a 1.9 MB text file (200,000 words). Now it’s not that big a deal but using 7zip I can compress it down to 400 KB and that’s 20% of the uncompressed size. So I’m thinking of including some C# code to decompress it.

But I did wonder if there was any kind of built in decompression, so you could add it to say Resources and have it decompressed automatically when read. I haven’t seen anything like that but it would be cool if if existed.

 

A free C Book – “C Programming Notes for Professionals”

A free C Book – “C Programming Notes for Professionals”

C Notes for Professionals Book coverThis has nothing to do with my ebook and was produced entirely by the Goalkicker.com project which produces free and very professional looking ebooks, I came across it just a few days ago.

The C Programming Note for Professionals is currently 327 pages long, a 2.4 MB download. It’s nicely laid out and professionally done. I’ve only flicked through it but it looks an excellent piece of work with 63 chapters currently. You can leave your email address and they’ll notify you of any changes.

There are almost 50 ebooks in total covering topics like Android, .NET, Xamarion Forms, Perl, PHP, MySQL, PostgreSQL and may other topics. This is an excellent library.  I don’t know who is behind this project but they deserve to be bought a lot of coffees…

An irritating bug with MonoGame/Android

An irritating bug with MonoGame/Android

Android Phone
Image by Iván Tamás from Pixabay

Bugs happen, it’s a way of life but when the bug affects you as a developer, it can be a tad annoying. I’ve found a bug and mentioned it in the MonoGame forums.

The bug occurs intermittently. I do a build then run the program on an Android phone. It starts loading, shows the splash screen then splat “The Content file was not found” message appears in Visual Studio.

This may be a bug in Xamarin or MonoGame. No doubt it will eventually get fixed but still a bit annoying. About the main workround I’ve found is rebuild everything. Start with the Pipeline tool- do a Build/Clean then a Build/Build. Then in the Project (in Visual Studio) do a Build/Clean then Build/Deploy which recompiles everything.

If the error still persists then it’s possible you have a typo; say a lowercase i instead of I in a filename. (I’ve done that once). Another fix though rather unsatisfactory is in the Project Properties, on the Options tab, right at the top is a checkbox Use Shared Runtime. If you untick that, deployment takes a bit longer. Instead of copying 3 MB which takes a second or so, it copies about 60 MB instead which takes a bit longer. I tried it but went back to the Clean and Deploy approach as copying was taking 10-15 seconds.

 

Ideas for multi-player games

Ideas for multi-player games

Simple word game
Image by brainygames from Pixabay

One side-project I’m working on that uses the MonoGame library involves creating a bunch of simple multi-player games. I’ve started with that Poker game (Top Banana or Manana Banana as I’ve called it) and the next one will likely be a variation of the game Boggle but not called that and not based on a 4 x 4 grid as Boggle is. I’m not daft!

The danger with doing this and just copying existing commercial games is you might get sued or a nasty cease and desist letter/email come your way if you infringe someones copyright or (far far worse!) their trademark. If you have a bit of money, you might be able to license the game from the original designer/creator but that’s probably not at all cheap. Games like Fluxx, Acquire, Settlers of Catan and Ticket-to-Ride are favourites but not something I shall be doing until and unless I can afford to license them.

Some games like card games are in the public domain and I’ve no qualms about producing my own version. Scheduled in after It’s-Not-Boggle is one based on 3-card Brag which is very easy to play and quite fun. I’m also trying to come up with an idea based on word Searching or Sudoku but as those are primarily solo-play games and not quite so easy to do multi-player.

But I’m sure there are multi-player games, i.e. Texas Holdem Poker that are legal to create my own so if you know any I might do, add a comment!

Very useful free resource website

Very useful free resource website

Metal
Texture Image by Eric Matyas.

Games need graphics, sound FX and music and Eric Matyas has an excellent website SoundImage.org. that provides them free.

It’s not just about sounds (apparently there are over 1,000 original sounds and music created by Eric) that you are allowed to use completely free in your games so long as you give him attribution but textures too. That’s a real bargain.

The texture shown was originally a 2048 x 2048 pixel graphic that I reduced in size for here. It came from, and there are a lot of other seamless metal textures on this page.

As I haven’t got a page setup for free resources, for now I’m adding this to the tips page.

Useful list of tutorials in C

Useful list of tutorials in C

 

Online educatioon
Image by Mudassar Iqbal from Pixabay

This GitHub repository has a pretty long list of beginner to medium sized project tutorials in C. There are over 30 on game development alone with titles like “Create a 2D platformer” and “SDL2 Isometric Game Tutorial“.

Other tutorials are on databases, networking, programming languages and operating systems plus even a bit on Blockchain. Recommended!

I’ve added a permanent link on the Links to C utilities page (on the top menu).

Programming Language Surveys

Programming Language Surveys

Arduino board
Image by Seven_au from Pixabay

It’s that time of year when several infrequent programming language surveys burst on the scene and I’m now beginning to doubt the veracity of the IEEE survey, along with the eternally mad Tiobe which has C at #1. The IEEE has C at #3 in popularity, but also counts Arduino as a programming language because people search for Arduino code. Such lack of rigour does you no favour chaps, so much for engineers!

Arduino (that’s one in the picture) is, like a Raspberry Pi; a hardware platform.  Given that Raspberry Pis have sold over 30  million which seems a lot more sold than Arduinos, why are they not listed?

RedMonk came out with their June survey recently (they do a small number each year)  which is based on popularity of GitHub project’s programming languages. They put C at 11th and C++/C# as joint 5th.  IEEE didn’t have C# in their  top ten which is completely at odds with every other programming survey. Even Tiobe has it at #5.

As always, I value Reddit’s programming language sub-reddits which has C at 9th and C# at 4th with C++ at 5th based on the numbers of members of each group. There is always a lag between the numbers shown on the summary and the actual numbers in each sub-reddit when you click into it.

Mobile game development progress

Mobile game development progress

Manana Banana Screenshot on AndroidDevelopment continues with the first game, which is a card game. I know the game as Top Banana, but I think that is the name of a commercial game, so for now the working title is Manana Banana. All it does currently is display the cards and backs as you can see. No photo this time, I learnt how to take snapshots on the phone (Hold down the power and Lower volume buttons at the same time) As it’s plugged in to my PC,. copying it across was not difficult.

This uses my virtual screen technology working on an 800 x 1400 virtual screen then scaling output onto the real screen which in this case on the Alps X27 Plus is 480 wide by 960 deep. As you can see I have a black rectangle at the top and the Android controls are visible at the bottom, neither of which I programmed for. I’ll get those fixed.

You play this game by clicking on the six top cards one-by-one and then tap the back of the card where you want to play that top card. So you end up with three poker hands. In this case I’d put the 7 and 9 on the top row for one pair, the two fives on the 2nd row also for a apir and the King and Jack for an Ace-high straight on the bottom row. The gap on the right will show the text of the hand so will say Pair, Pair and Ace Straight or something like that.

Next thing is making the cards clickable. That is the top six cards and the the three sets of two backs below. Once that’s done I’ll make that bit work then plug in the Jessie Chunn’s poker hand evaluation code to figure out what each hand of five cards is and more importantly give it a numeric score.

The gradient that covers the screen came from Unsplash.com.