Category: C

Tutorial on Atoms added

Tutorial on Atoms added

Atoms command lineThis is my alternative approach to learning C. Show code, explain what it does in depth rather than explaining the C language feature-by-feature. I’ve created a 90 line skeleton program for atoms. The full file is on GitHub, The file is called atoms.c.

All this does is setup the board and let you enter your move. I’ve tested it on Windows and it calls _getch() to read the keyboard so it’s fast to enter moves and you don’t have to press enter/return. It then validates the move and updates the board and draws it. No chain reactions yet or computer play but those will be in future tutorials.

In the screenshot you can see I added one atom to (3,3) and then (5,6).

The board uses three characters for each cell with atoms prefixed by P or C for player and computer.  Trying to have the computer play well will be an interesting bit of programming.

 

Raylib – a C library for videogames

Raylib – a C library for videogames

Raylib screenshotaMuch as I love SDL, I’m quite happy to look at alternatives and Raylib looks very good. It was inspired by Borland BGI graphics lib and by XNA framework (both of which I’ve used).

It’s written in C99 and is very cross-platform, even listing Raspberry Pi (I’m guessing they mean Raspberry Pi OS) as well as Windows, Mac, Linux, Android and HTML5. Basically any platform that supports C and OpenGL. There is a massive list of bindings for use in other programming languages.

Check out the examples page; you can try them online and each has a C source code listing so you can see how it’s done.

What I really like about RayLib is the scope of it and this is where I think it beats SDL. There’s 2D and 3D support, text support, in eight modules (core, shapes, textures, text, models, shaders, raudio and physac). It also comes with 8 free fonts but you can use your own custom fonts, pretty much the same way as I did in the Asteroids game.

I was very impressed with the text demo where a red box contains the text and if you resize it with the mouse the text is word wrapped.

The Spanish developer Ray (surname unknown) was cited today as the #1 trending C developer on GitHub and that’s a testament to the seven years that he has put into Raylib. His design philosophy with Raylib is to make programming fun and I am going to check it out.  If it looks as good as I think it is, I will be switching to it for future games work. One thing that particular intrigues me is the RayGui library– an immediate mode GUI library. There are various tools that have been designed with it. and it supports these GUI controls:

Label       |  Button      |  LabelButton |  ImageButton  |  Toggle      |  ToggleGroup |  CheckBox
ComboBox    |  DropdownBox |  TextBox     |  TextBoxMulti |  ValueBox    |  Spinner     |  Slider   
SliderBar   |  ProgressBar |  StatusBar   |  ScrollBar    |  ScrollPanel |  DummyRec    |  Grid

RayGui table

 

 

 

 

 

 

First new C Tutorial has been added

First new C Tutorial has been added

Atomes boardAs promised, I’ve added the first C Tutorial using the Atoms (aka Chain Reaction) game. However this is just a very easy intro to the Atoms game and doesn’t have a line of C code in it. We’ll save that for the next tutorial.

The planned tutorials for this are:

  1. Intro to the Atoms game.
  2. Drawing the Atoms board.
  3. Reading the keyboard and making a move.
  4. Handling explosions and checking if the game is over.
  5. Programming the computer player AI.
  6. Drawing a high-score table.

These will each include a C listing and an explanation of what the new C code does.

 

Thinking about future C tutorials

Thinking about future C tutorials

Molcules
Image by Anand Kumar from Pixabay

The tutorials I’ve done have followed a fairly “standard” model. Learn a feature, learn a new feature and so on. But what if this isn’t the best way to try and teach C?

I can’t remember how I learnt C. I’m not actually sure that I did which sounds weird but I learnt C++ nearly 28 years ago (I bought a book on C++ programming while on a weekend holiday in York). I learnt more C++ four years later when I was working on a football game. That project lasted six months and then the designer of the game decided to visit India and never came back and the whole thing fell though.

Fast forward to 2006 when I started writing the About C, C++ and C# column for about.com. Because I knew C++, I sort of knew C without explicitly having learnt it, Back then C++ was a superset of C. It still mostly is but there is the odd divergence.

This morning I was reading this thread on reddit. “What do you guys think its the best way to improve your coding?” and it got me thinking about the C tutorials. I know that I like to learn by working on small projects. Most games are too big for a tutorial (heck you can get a book out of them).

