Month: December 2020

The L game by Edward de Bono

The L game by Edward de Bono

The L Game
Image from Wikipedia

I bought a book The Five Day course in Thinking by the author Edward de Bono when I was at University. It included a seemingly very simple two player strategy game called The L Game.  If you’ve heard of the phrase Lateral Thinking that was invented by him back in 1967.

On a 4 x 4 board there are two L shapes and two neutral single pieces. To win you just have to move your L shape and (optionally) one of the neutral pieces so that your opponent can’t move his L shape.

I’ve had a cursory search for C source versions of this game and there are bound to be more than the one I found which was written for an Arduino WifiBoy Pro. There’s a downloadable zip file which contains a file wbpro_chess_L.ino. Despite the extension, it is a C source code text file.

If you are looking for an interesting programming problem then create a computer opponent for a game. The good thing about this is, its so simple graphics wise that you could draw the board in a console with B = Blue, R = red and 1 and 2 the two neutral pieces like this.

1RR.
.BR.
.BR.
.BB2

 

New tutorial on installing SDL on Linux

New tutorial on installing SDL on Linux

SDl Demo programWell you might say, “Don’t many Linux distros have SDL installed so people can play games?” and the answer is yes but not the development files and headers, and that’s what this shows you how to do along with a simple program to test that you can compile and run.

You’ll also need clang or gcc installed but as you can do that with a simple sudo apt install clang, it’s hardly worth a tutorial on its own.

However you also need to install VS Code and the C/C++ extension. Go to the VS Code website, download the Linux x64 version and double click on it to install it. After that from a terminal type code and it’ll appear. You then need to select extensions (5th icon down the left hand side) and pick the Microsoft C/C++ extension and install it.

I’ve added a new tutorial on the Tutorials page How to Install SDL on Linux. That includes a link to a demo file (its just above the screenshot) containing all three source code files and four VS Code configuration files for VS Code.

This program is almost identical to the asteroids_ch25 file (it draws lots of random size and colour rectangles on screen) but has been upgraded for Clang 10 and also what looks like a bug with search paths. There’s an extra line in Tasks.json to include the path to the SDL2 header files or you’ll get a can’t find a particular SDL header error when you compile.

Building code with VS Code is easy to understand once you “get” how the Folder works. I always keep the .vscode folder in there with the four C/C++ JSON configuration files and all source for that whatever it is you are compiling.  In the screenshot below (from WinSCP), you can see the path is /home/david/Projects/Examples and it contains the .vscode folder the three source files and demo which is the compiled code.  In VS Code I opened Examples as the Folder.

VS Code Folder

 

The .vscode folder is greyed out because the . means it’s normally hidden.

Coding a text adventure in C

Coding a text adventure in C

Text AdventuresText adventures have been around since the likes of Colossal Cave which I first played in 1980. They were quite popular on the early home computers like ZX 81 which were quite limited in RAM and capability. With the capacity of modern computers there are Interactive fiction (the modern name for adventure games) games with over a million words of text.

I suspect I’d probably want to code them in another language because C isn’t the best language when it comes to text. Nevertheless other have gone ahead and there’s an almost complete (20 out of 23 lessons) on how to program a text adventure in C on GitHub.

It’s a fine piece of work and some of the 20 articles like 20. Combat are quite long with lots of annotated code. At the bottom of each page you can download the source code on that page as a zip file or run the sources on repl.it. If you are learning C the line-by-line annotations really help explain why something was done.

The C template library

The C template library

Texture templateC of course doesn’t have generics or templates like C++ does, but I came across Gustav Lou’s C Template library this morning. It provides C equivalents to the following C++ template libraries. Each is done as a header file that you include.

deq.h -> std::deque
lst.h -> std::list
pqu.h -> std::priority_queue
que.h -> std::queue
set.h -> std::set
stk.h -> std::stack
str.h -> std::string
vec.h -> std::vector
 

The page on GitHub shows how to use libraries with an example of vector. The string equivalent library str.h would be an interesting one to see just how much of C++ string is supported.  C would still never be my language of choice for anything text heavy but if this is better than strcpy, strcat etc. I’ll happily use it.  Likewise list and vector. From memory C++ std::array is just a wrapper around the C standard array!

A possible defer mechanism for C

A possible defer mechanism for C

