Month: July 2020

A test of resource loading in MonoGame

A test of resource loading in MonoGame

Ace of ClubsAce of DiamondsAce of HeartsAce of SpadesLoading resources into RAM on a smartphone can be a relatively slowish process. I’d been working on a card game and had both a set of 52 individual playing cards plus a sheet of 52 in one image. I have two Android phones so used the opportunity to test which is quicker loading 52 small images or one larger image. MonoGame ‘s Draw routines can copy from part of an image; you just specify the source.

In this case I was comparing loading 52 images, each 100 x 153 pixels (the four aces shown are the same images) or one image that is 1500 x 633. On the face of it, loading one image should be faster- there’s a certain overhead with loading each image so you get that x 52. But larger images can be problematic especially on devices like smartphones with less smaller amounts of RAM than desktops.

The two smartphones are both older, one is a BLU STUDIO ONE; the other a Chinese beast which shows up in Visual Studio as an Alps X27 Plus. It was bought on Ebay and claims to have 6 GB of RAm and 128 GB storage. In practice, when I tested the storage, it ran out after 12 GB! The phone only cost me £29 so I cn’t really complain…Although it claims to be Android 9.1 in the Developer information in Settings, it like the BLU seem to be running Android Lollipop. (5,1 – level 22) when plugged into my PC/Visual Studio.

I first ran the load code on the 52 images in Debug mode. Possibly not the best way to test code.

        private string LoadCards()

        {
            Stopwatch stopWatch = new Stopwatch();
            const string suits = "HCDS";
            const string ranks = "A23456789TJQK";
            stopWatch.Start();
            int i = 0;
            foreach (char c in suits)
            {
                int j = 0;
                foreach (char r in ranks)
                {
                    string s = @"Cards\"+r + c;
                    cards[i, j++] = Content.Load(s);
                }
                i++;
            }
            stopWatch.Stop();
            TimeSpan ts = stopWatch.Elapsed;

            string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                ts.Hours, ts.Minutes, ts.Seconds,
                ts.Milliseconds / 10);
            return elapsedTime;
        }

That is the C# code to load the 52 images. The Alps which is a newer phone took 0.28 seconds to load them. The older BLU took 0.18. Neither are great times. To load the single image I commented the code out between the two stopWatch calls (Start() and Stop()) and then added this one line.

 allcards = Content.Load<Texture2D>("allcards");

The single image took 0.10 seconds on the Alps and 0.06 seconds on the BLU, both roughly three times faster loading one big image than loading all 52 images.  Information like this is useful and I’ll now create my own tools for building sprite sheets of multiple images.

 

Space Invaders done faithfully in C

Space Invaders done faithfully in C

Si78 Space InvadersI was around when space invaders came out in the late 70s and played it a bit, although I preferred Galaxian, Gorf, Defender and Battle Zone (3D Tanks on the moon- vector graphics).

This project (catchily named si78) though is a memory accurate re-implementation of the 1978 arcade game Space Invaders in C.

To build and run this (on a Linux box) you’ll need to download the invaders ROM which is available in one of the Mame sets. The game is written in the subset of C99 that is compatible with C++, and uses no compiler extensions apart from attribute packed.

 

Improving on C strings

Improving on C strings

T
Image by Anja🤗#helpinghands #solidarity#stays healthy🙏 from Pixabay

Although C has many useful features, Text or string handling is not one of them. Unless you are writing text adventures, this is probably not a big deal and even games like Asteroids do write text messages, show the score etc.

Givn C’s age, it’s not surprising that people have tried to improve on C’s strings (char *) and one that I came across is the Better string library. The library is stand alone, portable and known to work with gcc/g++, MSVC++, Intel C++, WATCOM C/C++, Turbo C, Borland C++, IBM’s native CC compiler on Windows, Linux and Mac OS X. If you are bothered by buffer overflow type bugs, this is one area that BSL can definitely improve on. Note although the main documentation is just one text file, it is a very long file!

I haven’t tested it with clang but if it works with gcc the odds are it will work with clang.

I’ve added it to the C code links page.

 

Trials and tribulations of mobile development

Trials and tribulations of mobile development

Mobile apps
Image by Gerd Altmann from Pixabay

Compared to desktop, I find mobile development somewhat frustrating at times. On iOS, you have a right palaver with certificates and provisioning profiles before you can even run a program on your device. Android is nowhere near so bad, but you have the fragmentation problem I mentioned yesterday. Too many different models with different screen sizes and resolutions.

