Category: C#

How to visit many many places in one go

How to visit many many places in one go

green points
Image by Gerd Altmann from Pixabay

No this isn’t turning into a travellog.  Imagine a huge square. It has 33,554,432 points along an edge. The entire square would thus have 1,125,899,906,842,642 points in it. That’s 250 or 3210 points. (Yes those two numbers are the same!)

Now how about contriving an algorithm that will pick a random point in this square and keep picking each point but never more than once? Eventually it will have picked every point.  If it could visit a million points every seconds, it would take something like 35.7 years to visit each and every point.

So assuming you could create an algorithm, how large would it be? How about three lines?

        public static ulong Nextulong()
            ulong result = ((aUVal * ULast) + bUVal) % aUVal;
            ULast = result;
            return result;

That’s in C#. The values for aUVal and bUval are

        const ulong aUVal = 1125899906842597;
        const ulong bUVal = 1051122009542795;

A uLong is just an unsigned long. That’s a 64 bit unsinged int.
This is an example of a Linear Congruential Generator BTW.

Posted in C#
How to count lines of code in Visual Studio

How to count lines of code in Visual Studio

Calucating Code metrics in Visual StudioUntil this morning, I didn’t realise that Visual Studio (even the free Community Edition) has this built in. I was curious to see how much code I’d written so far for my game processing engine.  Development comes in leaps and bounds during evenings and weekends.

Visual Studio has Code Metrics in it. You can do this for any project that builds correctly. To show this you have to do View => Other Windows => Code Metrics Results. That displays the window. Then you have to go on the Analyze Window, and click Calculate Code Metrics.

Lines of code

However you might want to take these with a pinch of salt. As I understand it, Lines of Source Code is calculated from the il code output from the compiler. The last column (Lines of executable code) suggests that most of my program is comments which is wrong! There is however a fair amount of data in the form of Constructor initializations, and one file of 1290 lines has over 1,000 such initializations.  You can read what the other columns mean and everything you ever wanted to know about code metrics on the Microsoft site.

Out of curiosity, I manually counted the number of lines in this project. There are 15 files and they added up to 3700 lines but that includes comments and blank lines.  A quick search for // found 119 which probably means I should improve my commenting. Blank lines is probably something similar. So we’re talking 3700-1000 (constructor initializers)-119 (comments) -119 (blank lines) = 2462 lines of code so far. That’s working tested code mind you.


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.

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.

Actually going schemaless in C#

Actually going schemaless in C#

JSON Image
Image from

Back in August I talked about going schemaless and I’ve made some progress since then. I’ve created a number of C# classes, many of which include single and in one cases a 2D array of things I want persisted to disk.

I use JSON (JavaScript Object Notation) files to hold the data.  So long as I’ve defined those classes with Properties using Get and Set, the JSON converters in .NET handles it all very nicely.

For example, in my game I have a CityArea class which includes a List<BuildingType> as well as several public properties.

