Author: David

It’s that book again

It’s that book again

Basic Computer games bookOne of my favourites and one that I actually bought twice in my life and of course I have mentioned before. Originally I bought it back in 1982 and more recently in 2015 along with the sister “More Computer Games” book. The reason  I mention it because there’s an ongoing project to do the games in it in languages other than BASIC.

The languages they’ve chosen are:

  • Java
  • Python
  • C#
  • VB.NET
  • JavaScript
  • Ruby
  • Delphi / Object Pascal
  • Perl

I no, it’s sad. No C… But given that it includes C#, I’ll let them off.

Using JSON as a datastore in C#

Using JSON as a datastore in C#

Shapes
Image by Gerd Altmann from Pixabay

For some not too complex applications, JSON can be a very handy way to store data rather than say using a database. It also has the advantage of storing data of varying sizes. For instance Lists with varying numbers of items. I created a Saveable generic class below that you use as an ancestor class for that you wish to Save/Load an IList of whatever.

 

 

    public class SaveAble<T>
    {
        private string _error = "";
        string LastError()
        {
            return _error;
        }
        public IList<T>? Load(string filePath)
        {
            if (!File.Exists(filePath))
            {
                Log.Error("Missing file {filePath}");
                _error = $"Missing file {filePath}";
                return null;
            }

            var content = File.ReadAllText(filePath);
            if (string.IsNullOrEmpty(content))
            {
                Log.Error("{filePath} file is empty");
                _error=$"{filePath} file is empty";
                return null;
            }

            return JsonSerializer.Deserialize<IList<T>>(content, new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true
            })!;
        }

        public bool Save(string filename,IList<T> collection)
        {
            var options = new JsonSerializerOptions
            {
                WriteIndented = true,
                PropertyNameCaseInsensitive = true
            };
            try
            {
                var bytes = JsonSerializer.SerializeToUtf8Bytes(collection, options);
                File.WriteAllBytes(filename, bytes);
                return true;
            }catch (Exception ex)
            {
                _error = $"Exception:{ex.Message}";
                return false;
            }
        }

    }

Just define your class MyClasses from SaveAble<MyClass>

where MyClass is the class you have a List of. Then you can do

MyClasses myclasses;
myclasses.Save("filename",List<MyClass>) and

List<MyClass> list = myclasses.Load("filename");

It is fast. On my PC (now six years old), it can load a 99,000 line JSON file in well under a second.

Why C# for the server?

Why C# for the server?

https://commons.wikimedia.org/wiki/File:Csharp_Logo.png
From Wikimedia

There are plenty of other programming languages that would do.  Programming languages are just tools but C# comes with several advantages.

  1. I know it pretty well, having been using it since 2005.
  2. With .NET 6 (and 5), it’s easy to create applications that run on Linux. This lowers the cost for hosting. I’m setting the game on a low cost VPS.
  3. Also on Linux, ASP.NET works pretty well for both Websites and Web Apis.
  4. I like some of the recent changes in C#. And Visual Studio 2022 Community Edition is pretty good. For instance the JSON handling has got better and better.

Do you know what Hello World in C# looks like now? Here it is in its entirety.

Console.WriteLine("Hello, World!");

That’s a console application. One line! Follow the link for more details about the C# templates. Note, there’s no usings there either. That’s because applications now start with a default set in C# 10 and .NET 6 (you get both if you install VS 2022). And if you want a particular namespace that you’ve written to be available to all source code in a project, you can just add this:

global using xyz;

And it becomes available everywhere without needing any more usings.

 

A new beginning – C#

A new beginning – C#

Postage
Image by Please Don’t sell My Artwork AS IS from Pixabay

