Category: tutorials

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!

New Tutorial on getting started with SDL

New Tutorial on getting started with SDL

SDL REctanglesI had this tutorial pencilled in to do and it’s now done. It’s the old SDL rectangles program that was part of the eBook. I’ve modernised it a bit so the same file will now compile under either MSVC on Windows or VS Code/Clang on Linux without changes.

I used the _WIN32 predefined macro so it compiles the call to Windows cod on Windows. Here’s an example:

#ifdef _WIN32
		sprintf_s(buff, sizeof(buff), "%10.6f", getElapsedTime(&s));
#else
		snprintf(buff, sizeof(buff),"%10.6f",diff(&s));
#endif

I do a similar thing with the path to SDL which is “SDL.h” on Windows but “SDL2/SDL.h” on Ubuntu. Writing code this way makes it  lot less of a hassle.

Added a tutorial on memory use in C

Added a tutorial on memory use in C

RAM BoardYou can read the tutorial here. It looks at the different ways memory is used in a C program. Do you know for instance what BSS is and when it is used compared to Data or where variables in a function declared static are held in memory?

I also tried overwriting a text literal out of curiosity to see what happens. Here’s the source:

#include<stdio.h>
#include <string.h>

char* name="My name is David";
int main()
{    
    strcpy_s(name,10, "New name");
    printf("Name = %s\n", name);
    return 0;
}

 
As you’d expect it blew up”

Slay Tutorial four published

Slay Tutorial four published

Debug ModeTutorial four of my reimagining of the game Slay continues.

This was an interesting bit of code to write, particularly setting the player hexagons. Then I tried to do too much in one go, adding the forts at the same time. I split this into separate functions.

It makes extensive use of recursion and that handy trick when you work with hexagons, the IsValidHex() function which tells you which six of the surrounding eight locations are valid. This is needed because the map is stored in a 2d array so in a 3×3 block, the centre location is surrounded by eight locations.

When you use hexagons, it’s more like a brick wall with each alternate row moved over a bit.  Now every location is surrounded by six adjacent locations just like in a hexagon grid. It turns out that a very simple function can tell you which of the 8 surrounding locations are valid.

In the grid I’m using, which runs in rows horizontally either 1,3 or 5,7 cells are invalid depending on whether the row is odd or even.

Here is a normal block of 3 x 3 locations.

7 0 1
6 x 2
5 4 3

But if I slide it over by 2 characters you get this.

  7 0 1     or     7 0 1
 6 x 2               6 x 2
  5 4            5 4 3

So by ignoring the bold locations, you can simulate a hexagon grid.

I’ve also added Debug mode which toggles with the tab key and introduced a blockId to each hex so you can see which hexes are lumped together. In Debug mode, the BlockId is printed out over the hex as in the screenshot. I’ve used the SDL_ttf library to draw the text. It slows down the screen update by a factor of 40x but is just fast enough to do 60 frames per second.

It’s interesting that the Ubuntu code running under Hyper-V is actually a lot faster than the Windows code.  As with previous tutorials, the code includes conditional compilation so it will compile and run under Windows or Linux.

Note, this code is not quite perfect. It now has three bugs:

  1. The map generator occasionally produces a map with a 2nd smaller continent separated by one hex from the main continent.
  2. Toggling Debug mode a lot makes it behave oddly. I thought I’d fixed that but I’m not so sure.
  3. Some blocks of contiguous hexes (all the same colour) lack forts.
Tutorial 14 on working with strings published

Tutorial 14 on working with strings published

Code listing on screen with keyboard
Image by Markus Spiske from Pixabay

Reading the C reddit most days, I see from time to time question about strings. They’re not particularly complex but I feel you really have to get your head around pointers to grok strings. I’ve already done a C tutorial on Pointers and c-strings but I thought showing some examples of doing things with c-strings would not go amiss.

The pointers aspect of C strings probably muddies the water a bit. All you are doing is manipulating a contiguous block of characters in RAM that ends with a 0. The pointer just tells you where in RAM that block begins. So long as it finishes with a 0 (\0 in C), it will work ok.

That’s what Tutorial 14- working with strings is about.  Especially for beginners, doing things like converting ints to strings, or concatenating strings can be a bit fiddly. I’ve also provided both the Windows and Linux versions. i.e. compiling with Visual C on Windows and clang on Ubuntu.

For instance, you might have heard about the long to ascii function ltoa. Bad news. It doesn’t exist in Linux compilers.  There is a Windows version with the instantly memorable (not) name _ltoa_s, which is one of the safe C functions.  Incidentally if you are using SDL then there is a SDL_ltoa function provided for you although oddly it’s not documented.

C Tutorial thirteen published on allocating memory

C Tutorial thirteen published on allocating memory

Memory chips
Image by PublicDomainPictures from Pixabay

I’ve restricted this tutorial to using malloc as it’s the main way you allocate and use dynamic memory in the thirteenth tutorial.