Next big thing signI remember that some other programming language (possibly Go) has a defer mechanism. You can tell it to defer a function call until the end of the function. I think this means, even if you do an early return that all functions that have been deferred will still run.  It’s a handy language feature. Alternatives to it ion say C# are try … finally where the finally ensures that code gets runs.

The reason for mentioning this is it’s a possibility for a future inclusion in the next C standard.  There’s a quite long article about defer listing benefits. But even better the author Jens Gustedt has provided a reference implementation of it on GitLab.

I’m all in favour of this. Adding new features to C is not something to be done lightly but error checking and handling in C has always been a bit iffy. I’ve never used a SetJmp for example.  I do hope that defer gets added to C though I can’t see it being there for a few years.

Tilengine – for creating Retro games

Tilengine – for creating Retro games

TileengineTilengine is an open source, cross-platform 2D graphics engine in C for creating classic/retro games with tile maps, sprites and palettes. It’s intended use is for developing 2D games of old.

Written in C99, it can be used on Windows (32/64), Linux PC(32/64), Mac OS X and Raspberry Pi. Internally it uses some SDL2 libraries. There are bindings for other programming languages as well as native support for C/C++.

You’d use this for parallax effects using sprites over background layers. It makes it easier than coding yourself. In particular sprite animation is excellent with pixel perfect collision detection and 17 different functions for manipulating them. Rather than roll my own in my Asteroids game I could have used this.

The other documentation is a little spare with placeholders, but I imagine you can work it out from the header files and samples.

How to read a text file into memory in C

How to read a text file into memory in C

Words readAs part of the crossword grid packing utility, the first stage is building the list of words in a structure in RAM. To keep thing simple I’m going to use an array of char * pointers. The array is limited to a maximum 20 words. If any more are read then they will be discarded.

Just to prove that it worked, I wrote this in Visual Studio and ran it in the debugger. You can see elements 0-9 in the screenshot with the source code in the background.

This is the listing of the program. Note, it doesn’t have a function to free up the memory dynamically allocated for each of the words.

You might wonder about these lines (25 and 26).

	if (line[len-1] == '\n')
		line[--len] = '
	if (line[len-1] == '\n')
line[--len] = '\0';
';

This is needed because when you use fgets to read a line of text it includes a line feed at the end. So the first line in the file Engine is actually 7 characters long with a terminating \n. The malloc on line 27 allocated enough RAM for len + 1 to allow for the terminating 0 at the end of each string. In line 33, if you are on Linux replace strcpy_s with strncpy. Both are safe versions of strcpy. Here’s the full listing.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#define MAXWORDS 20
#define MAXWORDLENGTH 32

typedef char* pWord;
pWord allwords[MAXWORDS];