You may have noticed, I stopped posting here a while back because basically I ran out of ideas for C related games stuff plus I was doing other stuff that wasn’t relevant (Delphi, C#).

I will get back to finishing my 2nd eBook, but for now, I’m working on a web/mobile game that isn’t really C related. However I thought I’d cover development of it here. as (a) part of it is C# (so technically it’s C and (b) it’s a game.  The backend part is C#, the front end Flutter which is Dart. I’m also going back to my old game design roots as the game architecture is ‘Postal Game’.

What is ‘Postal Game’ architecture?

Well first a little potted history.

Back before the web existed (late 80s), people used to play games by post. They’d fill in a postcard with the orders, post it to the game provider who would enter the details in a computer, process the game then print the results out and post that back. I discovered this (in the UK) back in 1986 and created a postal game: Casus Belli. A 16 player version of Empire. It ran for a year or so and I even attended a postal games conference with a stall back at the start of 1987 in London. By chance, the stall next to mine was run by KJC Games and we got chatting. Kevin J Cropper (The KJC of KJC Games) said “If I ever wanted to sell the game contact me” and at the end of 1987 I did and found myself working for KJC Games as a game designer and programmer in Cleveleys (just North of Blackpool). It was a small cottage industry in the UK and KJC Games was the biggest fish in this admittedly small pond.

Over the next two and a half years I created the 100 player version of Casus called Warlord. Long after I left they ran games across the web and though they don’t run it any more you can still see the page for it. My big creation was a 1,000 player postal game called Quest which KJC still runs. Not bad for a game created in 1989! They still have my name in the Advanced rules which is nice as I last did some work on it in 1996. It took me a year and 40,000 lines of code (Turbo Pascal 5) to create. The others listed helped test it, made suggestions and Steven Fairbrother who came along after I left, fixed my bugs.  When you write 40,000 lines of code in a year, there are a few bugs included…

So each turn gets posted in, processed, printed and posted back. The architecture is the same except its all now sent across the web. There’s a front end programmed in Flutter. This makes it possible to use the same code for Web and mobile development. The game is processed at a fixed rate. In this case I’m going for every three hours but slower or faster is possible. When it’s time, all orders are processed and the results made available to be fetched from the web or mobile device.

Pros and Cons

A Game Processing Engine (GPE) is a completely different kettle of fish from your traditional multi player game server. Hardware requirements are much less and you don’t manage multiple players all at once. Basically the game web/mobile uploads a zip file from each player to send in the orders and then fetches one containing the results. The GPE maintains game state, processes all orders, outputs all results and backs up the game, both before processing each turn (in case it goes wrong so it can be fixed and rerun) and afterwards,

So I’ll be posting here about my progress, programming issues and so on. If you have any queries, please don’t add them as comments – I delete any non-technical comments so instead use the contact form via the About me link on the top.

 

 

I’m back and so is my PC

I’m back and so is my PC

H60 PC TemperatureI’m not the greatest with hardware, preferring to deal with software but sometimes you have to get your hands dirty, so here is the saga of my broken PC cooler and how I fixed it.

Three weeks ago my PC broke. I’d had it five and a half years and the cooler (it had a five years warranty! ) broke. It was a liquid cooler and following the advice of the supplier I bought a Corsair H60 cooler which was the same brand but slightly different cooler to mine. So I carefully photographed the orientation of the broken cooler and the connectors before removing it. I was determined to do things right so I bought earthing straps, to prevent static electricity from frying anything it shouldn’t.

So I took out the old cooler, removed the dregs of the thermal paste from the base plate (using Q-tips- works very well!)  and carefully put the new cooler in, and also swapped the fan which cools the radiator. It looks like a car radiator and has the same function. Two thick pipes run from the cooler which sits on top of the CPU and run to the radiator. It’s a closed system so you never see the cooling liquid.

I hooked up the fan connector – no problem. I hooked up the cooler connector and found a 15 pin connector there as well. That wasn’t in the old cooler!  It was a 15 pin SATA power connector. Following more advice from the supplier I bought a 15 pin SATA to Molex lead. Molex are those four pin power connectors that you plug into external hard disks. My PSU (a Corsair CS750M) came with a bunch of cables and one of them was a PSU SATA to Molex connector. One side of the PSU is full of connector sockets- apparently it can power up to 8 SATA devices. So that was the cooler wired up.

So I switched it on, it started booting and then wham- CPU fan error beep beep beep. Now the H60 cooler fan connector only had one wire going into it compared to the three wires on the older cooler. On that older cooler the power came through those wires but the H60 was powered by the SATA cable. So I wondered if maybe this connector belonged elsewhere and studied the motherboard diagram. The Motherboard was an ASUS X99-S.

It turned out that there were several connectors. I had been plugging into CPU FAN1 which was able to drive a fan with over 1 Amp of power. There was another connector CPU FAN which couldn’t supply that much power, so that’s why the old cooler was plugged into CPU FAN1 as that powered it. I plugged my cooler into CPU FAN and it worked. Time wise my PC was out of action for three weeks given delays from emails plus buying the cooler (£64) and the 15 pin-to Molex cable. (£7.00 for three).

I’ve had my PC running for the last half hour and it’s showing the temperature figures shown in the screenshot. It helped that the cooler could use the same plate and screws as the old cooler and came with thermal paste already applied. Until I did this, I hadn’t even realised that my PC was liquid cooled. I’m always nervous as hell when doing things with hardware but feeling quite chuffed that it worked.

The free temperature utility came from here and is very good.

 

 

Another maze generator and solver in C

Another maze generator and solver in C

Solved mazeI liked this one; it compiled perfectly without any changes and ran perfectly. It produces a maze of the specified size with a route. That’s not bad for a program written over 20 years ago. By developer Joe Wingbermuehle. You can view the source code here.

It runs in a terminal, just supply width and height characters like this. I compiled it into a file ex1.

./ex1 15 15 s

If you provide the s parameter, it will solve it as the screenshot shows using <> for the solved route. off for just the maze.

How to encrypt text using Xor

How to encrypt text using Xor

Binary
Image by Gerd Altmann from Pixabay

This is not meant to offer protection, but if you want to say hide text by disguising it, then using Xor for reversible encryption will do the trick. It relies on the principle that if you Xor A and B to get C then you can Xor C and A to get B or Xor C and B to get A.

I wrote a short program and tutorials to demonstrate taking a single bit of text then disguising it. To make it more challenging, I only used Xor values from the range 0-255 that had four or more bits with 1 in it, for example 15 which is 00001111 in binary.

You can find the tutorial How to do Xor encryption in C. Please note this is only a very light weight encryption method so don’t use it for anything too important!

How to extend C (99) with a library

How to extend C (99) with a library

toolkitI’m always looking to improve my C code and one way to do this is through others efforts. Today I came across Zpl, a cross-platform header-only library.

The zpl.h file is a whopping 17,495 lines long!  It has code for macro helpers,  memory, collections, string, hashtable, file, memory streamer, print, time, random, sorting and miscellaneous.

Given the length, it would be difficult to make sense but the authors (Vladyslav Hrytsenko and Dominik Madarász from the Ukraine and Slovakia respectively) have provided a folder of example applications that use the library.

It looks a very impressive library and well worth a look.