Originally posted on math.stackexchange.com
I am trying to verify whether moving a chess-piece is valid, where the moves are calculated in one dimension.
Instead of identifying the squares on a chess-board as {A1, B1, C1, ...} they are identified as {1, 2, 3, ...}, respectively.
Calculating valid moves is done by addition/subtraction, but it is not very reliable, as it may suggest some very erroneous moves.
I first looked at how the pawn behaves:
- It moves one square at a time (or two if in starting position) forward.
- It strikes diagonally, one square.
So a pawn's movement possibilities is simply it's current position, plus 8 (or 16), i.e.:
C2 = 11,
11 + 8 = 19 = C3
Now, striking should be equally easy; Just by adding/subtracting 7 or 9, but this is not entirely correct...
If a pawn is on H2, which is identified as 16, then striking at:
16 + 9 = 35 = A4,
is clearly an invalid move.
To avoid this, I checked (for white pawns) if the current position of the pawn, denoted P, is:
((P + 7) % 8 != 0) && (P % 8 != 0)
Now I am really having big troubles with figuring out how to verify the moves of the remaining pieces in general...
Is there an effective way to validate the moves of the remaining pieces?