Use early return in MovePawn

This commit is contained in:
ekzyis 2024-09-18 06:01:13 +02:00
parent a77fbcbd8b
commit 86f39d02f0

View File

@ -164,7 +164,7 @@ func (b *Board) movePawn(position string) error {
var ( var (
x int x int
y int y int
y_ int yPrev int
piece *Piece piece *Piece
err error err error
) )
@ -176,34 +176,37 @@ func (b *Board) movePawn(position string) error {
// TODO: implement diagonal pawn attacks // TODO: implement diagonal pawn attacks
if b.turn == Light { if b.turn == Light {
y_ = y + 1 yPrev = y + 1
} else { } else {
y_ = y - 1 yPrev = y - 1
} }
piece = b.tiles[x][y_] piece = b.tiles[x][yPrev]
if piece == nil { if piece != nil && piece.Name == Pawn && piece.Color == b.turn {
if b.turn == Light { b.tiles[x][yPrev] = nil
y_ = y + 2
} else {
y_ = y - 2
}
piece = b.tiles[x][y_]
}
if piece == nil {
return fmt.Errorf("no pawn found that can move to %s", position)
}
b.tiles[x][y_] = nil
b.tiles[x][y] = piece b.tiles[x][y] = piece
return nil
}
if b.turn == Light {
yPrev = y + 2
} else {
yPrev = y - 2
}
piece = b.tiles[x][yPrev]
if piece != nil && piece.Name == Pawn && piece.Color == b.turn {
b.tiles[x][yPrev] = nil
b.tiles[x][y] = piece
return nil
}
// TODO: assert move is valid: // TODO: assert move is valid:
// * 2 moves from start position // * 2 moves from start position
// * 1 move otherwise // * 1 move otherwise
// * diagonal if attacking // * diagonal if attacking
return nil return fmt.Errorf("no pawn found that can move to %s", position)
} }
func (b *Board) mustSetPiece(name PieceName, color Color, position string) { func (b *Board) mustSetPiece(name PieceName, color Color, position string) {