Chess programing 1

It may come as a surprise to you, but I like chess. I am a member of my local chess club where I play occasionally. I am not very good at chess. I would call myself a beginner that knows all the rules. This will be the first in a series of posts (jinx) on chess. The main objective will be to implement a chess engine that I can not beat. Most of the information in these posts can be found in some way or another on

Before we do anything we have to define the game of chess. This is like explaining chess to someone who has never played. A computer is not a person, so in order to explain chess to it we need to map them to structures in the programming language of our choice (C). Each chess concept will be explained with its accompanying structure.

I think the best place to start is the chessboard. Chess is played on an 8 by 8 grid. The rows are called ranks and the columns files. The ranks are given the number 1-8 and the files the letters a-h. A cell of the grid is called a square. By convention we name a square by its file first and then its rank. For example: e4, e5, f4. The squares on the chessboard also have a color, either black or white. The black and white pattern of the board is called checkerboard pattern, after another much played game. Remember that the a1 square is black.

What is the best computer representation for the chessboard? A grid screams to be represented as an array. We then should link indices with square names, such as a1 is equal to the 0 element of the array. Indices and more generally numbers, have arithmetic operations defined on them. We can add, subtract, multiply, etc. This could come in handy later.

We should take a step back (or up) to mathematics. What a board really is, is a function (or a map) from the domain of squares to the range of pieces. More formally: \[ b : S \to P \] where \(b\) is the board function, \(S\) is the set of chessboard squares, and \(P\) is the set of chess pieces.

Since we are working in C, we have access to native, beafy 64-bit, unsigned integers. These bad boys will fit all of our squares exactly. However, we can only encode ones or zeros on each square. We will store multiple ‘bitboards’ and an array of pieces.

my way or the Conway

Another day, another implementation. Today I have implemented Conway’s game of life. It is a very simple model that can show very complicated results. It is also a lot of fun. What are the rule to this game? Well, I will tell you. First, let us start with the components of the system, we have

  • a 2-dimensional grid
  • a set of rules
    • alive and don’t have two or three alive neighbours -> dead
    • dead and three alive neighbours -> alive

Now we only have to define neighbours. In a 2D grid these are the 8 squares around a particular square. I have drawn a little ASCII graphic.

| O | O | O |
| O | X | O |
| O | O | O |

The O’s mark the neighbours and the X the particular square in question. Now all we have to do is implement it.

it’s complicated

I have been busy with complex numbers in JavaScript. I wanted to implement the Durand Kerner root finding algorithm. This algorithm requires complex arithmetic in order to work. So, in order to implement something, you need to implement something else. You just have to hope that you have arrived at the lowest level.

What is a complex number? It is a number of the type: \[ z = a + bi \] this is called rectangular form, and it is the form most people are familiar with. There is another form, called polar form, which looks like this: \[ z = re^{i\theta} \]

To translate from polar form to rectangular form we use Euler’s formula: \[ re^{i\theta} = r(\cos \theta + i \sin \theta). \] To translate from rectangular to polar coordinates, we use the special function \(\arctan\): \[ a + bi = \sqrt{a^2 + b^2}e^{i \arctan(b, a)}. \]

Why do we need these two forms? Well, some of the arithmetic operations make more sense in one form than in the other and, moreover, are easier to compute. To implement most of the functions we are familiar with we need to start with the three basic operators:

  • addition
  • multiplication
  • exponentiation

My implementation assumes the rectangular form as canonical. All operators are written for this form. For exponentiation we translate to polar, perform the operations, and translate back to rectangular.

Now for the mathematical definitions: \[ (a + bi) + (c + di) = (a + c) + (b + d)i \] \[ (a + bi) \cdot (c + di) = (a \cdot c – b \cdot d) + (a \cdot d + b \cdot c)i \] To define exponentiation we will first define the logarithm and the exponent. Notice how these operations are very similar to the translation operations defined before. \[ \log(a + bi) = \log(\sqrt{a^2 + b^2}e^{i \arctan(b, a)}) = \frac{1}{2}\log(a^2 + b^2) + \arctan(b, a)i \] \[ e^{a + bi} = e^a e^{bi} = e^a(\cos b + i\sin b) \] Now we can establish the general complex power: \[ (a + bi) ^{c + di} = e^{(c + di)\log(a + bi)} \] Which is defined in terms of our previous operations \(\cdot,\log,\exp\).

And that is most of it. To approximate trigonometric functions we use the identity (also found by using Euler’s formula): \[ \cos z = \frac{e^{iz} + e^{-iz}}{2} \] Calculating the inverse is left as an exercise to the reader. My code can be found here.


I wrote my own little brainfuck interpreter. You can read all about brainfuck on the esoteric programming website. They have a whole list of weird programming languages. So what is brainfuck? They tell you all about it on the Esolang website. But I’m gonna tell you anyway.

Brainfuck is a programming language designed to be as small as possible. This does not mean that programs written in brainfuck are neccesarily small. No, it means that the interpreter/compiler can be written in a small number of bytes.