So I got to thinking, what is a simple game that would make for a good set of C tutorials? I even dug out the two books BASIC Computer games and More BASIC Computer games for inspiration. However in the end I decided on the game atoms. Here are the rules.

Rules for Atoms (aka Chain Reaction)

This takes place on an 8 x 8 board. Each turn you and then your opponent. Add 1 to any cell on the board. At the start all cells are empty with a value of 0. When you add 1 to a cell, it turns red or blue if the computer is playing. If a cell reaches 4 then it is cleared to 0 and all four cells around it (horizontal and vertical) have 1 added to them and become the player’s colour.  Cells in the corner only need to reach 2 to explode while cells at edges need 3.

When there are enough atoms on the board, a chain reaction can take place and you win if your atoms replace your opponents or lose in the opposite case.

To keep the tutorials simple this will be a console game. Each cell will be blank or show the number of atoms in the cell followed by a C (for computer) or P for Player instead of colours.  I’ll start the first tutorial tomorrow.

 

New tutorial on C loop statements published

New tutorial on C loop statements published

Mandala loops
Image by Renate Anna Becker from Pixabay

There are four types of loop statements in C, for loops, while loops, do-while loops and goto statements. The first two are much more popular; In my Windows asteroids game, I used 54 for-loops, six while-loops, three do-while loops and no gotos.

I found the same thing in Delphi and Turbo Pascal. The only difference is that Pascal uses repeat .. until instead of do-while and I prefer repeat-until.  The logic is slightly clearer I feel as well. You repeat the body of the loop until a condition becomes true. In the C do-while statement, you repeat the body of the loop as long as the condition is true.

Anyway I’ve published tutorial eleven on C loop statements. Have fun. I’ll get it added to the tutorials page shortly..

An amazing repository of articles on Chess programming

An amazing repository of articles on Chess programming

Chess pieces
Image by Steve Buissinne from Pixabay

When I went to University, I stayed in the halls of residence and there was a final year student there who was into chess programming- heady stuff for a first year student. It’s always held a bit of a fascination for me – I’ve been playing chess since the age of 11 though never particularly well. I’ve found most chess programs could beat me unless I take a great deal of care and spend a long time thinking.

The Chess Programming Wiki has almost 4,000 articles on all aspects of chess programming across 7500 pages. If you are interested in chess programming and unfamiliar with this then you are missing out.  This uses the mediawiki software (same as Wikipedia) so can be a little opaque. I’ve found if you click the Special pages link on the left then All pages that it gives a much wider overview.

A bit of searching found the programming languages page and disappointingly there is no entry for C although there is a page on C in the Wiki!  This links to CFish, a C port of the Stockfish open source chess engine which is mostly C++. If you can write a program to beat beat Stockfish then you are indeed an awesome programmer!

Of course, AlphaZero has recently dominated play in chess, Go and Shogi. What makes this different is that its mostly self taught using an AI technique called reinforcement learning. You just tell it the rules of chess. This contrasts with “traditional” chess programming where moves are determined ahead and evaluation routines called.

 

 

Pacman in C99 that runs in the browser

Pacman in C99 that runs in the browser

PacmanSuch a simple game yet still incredibly popular. Pacman is now 40 years old. I must confess, its not one that I was great at (that would be Battle Zone- the 3D wireframe tanks on the moon game- I could play that for an hour for just 10p),

This cross-platform implementation by German programmer Andre Weissflog (aka Flooh) looks spot on and plays it as well. Most of the game has been implemented in one C source file and its definitely worth reading the comments at the top of that file to see how things are done.

For instance “audio output works through an actual Namco WSG emulator which generates sound samples for 3 hardware voices from a 20-bit frequency counter,  4-bit volume and 3-bit wave type (for 8 wavetables made of 32 sample values each stored in a ROM dump)”.

The game uses the author’s Sokol libraries which are Simple STB-style cross-platform libraries for C and C++, written in C. It’s the first time I'[d come across these and they’re worthy of a separate look at. STB is a another library that I’ll also look at in the future. I’ve added a link to this Pacman to the C Code library. Happy Christmas!

