ChessCom/Chess-Game — pull request #15 by BiviaBen (2013-12-21 04:26:02+00:00)
Title: Bpc/ivans king move fix

From PR #14 from Ivan, I dove a little deeper. Reposting [the comment from that PR](https://github.com/ChessCom/Chess-Game/pull/14#issuecomment-31051369):

The whole "king moving" conditional is messed up. As I read it, the original:
```php
if ($piece['piece'] == 'K') {
if((($to == ($this->_QRookColumn . (($this->_move == 'B')?'8':'1'))) && $this->{'_' . $this->_move . 'CastleQ'}) || (($to == ($this->_KRookColumn . (($this->_move == 'B')?'8':'1'))) && $this->{'_' . $this->_move . 'CastleK'}) || !in_array($to, $this->_getKingSquares($from))) {
// this is a castling attempt
if($this->objColumnToNumber[$from{0}] < $this->objColumnToNumber[$to{0}]) {
return 'O-O';
} else {
return 'O-O-O';
}
}
} else {
```
...reads like this:

1. If the piece is a king, do this block and skip the "possible moves" check in the `else` block below. (Herein lies our problem.)
2. Then, assume it's a castling move if:

- the king is being moved to the King's rook's column and has a Kingside castling move available *(note: incorrect; the king is moving to the king's knight's column)*; or
- the king is being moved to the Queen's rook's column and has a Queenside castling move available *(note: incorrect; the king is moving to the queen's bishop's column)*; or
- the king is being moved to any square not adjacent to it (which nullifies the need for the previous two checks! Lucky for us, or no one would have ever been able to castle.)

3. If we assume it is castling, then assign it a castling-move notation depending on whether it was moved left or right.
4. But if we aren't assuming castling and it is a move to an adjacent square, even if it is an illegal move, keep the original notation. (`_getKingSquares` only checks for squares, not whether it is legal!)

Ivan was able to fix the case for when the king makes a move to an adjacent square, it will check if the move is valid. However, any non-adjacent square triggers the castling assumption and can be incorrectly processed.

So, things this PR corrects:

1.Check possible moves first, for all pieces including the king.
2. Verify that the king is being moved to the proper square before assigning castling notation.
3. Verify that a castling move follows the requirements of castling.