# Thread: Legal moves in a chess game

1. ## Legal moves in a chess game

Hello everyone. I'm in the process of writing a chess game in the console. I have reached a problem when it comes to testing whether or not the entered move is legal. I was hope that someone could give me a few pointers (no pun intended) as to the easiest way to do it.

2. One of the simplest methods would be to create a two dimensional array where each element represent a board space. Have something like 0 represent an empty space and each piece it's own identifier. When a piece is told to move you know its position and its type which is all you need. For example a pawn can only move straight if it's not capturing, check if pawnPosition - rowLength - 1 is occupied and whether pawnPosition - rowLength + 1 is occupied (by an opponent's piece), if so the corresponding diagonal is a valid move, otherwise only pawnPosition - rowLength is valid.

If you wanted to optimize space you could also take a bitboard approach.

3. With the strict positional rules, do as Valis suggested. Each type of piece has different movement rules. These rules can be easily coded if you look at the board as having a cartesian coordinate system like the one provided by a two dimensional array.

Remember that 3 pieces have special moves:
Pawn en-passant, Pawn first move
Rook big castle, Rook small castle
King big castle, King small castle

Very few things will stop a piece from moving in chess. "Another piece of the same side occupying the destination space" is the only one for regular moves. So this is actually quiet easy to code. The two pawn special moves and the the two castle have well known rules, but easy to code too.

4. You should also keep in mind that the king should not be in check after the move.

5. There's an article on aihorizon.com that's somewhat relevant: http://aihorizon.com/essays/chessai/boardrep.htm

6. I made one before (AGES ago), and I programmed in all the allowable moves ....

I had a switch statement, and depending on whether the piece was a p, k, q, n, b, r it implemented a different function. I had four variables - the start x, start y, end x and end y, which were indices to the starting and ending positions of the piece. For the bishop, I first tested to see if there was anything in the diagonal and that the x deviation ==ed the y one ... just think about the moves, write them down, and see what you come up with. It's not all that hard, and gives you lots of experience with messing around with arrays!

EDIT - you can also recycle some of the functions. I think for the Queen's movement, I did something to do with an amalgamation of the Bishop's and the Rook's.

7. Thank you for the replies. If I have anymore problems, I will post again. I was using the 2D array idea to start with (and I have a couple of classes to store the coords of the pieces). Thanks again, much appreciated.