Month: October 2020

39 Puzzles in C

39 Puzzles in C

Simon Grantham PuzzlesThose of you who have used the Putty utility to connect to a remote computer using SSH might recognise the name chiark. It’s also the home of various puzzles that are coded in C and they’ve made the source code available.  You can read about each puzzle via the online documentation.

The puzzles are one player games and run natively on Unix (GTK), on Windows, and on Mac OS X. As usual I’ve added these to the C code links as well. Puzzles are near enough to games to count! I’ve screen grabbed 15 of them but there are almost 40 in total.

If you like this sort of thing and have an idea for a game, take a look at the devel page. The puzzles are split into three parts, front, middle and back ends. If you want to implement a new front end (SDL2 anyone?) then you just change the front end.

A better random number generator

A better random number generator

Binary numbers
Image by Gordon Johnson from Pixabay

How’s this for a minimal RNG implementation in C?

// *Really* minimal PCG32 code / (c) 2014 M.E. O'Neill /
// Licensed under Apache License 2.0 (NO WARRANTY, etc. see website)

typedef struct { uint64_t state;  uint64_t inc; } pcg32_random_t;

uint32_t pcg32_random_r(pcg32_random_t* rng)
    uint64_t oldstate = rng->state;
    // Advance internal state
    rng->state = oldstate * 6364136223846793005ULL + (rng->inc|1);
    // Calculate output function (XSH RR), uses old state for max ILP
    uint32_t xorshifted = ((oldstate >> 18u) ^ oldstate) >> 27u;
    uint32_t rot = oldstate >> 59u;
    return (xorshifted >> rot) | (xorshifted << ((-rot) & 31));

is a website dedicated to random numbers using their algorithms, The whole site is good but I particularly like the party tricks page where they show that one of their random number generators generates a sequence that contains interesting things like source of a C file, zip files and text from hamlet.

More thoughts on shuffledness

More thoughts on shuffledness

Image by Hucklebarry from Pixabay

Thinking about what I said, it can’t be just about how far a card moves when shuffled but how much disordering occurs as well. If you shuffled the deck and discovered 7 cards in a sequence like 2,3,4,5,6 of hearts deep into the deck, they would have moved from near the top of the deck (an “ordered deck” is A-K in Hearts, Clubs, Diamonds and Spades) then it probably wasn’t a very good shuffle.

One way to measure “disorder” is to subtract each card’s ordinal value from it’s successor and sum up the absolute value of them . Ordinal value is the value 0-51 where 0 = Ace Hearts, 1 = 2 Hearts and so on. In an ordered deck the sum of all these subtractions will be 51. In a well shuffled deck I would guess it might be something like 1352 (52 x 26). Absolute value is the abs(x) function of x which is always positive if x is negative.  abs(-8) = 8. abs(8) = 8.

So now for shuffledness we have two values. Displacement and disorder. If both are calculated as a value between 0 and 1 then multiplying them together might work as a measure of shuffledness.

Here’s a very simple example of calculating the value for disorder. So far the calculations have never got a total much above 900, and not near 1352. I’ll run a few experiments and see the range of values.

// shuffledness.c : This measures how shuffled a deck of cards is
// cards are held as values 0-51 in a 52 int array.

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

int deck[52];
time_t t;

