The rook is believed to have once been the “rukh”, which was some sort of tower shaped carriage that was placed on top of an elephant. Supposedly, the rukh was the actual fortification itself, and the elephant was the means of carrying it around. In the top of this tower shaped fort was an archer who would rain arrows upon his enemies, able to control long open distances because of his archery. Other variants included men with long spears, who would attack from above. Over time, according to legend, the pieces evolved, and somewhere in Europe, where there are no elephants, the elephant itself was discarded, and the rukh remained, albeit changed to resemble the castle like towers which were common in the middle ages.
Now one can see why they are often erroneously referred to as “castles”. Technically, to castle is a move in chess, involving the rook and the king.
In either event, I set about to add the rook moves to my chess engine. Remember, my logical board is an array of characters. 64 characters arranged in a straight line. Each character is given a numbered spot in the array, so moving a “R” or “r” for rook (white and black respectively), is a matter of simple algebraic math.
To advance “up” a row is: rook current space + 8 = rook’s new space. Down is a minus 8, and to move side to side is +1 or -1. However, there is a catch. If a rook was in space 8 (a2) and did a move to the left (which would be an illegal off the board move), the rook would mathematically end up in space 7, which is h1. This can’t be allowed.
So, what we use is some elementary level math: rook’s current space / 8 = the rook’s row. Since integers are always whole numbers, 57 / 8 = 7.125, which the integer, being whole, always rounds down, which gives us 7. The rook is in row 7. Likewise, if we want the column, we use this formula: rook’s current space % 8 = the rook’s column. This is looking for the remainder after the division, so in the case of 57 / 8 = 7 with a remainder of 1, the rook is in column 1. Very simple to implement and use.
The trick was making sure that we properly use that information. Creating a simple while loop solved that issue. You can see the first rook commit here. However, in all of my “smartness” I made a rook-ie mistake! My mistake was this: there are 8 rows, and 8 columns, but it is not numbered 1-8, it is numbered 0-7! This lead to move errors, as part of my code said if you were in greater than row 1 or less than row 8, etc., which would allow pieces to “fall off” the board (actually creating an array out of bounds exception), or move from one row far column to the opposite column on another row! This is not acceptable! Fortunately, the fix was easy, and you can see it in the second and third rook commits. Yes, it took me two tries to fix my own Fool’s Mate!
Linux – keep it simple.