There are only 8 commands in the language:

  • > move pointer right
  • < move pointer left
  • + increase value at pointer
  • - decrease value at pointer
  • . output character at pointer
  • , input character at pointer
  • [ jump past ] if value at pointer is 0
  • ] jump to [ if value at pointer is not 0.

This language is Turing complete, which means that any program may be written in it. This is not recommended however.

I implemented my interpreter in the C programming language, because of its native pointer support. Let’s look at the code:

void eval(char *s, char *p) {
  int i;

  for (; *s; s++)
         if (*s == '>') ++p;
    else if (*s == '<') --p;
    else if (*s == '+') ++*p;
    else if (*s == '-') --*p;
    else if (*s == '.') printf("%c", *p);
    else if (*s == ',') scanf("%c", p);
    else if (*s == '[' && !*p) {
      for (i = 1, s++; i; s++)
        i += (*s == '[') - (*s == ']');
    else if (*s == ']' && *p)
      for (i = 1, s--; i; s--)
        i += (*s == ']') - (*s == '[');

Doesn’t that look nice and neat? I was very pleased with myself. Until I found out that a lot of people have written brainfuck interpreters in brainfuck itself, that are shorter and of course more elegant. The *s pointer points to the program text. The *p pointer points to the actual data array.

The structure of the program should be familiar if you have ever written any semantic sucking code. We try to match one of the 8 commands and execute logic accordingly. The s-- at the end of the ] is there to ensure the string pointer does not go to far past the matching ].

To actually make this code do something, some additional I/O code needs to be written. Try making an interpreter for yourself and see what happens!

Double trouble

Following up on the post about Lorenz systems I have made a visualization of the double pendulum. Both of these systems are prime examples of systems studied in chaos theory. That is: systems that are highly sensitive to initial conditions.

Many of these systems can also be seen in nature. For example the weather. One of the problems is that numbers in nature are non computable. They simpy can not be estimated to within arbitrary precision by any program. This is kind of a scary thought.

Back to the system at hand. I used the wiki, the explanation there is probably better. But here is my take anyway. The double pendulum can be described by 7 variables:

  • gravity constant
  • length both rods
  • mass both rods
  • angle first rod
  • angle second rod
  • momentum first rod
  • momentum second rod.

The total energy (Langrangian) in the system consists of:

  • linear kinetic energy \(E_k = \frac{1}{2} m v^2\)
  • rotational kinetic energy \(E_r = \frac{1}{2} I \omega^2\)
  • potential energy \(E_p = mgh\)

We use some other identities to fill in these formula’s:

  • moment of inertia thin rod \(I = \frac{1}{12} m l^2\)
  • x-center of mass rod \(x = \frac{l}{2} \sin \theta\)
  • y-center of mass rod \(y = \frac{l}{2} \cos \theta\)
  • 2d velocity \(v = \dot{x} + \dot{y}\)

We throw all this together to get our pendulum applet. Have a happy new year!

Lorenz system

I have been doing some stuff with differential equations. They provide some unexpected results and show random behavior. I made a little visualization with the html canvas of a Lorenz (not Lorentz) system

  c = document.getElementsByTagName("canvas")[0];
  (ctx = c.getContext("2d")), (c.width = 500), (c.height = 500);
  (x = y = z = 1), (a = 10), (b = 28), (c = 8 / 3), (dt = 0.005);
  setInterval(() => {
      [x, y, z] = [
	  x + a * (y - x) * dt,
	  y + (x * (b - z) - y) * dt,
	  z + (x * y - c * z) * dt
      ctx.fillRect(200 + 5 * x, 200 + 5 * y, 1, 1);

You can see it live here:

My mandelbrot

I have tried implementing a zoomable mandelbrot set for a while. Today I created a satisfactory implementation. There is no native support for complex numbers in JavaScript, so we keep both real and imaginary parts of the complex number separate. The mandelbrot recurrence relation is:

z_{n+1} = z_{n} + c

The value of z_ 0 is c. We iterate over these values. The mandelbrot set is the set of all complex numbers for which this recurrence relation converges. We will write a function for this relation and then we are basically done. The rest of the code will simply draw the set and handle zoom events.

function f(a0, b0) {
      [a, b] = [a0, b0]
      for (i = 0; i < N && a*a+b*b<4; i++)
	  [a, b] = [a*a - b*b + a0, 2*a*b + b0]
      return i === N

This is our function. The implementation can be seen live at Use the spacebar to zoom and the arrow keys to move.

Random number cycles

Random number generation is often done by applying a function recursively to a seed number. The function needs to be bounded to a certain domain. Obtaining a function that is bounded is easily done by applying the modulo operation on the base function. The function must be deterministic. For example the following function

Continue reading “Random number cycles”

Fibonacci for beginners

The Fibonacci sequence is one of the most famous sequences. It appears everywhere in nature and mathematics. It is defined as:

\[ F(1) = 1 \] \[ F(2) = 1 \] \[ F(n) = F(n – 1) + F(n – 2) \]

We don’t want to calculate all these numbers by hand. For n = 100 the number has more than twenty digits. Addition is easy for humans and even easier for computers. Let’s write it with some Python, because everybody loves Python: Continue reading “Fibonacci for beginners”