int ReadWords(char * filename) {
	memset(allwords, 0, sizeof(allwords)); // clear it
	char line[MAXWORDLENGTH*2]; // double max size just in case
	FILE* fwords;
	int errnum = fopen_s(&fwords,filename, "rt");
	if (!fwords) {
		printf("Missing word file %s", filename);
	}
	int wordIndex = 0;
	while (fgets(line, MAXWORDLENGTH, fwords)) {
		int len = strlen(line);
		if (!len)
			break;
		if (line[len-1] == '\n')
			line[--len] = '
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define MAXWORDS 20
#define MAXWORDLENGTH 32
typedef char* pWord;
pWord allwords[MAXWORDS];
int ReadWords(char * filename) {
memset(allwords, 0, sizeof(allwords)); // clear it
char line[MAXWORDLENGTH*2]; // double max size just in case
FILE* fwords;
int errnum = fopen_s(&fwords,filename, "rt");
if (!fwords) {
printf("Missing word file %s", filename);
}
int wordIndex = 0;
while (fgets(line, MAXWORDLENGTH, fwords)) {
int len = strlen(line);
if (!len)
break;
if (line[len-1] == '\n')
line[--len] = '\0';
pWord pNewWord = (pWord)malloc(len + 1);    // line 27
if (!pNewWord) {
printf("Error allocating memory");
break;
}
if (wordIndex < MAXWORDS) { // can add to list
strcpy_s(pNewWord, len+1, line);  // line 33
allwords[wordIndex++] = pNewWord;
}
}
fclose(fwords);
return wordIndex; // = Count of words
}
int main() {
int numWordsread = ReadWords("words.txt");
}
'; pWord pNewWord = (pWord)malloc(len + 1); // line 27 if (!pNewWord) { printf("Error allocating memory"); break; } if (wordIndex < MAXWORDS) { // can add to list strcpy_s(pNewWord, len+1, line); // line 33 allwords[wordIndex++] = pNewWord; } } fclose(fwords); return wordIndex; // = Count of words } int main() { int numWordsread = ReadWords("words.txt"); }
A challenging Puzzle – fitting words in a grid

A challenging Puzzle – fitting words in a grid

\scrabble wordsYou are given a list of words. You have to fit them into a grid so that the grid is as small as possible. The words can go horizontal or vertical and can use letters from other words (like in Scrabble). But you can’t have words next to each other except where they share letters like in the picture above. MN BTW is not a valid Scrabble word so this is wrong! (I er borrowed it from somewhere!)

So words can be placed anywhere, in either orientation. Evaluating all the possibilities could probably be done by brute force. But for each word in each position on the board there are n-1 words to be fitted afterwards. Do you try and fit in each alternate word in a different orientation like horizontal then  vertical then horizontal?

If there are ten words to fit in say in a starting grid of 20 x 20 and the first word is 6 characters long then it can fit in 15 different places along the top line and on each of the 20 lines so that’s 300 positions. Then if its vertical there another 300 positions. That’s 600 positions to try. And for each of those 600 there’s 9! different combinations of words to fit in. 9! = 362,880.

Of course if the first word and the second word have no letters in common then it may be as well to skip that 2nd word and go onto the 3rd and so on. We want to keep the grid from getting too large with unconnected words. Also We might limit the first word to start in th 6 positions in the top row and maybe only the first and 2nd rows. That vastly reduces the number of combinations to try out. But still it’s a tough thing to program.

C isn’t usually the best language to program anything with text in, but in this case, we’re not building sentences or searching, just looking at arrays of characters and so it might just be suitable.

I’m going to have a go at this and see if it can be done and if so I’ll publish my code but this may take a few days. If so then it could be used as a basis of a word search generator though the rules about words being next to each other could be relaxed plus words run forwards and backwards in both horizontal and vertical orientation and also diagonal.

Previous Puzzle Answer

This was “If I have the integers 4,5,6,7 and 8 and a special C function f so that f(4)=2, f(5) = 5, f(6)=10, f(7)=40 and f(8) = 92. What is the function f?”.Bit of a trick question this as the function is returning the number of unique Queens that could be fitted on a chess board of size n (4×4,5×5..8×8) without being able to attack each other.

Philip Jama has posted a C program on GitHub to arrange the number of Queens on a chessboard of the specified size. So the function wasn’t really a function…

 

Configuring VS Code for C/C++

Configuring VS Code for C/C++

Visual Studio CodeMost of the time I’ve got by configuring VS Code but recently I wasted an hour having managed to completely mess it up. I have a Raspberry Pi version of Asteroids which adds temperature display and game pad support. It’s a useful way to check when I burn a new SD and install VS Code, clang, and all the libSDL2-dev codes that everything is there. If it’s not it won’t compile.

Only this time because I was doing other stuff I decided to create a Projects folder which contained the Asteroids folder and some other stuff and opened Projects as the Folder.  I copied the hidden .vscode folder into Projects/Asteroids and tried to compile. Errors. Lots of compile errors. I repeatedly edited the tasks.json file with altered paths but no joy. I spent an hour trying before closing the Folder and reopening it with Asteroids as the Folder and with the original tasks.json. It compiled perfectly.

So the moral of the tale is just keep the level of folders down to one when you open the Folder on the files you are compiling. Do not have subfolders.

Interesting number sequence

Interesting number sequence

Chess Set
Image by Clker-Free-Vector-Images from Pixabay

Here’s an interesting puzzle (well for some people). If I have the integers 4,5,6,7 and 8 and a special C function f so that f(4)=2, f(5) = 5, f(6)=10, f(7)=40 and f(8) = 92. What is the function f? And no it’s not a simple array containing the numbers 2,5,10,40,92 at positions 4-8!

I also checked the OEIS (Online Encyclopaedia of Integer sequences) and it’s not in there either. Years ago I was fooled by a integer sequence that was the maximum number of electrons in orbital shells but its definitely not that.

Here’s a minor clue. It is game related. Answer in a day or two.