This saved out as JSON like this:

      "buildings": [
          "Name": "College",
          "Size": 2,
          "Percent": 60,
          "Cost": 50,
          "Type": 11
          "Name": "Gallery",
          "Size": 2,
          "Percent": 40,
          "Cost": 150,
          "Type": 23
and ends...
      "State": "R",
      "Type": "F",
      "Density": "L",
      "Points": 46,
      "AreaName": "Newfane"

The whole JSON file has 1500 buildings scattered amongst 100 areas (10 x 10) and is 11422 lines long. The file is 234Kb long. Though that’s with indentations. I could remove that but for now, during development, it makes the file easier to read.

These are the two class definitions (I’ve removed extraneous stuff from them),

class BuildingType : ICloneable {
        public string Name { get; set; } = "";
        public BuildingSize Size { get; set; } = BuildingSize.bsNone;
        public int Percent { get; set; }
        public int Cost { get; set; }
        public BuildType Type { get; set; }

class CityArea {
        public char State { get; set; }
        public char Type { get; set; }
        public char Density { get; set; }
        public int Points { get; set; }
        public string AreaName { get; set; }
        public static List AllBuildings = new List();		

This is the code to save out areas (which is List<CityArea> areas to the file. I found this by reading the Microsoft documentation about Serialization and deserialization. It’s pretty good stuff and the code for saving these structures are these pretty short methods.

        public bool SaveToUTF8(string filename)
            var options = new JsonSerializerOptions
                WriteIndented = true
            var bytes = JsonSerializer.SerializeToUtf8Bytes(areas, options);
            File.WriteAllBytes(filename, bytes);
            return true;

and this is the code to Load it.

        public bool Load(string filename)
                var bytes = File.ReadAllText(filename);
                areas = JsonSerializer.Deserialize<CityArea[][]>(bytes);
            }catch(Exception e)
                Error = $"Failed to load {filename} because {e.Message}";
                return false;
            return true;

I haven’t timed either Load or Save but they are fractions of a second.

How to create an Alphabet bitmap in CSharp

How to create an Alphabet bitmap in CSharp

Letters generated by the programHere’s another short utility. I have been looking for a decent alphabet to look in my next game (called HogWash) . As before, I want to create a sprite sheet with letters. But every alphabet set that I found had issues with kerning. I kid you not, usually but not always with M, W, or even Q.

Even when I put together a sprite sheet manually, the editor didn’t quite get it right and letters didn’t quite fit the grid. So to simplify it, here;’s a 50 line C# program that takes the letters you supply in a string, combined with a font (Liberation Mono- from Red Hat) and a brush (black solid). It does a double loop that I exit with a goto (shock horror!) when it reaches the a terminating * in the string I supplied.

That is the graphic file above that the program below generated. As you can see the letters are far enough apart so no overlapping. Just put in your path where I have for the source and dest consts. You can use this technique for building sprite sheet.

// Author D. Bolton You are free to use and copy this program as you wish but please leave this line in.
using System;
using System.Drawing;
using System.Drawing.Imaging;

namespace buildfont
    class Program
        const int LetterWidth = 100;
        const int LetterHeight = 120;
        const string source = "Your path"
        const string dest = @"YourPath\letters.png";

        static Bitmap allLetters = new Bitmap(LetterWidth * 8,LetterHeight * 5);

        static void Main(string[] args)

        private static void BuildOneImage()
            var font = new Font("Liberation Mono",95);
            var brush = new SolidBrush(Color.Black);
            var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ*";
            Console.WriteLine("Creating letters.png");
            var aty = 0.0f;
            using (Graphics g = Graphics.FromImage(allLetters))
                var strindex = 0;
                for (var y = 0; y < 5; y++)
                    var atx = 0.0f;
                    for (int x = 0; x < 6; x++)
                        string aLetter = str[strindex++].ToString();
                        if (aLetter == "*") goto Done;
                        g.DrawString(aLetter, font, brush, atx, aty);
                        atx += LetterWidth;
                    aty += LetterHeight;
            allLetters.Save(dest, ImageFormat.Png);
Now for some mobile networking

Now for some mobile networking

Early taxi app screenshotNot the face to face type but actual networking. This is needed because I’m working on a game server. My mobile game (Manana Banana) will become networked enabled and thus multiplayer.  C# is ideal for this type of thing but I’m not using the networking capability of MonoGame instead managing the whole lot myself.

Back a few years ago when I was a full-time mobile developer I wrote an app that was used by taxi drivers. It was a conversion of an Android App (I wrote it from scratch running on an iPhone based on the Android source code).  There’s a curious architecture with such apps because not only is the a user interface but in the background the app was “chatting” over 3G to a central server (written in VB6 I kid you not) which sent an “are you alive?” message every six seconds to every driver’s phone.

It was not a traditional client-server architecture but the kind of system where the driver could send a message to the server or the server could send a message to the driver. 

What this meant was the app was always keeping one eye on the 3G, getting messages and then it might for instance popup a screen saying “There’s a job from x to y. Do you want it?”. If the driver said yes then the app would receive details and show the driver the route to the pickup point. If the driver didn’t respond within 30 seconds or said no then the program would pass that back to the server,

What is a ConcurrentQueue?

C# has an advanced data structure called a ConcurrentQueue<t> which is a thread safe generic queue. I used two of these, one for a receive queue and one for a transmit queue in conjunction with a thread that never finished. All the 3G stuff was done using C# TCP/IP clients and ran in this thread. Messages that came in were put on the receive queue and could be popped off and processed in the main program. Messages to send out from the main program were put on the transmit queue and sent out in the thread. It was a very clean way of separating the main application running in the main thread from the 3G running in a background thread. 

Compared to the Android program which was all running in one thread and polled the 3G, I was told by my drivers that my app felt much more responsive!   The screenshot above was a very early image of it. It had a very simple UI where each screen of controls (Views in iOS parlance) was built up dynamically.  

Also C#/Xamarin has a way of getting from a thread to the main thread on iOS. You cannot update any controls from any thread only from the main UI thread.  There’s a method called InvokeOnMainThread for the Xamarin iOS controls. See this Microsoft/Xamarin documentation on how to use it. So that’s what I’ll be doing in my networked game.  

Interestingly because I’m managing everything, the TCP/IP messages can be very small, under 20 bytes each. This allows a very high throughput. 

Some awesome listings

Some awesome listings

Awesome stamp
Image by Pete Linforth from Pixabay

It has become a thing to label a big collection (usually open source) as awesome and there are several such collections around for many programming languages. In fact the C code collection’s first entry is to one of them.

That said they are pretty awesome, often having links to many related and useful open source projects. My only problem with the likes of GitHub and SourceForge etc. is the sheer quantity of excellent stuff on there. These awesome links are one way to “tame” them.

So now there’s a new link up top for C# and MonoGame links and a couple of entries to start it off.


MonoGame – How to make a clickable button

MonoGame – How to make a clickable button

Clear Button with one card clickedI’m using this in Android games but the principle applies to any MonoGame game. Here clickable and touchable mean the same.

You need three things to make something clickable.

  1. The area. For simplicity sake this will always be rectangular.
  2. The Action. When you touch (or click it), you want it to run code.
  3. An id of sorts. If you have multiple buttons etc, you meed to distinguish them.

We’ll use an int for 3. Use const ints to give it a name rather than being a magic number.


When you click whatever, the Event should include the ide so let’s define the event Type first.

public class ButtonClickedEventArgs : EventArgs
    public int Id { get; set; }

Not rocket science is it!

Now lets define a ClickButton class.

public class ClickButton
    public int Id { get; set; }
    public Rectangle TouchArea { get; set; }
    public Action<object, ButtonClickedEventArgs> AnAction { get; set; } = null;

    public ClickButton(int id)
        Id = id;
        TouchArea = new Rectangle(0, 0, 0, 0);

Again nothing too complicated. There’s an int Id which which is set in the Constructor, a Rectangle TouchArea and an Action which is defined to include our ButtonClickedEventArgs.

Here;’s some example code. I’ve defined a graphic for a Clear button in my game and this is loaded as usual in the LoadContent().  I’ve also defined the button in Class declaration.

ClickButton ClearButton;

In LoadControl(), this is also initialised. Here’s it’s two line. It could be done in one, by altering the constuctor.

ClearButton = new ClickButton(1);  // 1 is the id
ClearButton.AnAction += ClearCards;

ClearCards is a method that does something when the button is cleared. This matches our Event handler as it has the usal two parameters for an Event except the args is our ButtonClickedEventArgs.

private void ClearCards(object sender, ButtonClickedEventArgs args)  {
   // all the code here, not shown

Where is the TouchArea defined?

So are we all setup ready to rock’n’roll? Well not quite. We haven’t said exactly where the TouchArea is. That of course depends on where we draw the button. In my game, the ClearButton moves across. It’s absent when all six cards are present but as soon as one has been touched and a back card touched to move it, the Clear Card appears. In the top image you can see it to the right of the five top cards. I had clicked the seven of clubs when it was in the top row then the first back on the top row of the three rows.

For my next move I clicked the ten of diamonds and the second back on that first row where the ten of diamonds no wit. It now looks like this and the Clear Button has moved over.  If I click the Clear button it will move the seven clubs and ten diamonds back to the top row and replace them in the first row with backs.

Second clickTo set the TouchArea of the ClearButton, I do it in the Draw method. It’s as simple as this:

if (hand.Count < 6) // Draw ClearButton on end
    spriteBatch.Draw(clearButton, new Rectangle(x, y, cardWidth, cardHeight), 
        new Rectangle(0, 0, cardWidth, cardHeight), Color.White);
    ClearButton.TouchArea = new Rectangle(x, y, cardWidth, cardHeight);

There’s actually a small bug visible. When you click a top row card, the game highlights it by reducing its opacity to 0.5. If you look at the ten of diamonds, you can see it still has that reduced opacity; it should have been restored to 1.0 when it was moved to the first row. The same is true in the top picture for the seven clubs! Easily overlooked but just a one-line fix.

Some Touchy Code

The very last bit is to fire touch detection and this is done in the Update() method. When you touch the screen, calling Touchpanel.GetState() returns a collection of touches. This is my code. It cycles through the touches collection, gets the X, Y position of each touch and adjusts it to match the virtual screen coordinates. (Drawing to a virtual screen means this looks the same on every Android irrespective of its physical screen sizes and resolution).

touchState = TouchPanel.GetState();
foreach (var touch in touchState)
   if (touch.State == TouchLocationState.Pressed)
         var x = touch.Position.X / xRatio; // adjust for virtual screen
         var y = touch.Position.Y / yRatio;
         CheckClickedTop(x, y, hand);
         if (pickedCard == null) return; // no point checking further...
         for (var i = 0; i < 3; i++)
            CheckClickedBottom(x, y, commonCards[i], true);
            if (hand.Count == 6) continue; // All top cards so no ClearButton visible
            // Check if Clear button
            if (ClearButton.TouchArea.Contains(x, y))
                  ClearButton.AnAction(ClearButton, new ButtonClickedEventArgs() { Id = ClearButton.Id }); 

The top cards are held in a class called hand and the bottom three rows are held in CommonCards[3] each of which is a hand. The CheckClicked.. methods cycle through the cards in the hand comparing coordinates to see which card if at all has been clicked. If it has it calls the AnAction Event for the one clicked. The very last if shows how this works to check if the ClearButton was clicked. I’ll simplify this code by moving it into a ClickButton method.

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