Pointers hold an address (of somewhere in RAM) and this can be an existing variable, a function or even data like a text string. But if you want to reserve a block of RAM and get a pointer to it, you have to call the stdlib function malloc(). (Or calloc, but I will return to that in a future tutorial).

Of course once you’ve finished using a block of RAM, it’s only polite to return it to the operating system by calling free(). Don’t forget either that malloc always returns a void * pointer, so you should cast it to something appropriate.

 

C Tutorial twelve on function pointers published

C Tutorial twelve on function pointers published

Lots of pointers
Image by pencil parker from Pixabay

While function pointers are important. I don’t think they’re quite as important as pointers. C would just not be C without pointers. There are so many things that you would not be able to do if the language lacked pointers. Things like most data structures (try doing a linked list without pointers!) .

However function pointers give additional flexibility. You can pass them as parameters in functions and store them in variables.

These are the earlier tutorials on pointers:

And this is the new one:

 

Thinking about Slay tutorial 7- Game AI

Thinking about Slay tutorial 7- Game AI

Slay gamesHaving just published Slay Tutorial three, making the Onslaught game play well as a computer opponent(well up to 8 of them)  has been weighing on my mind. I have played the original Slay perhaps a couple of thousand times, so I’m reasonably familiar with strategy.

There’s almost 500 games on the Slay game chooser screen shown with four different sizes of islands; the four boxes. Usually by the time I’ve played through all games here (probably taking 18 months to two years) , I can start again and have forgotten what it was like. Plus I think it randomises the starting positions so you get a lot of replay value.

In the first Slay Tutorial I published a map of the tutorials and so far am sticking to it. Tutorial seven is the one for the game AI and its on my mind. I play all the Slay games at the same top intelligence level and even it sometimes makes stupid mistakes like leaving an area vulnerable to splitting and losing all units due to starvation.

The main aim of any player is to expand their territory at the expense of other players. Joining territories can be one tactic as its lets you support the bigger units. The 2 point unit is a Peasant then there’s Spearmen (6 points) , Knights (18 point) and Baron (54 points).  Getting a Knight early on gives you a big advantage as it can defeat castles and too often I’ve seen a territory with one or two spearmen get trapped by castles and destroyed in a few turns.

Likewise putting a castle down early on can secure a territory for a while. Or if you have a larger area, a couple of castles can shield your flanks so you can focus yoyr troops against one enemy and not worry about other players moving in.

Self Playing

In Slay once you are eliminated the games plays through until one player beats everyone else. But self-playing can also be a useful way to have computer players learn. One possibility is to try and implement a “matchbox” AI. This was done with Tic-Tac-Toe (noughts and crosses for us Brits) with Menace, Now it may be that Onslaught is too complex to implement that but there’s a lot of RAM available, so if I can limit the number of setups that it recognises then maybe?

Anyway there’s a fair bit of time and Tutorials 4-6 to do before I get to Tutorial seven.

PS

If you move the mouse over the About Me, you’ll see a link to a page that has short cut links to all blog posts along with the title of each.  It’s a quicker way of navigating.

 

Slay tutorial three published

Slay tutorial three published

Onslaught mapThis is a typical map produced by the generator. One large continent with coloured hexagons from 8 players arranged in clumps and individual hexes. It’s not quite perfect- in the top right corner there is a single blue hex but its not bad.

I’ve just published Slay tutorial three with the source code in the file onslaught2.zip on GitHub. I’m quite pleased with the map generator which is based on the one I devised for Empire and which I covered in an earlier blog post.  It does a lot and quick enough that when you press the N key it can generate a new map in a fraction of a second.  C + SDL2 is very fast even when drawing nearly a thousand hexagons every frame. It’s mostly in just one file (for now) with timing code and a data file for generating maps in separate files. The main file is just over 600 lines long.

As it needed a fair bit of debugging, I made it cross-compile in Windows or Linux (and probably Mac OS but that’s not tested). You can load the solution file in Windows with Visual Studio or put the files into a Folder with Visual Studio Code on Linux. Included in the zip file is the assets folder which has all the individual hex graphics and a .vscode folder with JSO files for doing the build with clang on Linux.  I’ve compiled it and run on both Windows and Linux. The SDL2 Window is 1300 x 768 pixels wide.

Onslaught (aka Slay on Linux) tutorial two published

Onslaught (aka Slay on Linux) tutorial two published

Onslaught linux hexagons screenI’m quite pleased with this. It took about six hours in total to create including the time to create the graphics. Running in Hyper-V under Ubuntu 20.04, it draws a screenful of graphics in about 65 microseconds.

I took the hexagon drawing code from the AboutEmpire.zip code on GitHub and modernised it for SDL2. The Empire code uses Surfaces from SDL1 while this uses Textures from SDL2.

Orange hexagon Blue hexagon There are nine hexagons with all but the dark one having an internal border.

I think the orange and salmon hex look a bit too close, so I’ll change one of them.

The tutorial goes into a bit more depth. about the program (which is just over 200 lines long) and can be found on GitHub in the file Onslaught1.zip.