Implement rook moves

This commit is contained in:
ekzyis 2024-09-18 06:49:58 +02:00
parent 8e881fc0b3
commit 2c6a7133e3
2 changed files with 100 additions and 1 deletions

View File

@ -217,7 +217,85 @@ func (b *Board) movePawn(position string) error {
}
func (b *Board) moveRook(position string) error {
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 {

View File

@ -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)