C# is a nice and powerful language and well suite dto mobile, though to be fair so are Swift on iOS and Java/Kotlin on Android. Android software is a bit of a mishmash. You have to get the right SDKs to match your phone’s OS. Then you have to create a simulator if you are not testing on a device. iOS has its own issues, generally involving needing a Mac before you can put code on the iPhone.

MonoGame is a nice framework. Compared to both Android and iOS native development (no JavaScript here!) it’s a lot more straightforward to work with. You override the Game.Update method for reading keyboards and touchscreens. Then you override Game.Draw to output graphics. In that respect it’s even easier than using SDL for games. It’s a little like WinForm programming.

Another extension to the scope of this blog

Another extension to the scope of this blog

MonoGame application running on AndroidWhen I started this blog at the end of February it was to assist sales of my ebooks. The one written and the one being written. Things have changed a bit and the one being written is now the Raspberry Pi book. That book is still being written but it’s not as high a priority now.

But I also have another side project underway which is to do with mobile game development (and maybe eventually Raspberry Pi).  The only thing is, this project uses C# not C or C++. However it is games related and as its my blog, I’ve decided that I shall write about it here as well as the C stuff. So get used to hearing about MonoGame, XNA and Xamarin.

Just so you know. Xamarin is the company (bought by Microsoft a few years back) that was formed by the founder of the Mono Project (Miguel de Icaza)  and is an excellent cross-platform technology for iOS and Android development based on C#.  I wrote two mobile apps (both sadly derailed by events) one of which was the equivalent of the Uber app. I managed to store every one of the 29 million UK postal addresses in the RAM of an iPhone 6.

XNA was a Microsoft technology for creating games on Xbox, Windows and Windows Phone some ten years ago. It reached version 4 but was then dropped by Microsoft. However the MonoGame project took it over and MonoGame is XNA reincarnated.  It’s cross-platform and runs at 60 fps.

The only technology that I believe can rival Xamarin is Google’s Flutter but it is still too new and doesn’t do games. The C# code runtime adds 3.5 MB to the overall executable but is very efficient and fast.

The image is an Android phone I have running an app. It doesn’t look much but that menu will display with the same height and width on any Android phone.  The problem with Android development (compared to iOS)  that there’s over 20,000 different size screens compared to a dozen or so on iOS. My program is scaled to a fixed virtual size and then tranforms that to the real size. MonoGame lets you do that.

A game development website recommendation

A game development website recommendation

Games
Image by Maria_Alberto from Pixabay

In my previous post I mentioned that I’d had to discover a lot of stuff for myself. Just before the Web came into being ie 1994-1995 I’d been working on a hexagon map based game.  I figured out how to draw hexagons, how to store a hexagon map (as a 2D grid), how to click on a map location and discover exactly which hexagon you clicked.

I still have source code that I wrote 30 years ago for the postal game Quest and likewise for the hexagon game which I called Onslaught. Both were written for a 16-bit Turbo Pascal and probably could with a bit of effort be transformed into 32-bit or 64-bit Delphi had I the time and desire, both of which I lack.  Given that Quest is still run, that’s probably not a good idea anyway! Plus I had only been writing Pascal code for a few years and my old code is far from being comprehensible!

Anyway, a lot of the wisdom and stuff that I taught myself can be found on the excellent Amit’s Game Programming Information website (particularly the hexagon stuff) and I highly recommend it if you have any desires to be a game programmer.

 

 

 

 

My different programming style from before

My different programming style from before

Software
Image by Gerd Altmann from Pixabay

Next year I will have been developing software as a job for 40 years. I graduated in mid 1981 and three months later started my first job in October 1981. To say that things have changed enormously would be an understatement. Back then there was no internet so information was limited to three sources: Books, magazines and what you learnt yourself.

Along the way I have used commercially a large number of programming languages: BASIC (8k Basic on Apple II and ACT Sirius- a precursor to the IBM PC), CBasic on Dec Rainbow, Z80 assembler for home computers (MSX, Zx Spectrum and Amstrad CPC 464), 6502 for CBM Vic-20 and CBM-64 (and also one project for the rarely heard of CBM-16) then Turbo Pascal on CP/M and MsDos machines, Turbo C++, Ada, Delphi (4,5,7,9 and XE7) , SQL, HTML, PHP, CSS,Java, C and C# (with Xamarin for mobile). As well as the ebook (C) I’m working on two side projects (C#and MonoGame).

Back in the day pre-internet when I wanted to do graphics, I had to figure them out myself. Things like Turbo Pascal came with thick manuals that you more or less learnt, To draw rectangles on the CBM-64 in hires mode. I figured out how to draw them and finished a game in 6 weeks. Recently I’ve been doing the same using MonoGame for mobile game development. I did a quick search of Google, found a library in SourceForge or GitHub, downloaded it and fitted it in. No big manuals to learn, just knowing how to find stuff on the web, make sure the licence allows its use and I can understand its source code enough to use it.

