Implement bishop moves

This commit is contained in:
ekzyis 2024-09-18 06:44:59 +02:00
parent a8dd06590a
commit 8e881fc0b3
2 changed files with 104 additions and 1 deletions

View File

@ -221,7 +221,89 @@ func (b *Board) moveRook(position string) error {
}
func (b *Board) moveBishop(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++
yPrev--
piece = b.getPiece(xPrev, yPrev)
if piece != nil {
if piece.Name == Bishop && 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 {
xPrev++
yPrev++
piece = b.getPiece(xPrev, yPrev)
if piece != nil {
if piece.Name == Bishop && 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--
yPrev++
piece = b.getPiece(xPrev, yPrev)
if piece != nil {
if piece.Name == Bishop && 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--
yPrev--
piece = b.getPiece(xPrev, yPrev)
if piece != nil {
if piece.Name == Bishop && piece.Color == b.turn {
b.tiles[xPrev][yPrev] = nil
b.tiles[x][y] = piece
return nil
} else {
break
}
}
}
return fmt.Errorf("no bishop found that can move to %s", position)
}
func (b *Board) moveKnight(position string) error {

View File

@ -109,6 +109,27 @@ func TestBoardMoveKnight(t *testing.T) {
assertNoPiece(t, b, "g8")
}
func TestBoardMoveBishop(t *testing.T) {
b := chess.NewBoard()
b.Move("Bc4")
assertMoveError(t, b, "Bc4", "no bishop found that can move to c4")
b.Move("e3")
b.Move("e6")
b.Move("Bc4")
assertPiece(t, b, "c4", chess.Bishop, chess.Light)
assertNoPiece(t, b, "f1")
b.Move("Bc5")
assertPiece(t, b, "c5", chess.Bishop, chess.Dark)
assertNoPiece(t, b, "f8")
}
func assertPiece(t *testing.T, b *chess.Board, position string, name chess.PieceName, color chess.Color) {
p := b.At(position)