diff --git a/chess/board.go b/chess/board.go index 1e3930d..dd29624 100644 --- a/chess/board.go +++ b/chess/board.go @@ -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 { diff --git a/chess/board_test.go b/chess/board_test.go index fc4de6d..943314b 100644 --- a/chess/board_test.go +++ b/chess/board_test.go @@ -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)