// Order the cards 0-51. 0 = Acew Hards,13 = Ace Clubs,26 = Ace of Diamonds and 51 = King of Spades
void InitDeck() {
	for (int i = 0; i < 52; i++) {
		deck[i] = i;

// Works on glovbal array deck and calculates a value for how displayed each card is
float CalcDisorder() {
	int total=0;
	for (int i = 1; i < 52; i++) {
		total += abs(deck[i] - deck[i - 1]);
	printf("Total = %d\n", total);
	return total / (52.0f * 26.0f);

// Shuffle a deck by swapping two random cards a specified number of times
void ShuffleDeck(int numtries) {
	int firstIndex, secondIndex;
	for (int i = 0; i < numtries; i++) {
		do {
			firstIndex = rand() % 52;
			secondIndex = rand() % 52;
		while (firstIndex == secondIndex);
		int value = deck[firstIndex];
		deck[firstIndex] = deck[secondIndex];
		deck[secondIndex] = value;

int main() {
	/* Intializes random number generator */
	printf("CalcDisorder() == %f\n", CalcDisorder());
	return 0;

That’s about 50 lines long. I’ll work on it and add the displacement calculation and try and get a maximum figure the the disorder calculation.

Visual Studio Code Now supports ARM

Visual Studio Code Now supports ARM

Visual Studio Code 1.50Which means it supports Raspberry Pi. Of course I’ve been using it thanks to the version but it’s convenient now that both 32-bit and 64-bit ARM are available to download from the official site. As always, make sure you pick the .deb version either ARM for the 32-bit Raspberry Pi OS or ARM 64 if you have the 64-bit.

Apparently there is also a new C/C++ extension from Microsoft that I shall have to check out as well.

Also this means you can do remote code development. The idea is that you run Visual Studio Code on your PC/Mac whatever and connect to a program running on your PI (over WifI or a Network cable) using SSH. See the VS Code documentation for remote development.

Ingenious games in just 13KB of JavaScript

Ingenious games in just 13KB of JavaScript

Last Spartan screenshotI’m not fond of JavaScript but I am still in awe at the ingenuity of people who created a HTML5 game in JavaScript in just 13KB. There’s an annual competition called Js13K and this year there were 220 entries and prizes of $20,000 in total.

When you think that many graphics are way bigger than 13KB this is even more of an accomplishment. It means those games have to mostly draw their own. graphics rather than use prerendered graphical images. It helps that HTML5 includes a canvas drawing area and instructions in JavaScript to draw into it.

The GitHub Blog featured the top ten from this years competition. The picture comes from The Last Spartan which I really liked. Ironically the screen grab image was 121KB, almost eight x the size of the actual game!

If you are ever stuck for ideas for games, take a look at these. Being JavaScript, you can right-click in your browser and View Source (Chrome) or View Page Source (Firefox). Of course, to achieve 13KB, many of them have been minified which means getting rid of all spaces, carriage returns and renders it rather unreadable. This is what it looks like.

Screenshot of last Spartan source code

However the internet taketh and the internet giveth. If you paste this (or any of the source listings) into an online deminifier (aka beautifier) such as then you get all 1622 lines laid out in immaculately indented glory.  It’s actually 73KB in size as a normal listing and still very impressive.

There’s no reason why games can’t be done this way i.e. drawing graphics in C+SDL2 though I doubt I’d get them down to 13KB. My asteroids game which was 2200 lines of C generates a 96 KB exe. But when you add in images, SDL code and sounds etc it comes out at just under 35 MB.

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.

How to measure how shuffled a deck of cards is

How to measure how shuffled a deck of cards is

Opened deck plus new deck of cardsI first thought about this when I wrote the program to shuffle  deck of cards using a riffle shuffle. If you are given a deck of cards (or pack of cards as us Brits say), how do you discern just how shuffled the pack is? Can you calculate a numeric value for it say a % ranging from 0 to 100?

I believe it’s possible.  Here’s how.

  1. Start with a default pack of cards in perfect sorted order. Out of curiosity I found an unopened deck oif Waddington’s cards and opened it as the photos show. The cards in the pack were arranged in order King, Queen, Jack down to Ace in each of the four suits Heart, Clubs, Diamonds and Spades in that order. Let’s reverse the card rank ordering so a full deck starts with Ace Hearts through to King Hearts, Ace of Clubs to King of Clubs and so on with the last card being the King of Spades.
  2. Instead of referring to cards by their rank and suite lets just number them 0-51. 0= Ace of Hearts, 51 = King of Spades.
  3. When a deck is shuffled, each card can move to any other position. So a measure of shuffledness is calculating how far the cards moved in aggregate.
  4. However the card movements have to be “normalized”. Cards 0 and 51 can move to any of 51 positions while cards 26 (King of Clubs) and 27 (Ace of Diamonds) can only move a maximum of 26 places.
  5. I’m looking at the absolute value of a movement so if card 3 moves to position 47, it has moved 44 places and likewise card 47 moving to position 3 moves 44 (not -44) places.
  6. So to normalize a card’s move, divide its move by its maximum possible distance it can move. So wherever card 0 moves divide it by 51, card 1 by 50, card 26 ‘ move by 26.
  7. Sum up all 52 normalized move’s and multiply by 100. That is the measure of shuffledness.

I’ll write a C program to measure how shuffled a deck is and publish it in a day or two. Also here is a conversation on Reddit about shuffling cards.


The biggest problem with C

The biggest problem with C

Created on

The biggest problem is that a single letter language name like C (or D) makes it almost impossible to search accurately on the web. I did a search for C jobs and found 3,602 C jobs on (I’m not looking for a new job BTW!),

Yeah I didn’t believe it either and when I looked at some of the jobs well there are a few but it also finds jobs for C# (not the same at all) or C/C++ which you just know is C++ really. So there’s probably less than a dozen jobs instead of 3602.

Also, job sites have this weird thing where they shows job adverts from multiple recruitment agencies so the same job gets advertised 3-4 times over. So my rule of job applications is divide the estimated number of found jobs by four to get a more accurate figure.

Being realistic, if I was looking for a job programming in C, I think the embedded market is probably the only main way to go and I know nothing about embedded C!  You have a far greater chance of getting a job if you program C++ or C# (if you are limiting it to programming languages that begin with C) rather than C itself.

C is one of those languages that’s really useful to know but won’t get you a job on its own.

It’s probably also the reason that longer programming languages like Go have adopted a convention of suffixing lang to their website name since about 2011. Shorts words like Go have multiple meanings and adoptions. I can’t imagine players of the game Go were too impressed when Go the programming language appeared yet at least the website is golang. The same is true for Dart which is not only best known for being a sharp pointed flying thing but is also an acronym (Dublin Area Rapid Transit) . The programming language website is dartlang.




Microsoft appears to reembracing game development again

Microsoft appears to reembracing game development again

Image from Microsoft learn games

They have just set up this webpage according to the announcement on one of their dev blogs. Of course there’s irony that they include MonoGame, because if it hadn’t been for MonoGame, all of the XNA library code would have been lost. XNA was Microsoft’s own game development technology that got to version 4 and was then abandoned.

There’s also a page of tutorials teaching Godot, Unity and a backend service called PlayFab. It never ceases to amaze me that Microsoft don’t invest just a little bit more into their games development. They’ve got lots of different platforms including various XBox consoles, PCs, Mobile and so on that can all be programmed using Microsoft related technologies using Microsoft supplied software that is very good and often free.  It often feels like they’ve backed off from the days when they were publishing games.