diff --git a/chess/board.go b/chess/board.go index dd29624..297a540 100644 --- a/chess/board.go +++ b/chess/board.go @@ -217,7 +217,85 @@ func (b *Board) movePawn(position string) error { } func (b *Board) moveRook(position string) error { - return nil + var ( + x int + y int + xPrev int + yPrev int + piece *Piece + err error + ) + + if x, y, err = getXY(position); err != nil { + return err + } + + xPrev = x + yPrev = y + for xPrev >= 0 && xPrev < 8 && yPrev >= 0 && yPrev < 8 { + xPrev++ + piece = b.getPiece(xPrev, yPrev) + if piece != nil { + if piece.Name == Rook && piece.Color == b.turn { + b.tiles[xPrev][yPrev] = nil + b.tiles[x][y] = piece + return nil + } else { + // direction blocked by other piece + break + } + } + } + + xPrev = x + yPrev = y + for xPrev >= 0 && xPrev < 8 && yPrev >= 0 && yPrev < 8 { + yPrev-- + piece = b.getPiece(xPrev, yPrev) + if piece != nil { + if piece.Name == Rook && piece.Color == b.turn { + b.tiles[xPrev][yPrev] = nil + b.tiles[x][y] = piece + return nil + } else { + break + } + } + } + + xPrev = x + yPrev = y + for xPrev >= 0 && xPrev < 8 && yPrev >= 0 && yPrev < 8 { + xPrev-- + piece = b.getPiece(xPrev, yPrev) + if piece != nil { + if piece.Name == Rook && piece.Color == b.turn { + b.tiles[xPrev][yPrev] = nil + b.tiles[x][y] = piece + return nil + } else { + break + } + } + } + + xPrev = x + yPrev = y + for xPrev >= 0 && xPrev < 8 && yPrev >= 0 && yPrev < 8 { + yPrev++ + piece = b.getPiece(xPrev, yPrev) + if piece != nil { + if piece.Name == Rook && piece.Color == b.turn { + b.tiles[xPrev][yPrev] = nil + b.tiles[x][y] = piece + return nil + } else { + break + } + } + } + + return fmt.Errorf("no rook found that can move to %s", position) } func (b *Board) moveBishop(position string) error { diff --git a/chess/board_test.go b/chess/board_test.go index 943314b..fc3701f 100644 --- a/chess/board_test.go +++ b/chess/board_test.go @@ -130,6 +130,27 @@ func TestBoardMoveBishop(t *testing.T) { assertNoPiece(t, b, "f8") } +func TestBoardMoveRook(t *testing.T) { + b := chess.NewBoard() + + b.Move("Ra3") + + assertMoveError(t, b, "Ra3", "no rook found that can move to a3") + + b.Move("a4") + b.Move("a5") + + b.Move("Ra3") + + assertPiece(t, b, "a3", chess.Rook, chess.Light) + assertNoPiece(t, b, "a1") + + b.Move("Ra6") + + assertPiece(t, b, "a6", chess.Rook, chess.Dark) + assertNoPiece(t, b, "a8") +} + func assertPiece(t *testing.T, b *chess.Board, position string, name chess.PieceName, color chess.Color) { p := b.At(position)