PS. Also included in the GitHub download is The Pac-man dossier by Jamey Pittman, which is a 48 page PDF and tells you everything about playing Pacman. Stuff like the logic of gameplay, mechanics, easter eggs and the hardware specs of the original game boards not to mention the infamous level 255 overflow.

Interestingly the original hardware was a 3MHZ Z80A with 2 KB of RAM and 16KB of ROM on a 224 x 288 16 colour screen .

 

I added an if and switch tutorial

I added an if and switch tutorial

Teachjer and blackboard
Image by mohamed Hassan from Pixabay

The next tutorial is Simple control flow in C. This demonstrates how to do if, if else and then switch statements. These are pretty siomple concepts but they are fundamentals so you do need to know them.

One thing I didin’t show in the switch tutorial is that you can mix in labels for that real write-only code experience. It’s not a technique I recvommend which is why its NOT in the tutorial but if you promise never to use this except in the rarest of circumstances, here’s what I mean.

#include <stdio.h>

int main() {
	int a = 10;
	switch (a) {
	case 1:
	case 2:
	case 3:
	case 4:
	{
		printf("a<5\n");
		break;
	};
	case 5:
fred:
	case 6:
		printf("a ==5 or a ==6\n");
		break;
	case 7:
	case 8:
	case 9:
		printf("a <9\n");
	case 10:
	{
		printf("a=10\n");
		goto fred;
	}
	default:
		printf("a not in range 1-10\n");
		break;
	}
}

The label is the line fred: and you can see in case 10 that after printing “a=10\n”, it jumps to fred which is just after the 5 case. That does nothing and falls through to the 6 case where it prints out “a ==5 or a ==6\n”. It’s not recommended but at least now if you ever see a jump to a label in a switch statement you can be sure that the programmer was not really at the top of his or her game.

New tutorial on installing SDL on Linux

New tutorial on installing SDL on Linux

SDl Demo programWell you might say, “Don’t many Linux distros have SDL installed so people can play games?” and the answer is yes but not the development files and headers, and that’s what this shows you how to do along with a simple program to test that you can compile and run.

You’ll also need clang or gcc installed but as you can do that with a simple sudo apt install clang, it’s hardly worth a tutorial on its own.

However you also need to install VS Code and the C/C++ extension. Go to the VS Code website, download the Linux x64 version and double click on it to install it. After that from a terminal type code and it’ll appear. You then need to select extensions (5th icon down the left hand side) and pick the Microsoft C/C++ extension and install it.

I’ve added a new tutorial on the Tutorials page How to Install SDL on Linux. That includes a link to a demo file (its just above the screenshot) containing all three source code files and four VS Code configuration files for VS Code.

This program is almost identical to the asteroids_ch25 file (it draws lots of random size and colour rectangles on screen) but has been upgraded for Clang 10 and also what looks like a bug with search paths. There’s an extra line in Tasks.json to include the path to the SDL2 header files or you’ll get a can’t find a particular SDL header error when you compile.

Building code with VS Code is easy to understand once you “get” how the Folder works. I always keep the .vscode folder in there with the four C/C++ JSON configuration files and all source for that whatever it is you are compiling.  In the screenshot below (from WinSCP), you can see the path is /home/david/Projects/Examples and it contains the .vscode folder the three source files and demo which is the compiled code.  In VS Code I opened Examples as the Folder.

VS Code Folder

 

The .vscode folder is greyed out because the . means it’s normally hidden.

Coding a text adventure in C

Coding a text adventure in C

Text AdventuresText adventures have been around since the likes of Colossal Cave which I first played in 1980. They were quite popular on the early home computers like ZX 81 which were quite limited in RAM and capability. With the capacity of modern computers there are Interactive fiction (the modern name for adventure games) games with over a million words of text.

I suspect I’d probably want to code them in another language because C isn’t the best language when it comes to text. Nevertheless other have gone ahead and there’s an almost complete (20 out of 23 lessons) on how to program a text adventure in C on GitHub.

It’s a fine piece of work and some of the 20 articles like 20. Combat are quite long with lots of annotated code. At the bottom of each page you can download the source code on that page as a zip file or run the sources on repl.it. If you are learning C the line-by-line annotations really help explain why something was done.