Category: C

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 / pcg-random.org
// 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));
}

https://www.pcg-random.org/

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

Shuffling
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 */
	srand((unsigned)time(&t));
	InitDeck();
	ShuffleDeck(1000);
	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.

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

Wordart
Created on wordart.com

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 TotalJobs.com. (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.

 

 

 

Creating a maze in C

Creating a maze in C

Backtracking mazeThe internet is well not quite awash with maze generators but there certainly are plenty of them about. This one is 100% written in C.

There’s a #define, commented out by default that enables prim’s algorithm. The default is to use depth-first search instead. If you uncomment the #define movie,. it will save out the maze as a series of .bmp files.

I’ve added the link on to the C Code Links page.

 

Curated C library

Curated C library

Rusty links
Image by Positive_Images from Pixabay

Back when I wrote the About.com website I created (curated!) a list of useful C libraries. You can still see if you look on archive.org, for instance this is it back in 2013 when I finished working on about.com.

Now that library was general stuff, not with a games (or loosely games related) like this site but many of the links still work. Back then most websites used http not https, so if a link doesn’t work, change the url to https and try it again. Some links will have ‘rotted’; its inevitable on the web (and I never miss a chance for a visual pun!) but all of it was open source so it probably has a higher chance of it still being around.

I will also be trying to salvage games/games related links from there and add them to my sites games links or C code links. For instance I found the CBM-64 BASIC and 6502 emulator in C by developer Michael Steil on GitHub and have added them to the C code links.

New C Tutorial published on arrays

New C Tutorial published on arrays

arrays
Image by Andrew Martin from Pixabay

This continues the series of C tutorials. In this one, I’m looking at arrays and how to declare them. An array is an essential part of C programming, but they are always fixed size. You can’t change the size at runtime or specify the size in a variable before declaring it unless you declare them using pointers which is a bit advanced for the fourth tutorial.

The picture is a metal grid but it illustrates what a two dimensional array [5][7] might look like. I looked but I couldn’t find any pictures of seven dimensional arrays!

Discussing the use of break in C

Discussing the use of break in C

C
Image by pramit marattha from Pixabay

On the C programming subreddit there’s a discussion where a student has been old he should never use break in C. As one comment says, “The teacher is a nitwit” and I agree with that comment.

I use break (a) to exit loops early and (b) to exit every branch of a switch statement unless I want it to drop through or else that case does a return. I use switch a few times in the asteroids source code and there’s examples of all three instances of using breaks, using returns and dropping through cases (no break).

Here’s an example of the latter. It controls the logic of what to display when you start or restart a level after losing lose a life. If you have one life left it prints “Last life” otherwise it prints how many you’ve got. Actually I think it’s a bit of an overkill and an if else would have done just as well

 

	switch (Player.lives) {
		case 1:sprintf_s(buffer, sizeof(buffer), "Last Life!");
			break;
		case 2:
		case 3:sprintf_s(buffer, sizeof(buffer), "Lives left: %d", Player.lives);
			break;
		}

So probably not the best example of using a switch! But it illustrates a point.