Hacker News new | ask | show | jobs
by andy_threos_io 824 days ago
With a better coding you don't need more than 8 bits for a move (less for some).

The implementation should store a state machine for the game, a struct for each pieces, and also the board with index to the pieces (occupation).

There is only 16 pieces for each player, the two players move one another.

The Naive would be that you index the pieces (4 bits) and store the movement after that,

Pawns 2 bits for movement (2 forward, 2 diagonal)

King 4 bits for movement (normal move 1 + 3 bits, castle 1 + 1 bits)

Knight 3 bits for movement (8 possible move)

Rook 4 bits for movement ( 1 bit orientation horizontal/vertical 3 bit new position )

Bishop 4 bits for movement ( 1 bit orientation left/right diagonal 3 bit new position)

Queen 5 bits for movement ( 2 bit orientation horizontal/vertical/ left/right diagonal 3 bits for new position)

This way you need

Pawn 4 (index) + 2 (movement) = 6 bits

King 4 (index) + 4 (movement) = 8 bits

Knight 4 (index) + 3 (movement) = 7 bits

Rook, Bishop 4 (index) + 4 (movement) = 8 bits

Queen 4 (index) + 5 (movement) = 9 bits

But you can encode the pieces index in another way, that the Queen got 3 bit index and other pieces got longer index (Pawn 5 bits)

index bits + movement 000 + 5 movement Queen -> 8 bits

00100 + 3 movement King Normal -> 8 bits

00101 + 1 movement King castle -> 6 bits

0011x + 3 movement Knight (2) -> 8 bits

01xxx + 2 movement Pawn (8) -> 7 bits

10x + 4 movement Bishop (2) -> 7 bits

11x + 4 movement Rook (2) -> 7 bits

Also other bit allocations are possible, I don't know if it's worth it to make the Pawns index 1 bit longer, but in this way the max 8 bits required for a movement. (You need the state machine for the "decompression", also have to track that the black and white Pawns are moving in the opposite direction. )

There can be further compression, if you check the possible move for the piece. ex. the first possible Knight movement is only 1 place, so no need to store the movement. But this need more calculation.