From 6b4dea51457e712ffd60856d0351e2067007d74d Mon Sep 17 00:00:00 2001 From: Marco Date: Wed, 28 Jun 2023 08:26:11 +0200 Subject: [PATCH] Add king rules. --- chess/free_squares.go | 4 ++++ types/coordinate.go | 30 ++++++++++++++++++++++++++---- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/chess/free_squares.go b/chess/free_squares.go index 8e392c2..84516db 100644 --- a/chess/free_squares.go +++ b/chess/free_squares.go @@ -30,6 +30,10 @@ func (b *Board) GetNonBlockedDiagonals(fromSquare types.Coordinate) []types.Coor return nonBlocked } +func (b *Board) GetNonBlockedKingMoves(fromSquare types.Coordinate) []types.Coordinate { + return b.getNonBlockedConsecutive(fromSquare.GetAllKingMoves(), fromSquare) +} + func (b *Board) GetNonBlockedKnightMoves(fromSquare types.Coordinate) []types.Coordinate { allKnightMoves := fromSquare.GetAllKnightMoves() return b.getNonBlockedForKnights(allKnightMoves, fromSquare) diff --git a/types/coordinate.go b/types/coordinate.go index 345f75a..982413b 100644 --- a/types/coordinate.go +++ b/types/coordinate.go @@ -1,6 +1,8 @@ package types -import "github.com/samber/lo" +import ( + "github.com/samber/lo" +) // coordinates starting at 1:1 and end at 8:8 type Coordinate struct { @@ -58,6 +60,22 @@ func (b *CoordinateBuilder) Resolve() *Coordinate { return nil } +func (c *Coordinate) GetAllKingMoves() []Coordinate { + squares := make([]*Coordinate, 0, 8) + + squares = append(squares, c.Up(1)) + squares = append(squares, c.Down(1)) + squares = append(squares, c.Left(1)) + squares = append(squares, c.Right(1)) + + squares = append(squares, newCoordinateBuilder(*c).Up(1).Right(1).Resolve()) + squares = append(squares, newCoordinateBuilder(*c).Up(1).Left(1).Resolve()) + squares = append(squares, newCoordinateBuilder(*c).Down(1).Right(1).Resolve()) + squares = append(squares, newCoordinateBuilder(*c).Down(1).Left(1).Resolve()) + + return filterNilSquares(squares) +} + func (c *Coordinate) GetAllKnightMoves() []Coordinate { unfilteredMoves := make([]*Coordinate, 0, 8) @@ -70,9 +88,13 @@ func (c *Coordinate) GetAllKnightMoves() []Coordinate { unfilteredMoves = append(unfilteredMoves, newCoordinateBuilder(*c).Up(1).Left(2).Resolve()) unfilteredMoves = append(unfilteredMoves, newCoordinateBuilder(*c).Up(2).Left(1).Resolve()) - return lo.FilterMap(unfilteredMoves, func(unfilteredMove *Coordinate, _ int) (Coordinate, bool) { - if unfilteredMove != nil { - return *unfilteredMove, true + return filterNilSquares(unfilteredMoves) +} + +func filterNilSquares(squares []*Coordinate) []Coordinate { + return lo.FilterMap(squares, func(square *Coordinate, _ int) (Coordinate, bool) { + if square != nil { + return *square, true } return Coordinate{}, false })