Intellisense also helps. No more knowing that such and such a function has three parameters, you just type in the name and it shows the parameters and their types. Is it more productive than before the web? I think so but there’s also more distractions.

Do I miss those days when things were a lot simpler? A little but I know I’d miss being able to find things with Google, on StackOverflow, even in Wikipedia etc.  Things can be a lot more complicated but I think I’m way more productive.

Using Excel for level design

Using Excel for level design

Excel level spreadsheet for AsteroidsIn the asteroids game and shortly in my MatchThree game, I’ll be creating a level data array of struct. This has a struct for each level containing a count of particular features for that level.

This is the struct and array for a level in asteroids.

struct level {
	int nums[4]; // how many of each size of asteroid
	int aliens; // how many aliens
	float factor; // from 1.0 to 1.5 - multiply asteroid speed by this
};

struct level levels[50];

This is the first 3 levels and level 50.

#include "levels.h"

struct level levels[50] = {
{ .factor = (float)1,.aliens = 1,.nums = { 0,0,3,3 } }, // Level 1
{ .factor = (float)1,.aliens = 0,.nums = { 0,1,3,3 } }, // Level 2
{ .factor = (float)1,.aliens = 0,.nums = { 0,1,3,3 } }, // Level 3
..
{ .factor = (float)1.5,.aliens = 3,.nums = { 4,4,5,5 } } // Level 50

I didn’t type any of this in. Instead, I created that spreadsheet above. It’s easy to work out difficulty levels in column H.  The formula that calculates this is ins this on row 5. If you don’t know Excel, the $ in the factors means that as you copy this into successive row, it keeps the $ row value constant.

=(B5*B$4)+(C5*C$4)+(D5*D$4)+(E5*E$4)+(F5*F$4)+(G5*G$4)   - Row 5

=(B6*B$4)+(C6*C$4)+(D6*D$4)+(E6*E$4)+(F6*F$4)+(G6*G$4) - Row 6

So you can see its multiplying the values in rows 5 6 etc by the values in row 4.  Having put that in place I could tinker with the values in rows 5,6 etc to make the difficulty level increase roughly at the same pace. The difficulty level for level 50 is 77.5.

This is what the Excel formula looks like to generate the C code, it’s in cell M5 in the spreadsheet and then copied and pasted down.

="{.factor =(float)"&G5&", .aliens="&F5&", .nums = {"&B5&","&C5&","&D5&","&E5&"}}, // Level "&A5

and this is what it looks like. C code that can be copied and pasted directly. It even includes the comment for the level number!

{.factor =(float)1, .aliens=0, .nums = {0,0,3,3}}, // Level 1

Creating a spreadsheet and C code from it this way saved a lot of typing but let me quantify the numerical difficulty which increases from 17.5 on level 1 to 77.5 on level 50. There’s no meaning to this value, it’s just a calculation.

A tictactoe (aka noughts and crosses) game in C

A tictactoe (aka noughts and crosses) game in C

TicTacToe aka Noughts and Crosses
Image by Kevin Phillips from Pixabay

I was asked to write this a few month’s back and it took me 2 or 3 evenings. It’s 312 lines long in just one file. Hopefully there are enough sensible function and variable names to make sense of it.

It runs in a terminal. It was compiled with Visual Studio but should not need many changes to compile with gcc/clang. (I hope!).

I made extensive use of pointers. For instance this function uses pointers in a for-loop.

int InDanger(char piece, int * x, int * y) {

    for (*y = 0; *y < 3; (*y)++) {
        if (CountRows(piece, y,0)==2) return 1;
    }

    for (*x = 0; *x < 3; (*x)++) {
        if (CountCols(piece, x,0) == 2) return 2;
    }
    *x = 0;
    if (CountDiagonal(piece, x,0) == 2) return 3;
    *x = 2;
    if (CountDiagonal(piece, x,0) == 2) return 4;

    return 0; // no danger
}

I’ve added this to the GitHub C games repository and updated the C games source page.

Useful reference to C operators

Useful reference to C operators

Reference
Image by ElasticComputeFarm from Pixabay

Ever wondered what all the operators that you can use = are. Like ^=. Or what about operator precedence? Does * come before ++? (Answer no, ++ is higher precedence than *).

Do you know how

a & b == 7

is parsed? It’s actually a & (b==7)

This Wikipedia page lists all the operators with precedence order and as it includes C++, it lets you see what you can and can’t do in C and C++.  It’s worth bookmarking whenever you need to look these things up.