Beispiel #1
0
        /// <summary>
        ///     Returns whether the piece has any possible legal captures.
        /// </summary>
        /// <param name="piece"></param>
        /// <returns></returns>
        private bool DoesPieceHaveLegalCapture(IPiece piece)
        {
            piece.GenerateCaptures(GameBoard.State, ActivePlayerBoardState);
            ICapture capture = ModelLocator.Capture;

            capture.StartingPosition = piece.Location;

            IBoardState captureSet = ModelLocator.BoardState;

            captureSet.Add(piece.CaptureSet);

            foreach (ChessPosition position in captureSet)
            {
                capture.EndingPosition = position;
                if (IsCaptureLegal(piece, capture, GameBoard.State))
                {
                    return(true);
                }
                if (piece is IPawn && IsCaptureLegalEnPassant(piece, capture, GameBoard))
                {
                    return(true);
                }
            }

            return(false);
        }
Beispiel #2
0
        /// <summary>
        ///     Can any friendly piece block the attacker?
        /// </summary>
        /// <param name="threateningPiece"></param>
        /// <returns></returns>
        private bool CanFriendlyPieceMoveBetweenKingAndAttacker(IPiece threateningPiece, IBoardState boardState)
        {
            switch (threateningPiece)
            {
            // all cases fall through
            case IKnight _:   // knights jump pieces, cannot move between
            case IPawn _:     // pawns attack in an adjacent square, cannot move between
            case IKing _:     // king will never be checking another king.
                return(false);
            }

            foreach (IPiece piece in ActivePlayerPieces.Where(p => !(p is IKing) && p.Location != ChessPosition.None))
            {
                piece.GenerateMoves(boardState);

                // use a copy of the MoveSet to prevent the collection from being modified in the following loop
                IBoardState copyOfMoveSet = ModelLocator.BoardState;
                copyOfMoveSet.Add(piece.MoveSet);

                foreach (ChessPosition location in copyOfMoveSet)
                {
                    var move = ModelLocator.CreateMove(piece.Location, location);

                    var isMoveLegal            = IsMoveLegal(piece, move, boardState);
                    var isKingInCheckAfterMove = DoesPotentialMoveLeaveKingInCheck(move);

                    if (isMoveLegal && !isKingInCheckAfterMove)
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
Beispiel #3
0
 public BoardState(IBoardState boardState)
 {
     Fen = boardState.Fen;
     OriginalPosition = boardState.OriginalPosition;
     NewPosition      = boardState.NewPosition;
     ETag             = boardState.ETag;
 }
        public IEnumerable <IReversiTurn> GetValidTurnsForBoard(IBoardState board)
        {
            var turnCandidates = board.GetEmptyEnemyNeighbours();

            var result = new List <IReversiTurn>();

            foreach (ICellCoordinates cell in turnCandidates)
            {
                var turn = this.TurnForCellOnBoard(cell, board);
                if (null == turn)
                {
                    continue;
                }

                result.Add(turn);
            }

            bool isNoValidTurnsLeft = (0 == result.Count);

            if (isNoValidTurnsLeft)
            {
                return(null);
            }

            return(result);
        }
        public GameCheckState Check(IBoardState <ChessPieceEntity> boardState)
        {
            var whiteState = _playerStateService.CurrentPlayerState(boardState, Colours.White);
            var blackState = _playerStateService.CurrentPlayerState(boardState, Colours.Black);

            if (whiteState == PlayerState.None && blackState == PlayerState.None)
            {
                return(GameCheckState.None);
            }

            if (whiteState != PlayerState.None && blackState != PlayerState.None)
            {
                Throw.InvalidGameState($"Invalid game states white/black {whiteState}/{blackState}");
            }

            if (blackState == PlayerState.None)
            {
                return(whiteState == PlayerState.Checkmate
                    ? GameCheckState.WhiteCheckmated
                    : GameCheckState.WhiteInCheck);
            }

            return(blackState == PlayerState.Checkmate
                ? GameCheckState.BlackCheckmated
                : GameCheckState.BlackInCheck);
        }
Beispiel #6
0
        /// <summary>
        ///     Creates a board with starting positions.
        /// </summary>
        public Board(IBoardState state)
        {
            State = state;

            State.Add(ChessPosition.WhiteStart);
            State.Add(ChessPosition.BlackStart);
        }
Beispiel #7
0
        public void PlayTurn(IBoardState boardState)
        {
LOGIC_START:
            foreach (Hex own in boardState.GetFieldsForPlayer(this._player))
            {
                if (own.Dices == 1)
                {
                    continue;
                }

                foreach ((Hex other, RelativeDirection direction) in boardState.GetNeighborsOfDifferentColor(this._player.Color, own))
                {
                    // 0.33 - 6.0
                    double diceRelation = ((double)own.Dices) / other.Dices;
                    if ((this._random.NextDouble() * 0.5 + diceRelation > 1.2d || own.Dices == 8) && boardState.CanAttack(own, other, out _))
                    {
                        bool won = boardState.PerformAttack(own, other).victory;
                        if (won)
                        {
                            // Restart the logic to also process the freshly conquered fields
                            goto LOGIC_START;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }
        }
        public void PlayTurn(IBoardState boardState)
        {
            Color lastAttackedBy = boardState.AttackHistory.LastOrDefault(x => x.defender.playerColor == this._player.Color).attacker.playerColor;

LOGIC_START:
            foreach (Hex own in boardState.GetFieldsForPlayer(this._player))
            {
                if (own.Dices == 1)
                {
                    continue;
                }

                foreach ((Hex other, RelativeDirection direction) in boardState.GetNeighborsOfColor(lastAttackedBy, own))
                {
                    if (own.Dices >= other.Dices && boardState.CanAttack(own, other, out _))
                    {
                        bool won = boardState.PerformAttack(own, other).victory;
                        if (won)
                        {
                            // Restart the logic to also process the freshly conquered fields
                            goto LOGIC_START;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }
        }
Beispiel #9
0
 public void ChangeState(BoardState state)
 {
     _currentState?.OnExitState();
     _currentState      = _states[(int)state];
     CurrentState.Value = state;
     _currentState.OnEnterState();
 }
Beispiel #10
0
 /// <summary>
 ///     Adds a capture to the capture set.
 /// </summary>
 /// <param name="capturePosition"></param>
 /// <param name="enemyBoardState"></param>
 protected void AddCaptureToCaptureSet(ChessPosition capturePosition, IBoardState enemyBoardState)
 {
     if (enemyBoardState.Contains(capturePosition))
     {
         CaptureSet.Add(capturePosition);
     }
 }
Beispiel #11
0
 public PlayerIIMoved(IBoardState boardState)
 {
     Fen = boardState.Fen;
     OriginalPosition = boardState.OriginalPosition;
     NewPosition      = boardState.NewPosition;
     ETag             = boardState.ETag;
 }
Beispiel #12
0
 public override void GenerateMoves(IBoardState boardState)
 {
     foreach (var move in TestMoves)
     {
         MoveSet.Add(move);
     }
 }
        private void RefreshPathsFeature(IBoardState <ChessPieceEntity> boardState, Colours currentPlayer)
        {
            if (FeatureFlags.CachingPaths)
            {
                // Need proper boardstate key I think, currently a few tests fail, I guess around some state related
                // so something not encoded in the textboard (enpassant  and castle viability namely)
                var stateKey = ChessGameConvert.SerialiseBoard(boardState);
                if (_stateCache.TryGetValue(stateKey, out var items))
                {
                    boardState.UpdatePaths(items);
                }
                else
                {
                    RefreshChessPaths(boardState, currentPlayer);

                    if (FeatureFlags.CachingPaths)
                    {
                        _stateCache.Add(stateKey, boardState.GetItems().ToArray());
                    }
                }
            }
            else
            {
                RefreshChessPaths(boardState, currentPlayer);
            }
        }
Beispiel #14
0
 public override void GenerateCaptures(IBoardState boardState, IBoardState owningPlayerBoardState)
 {
     foreach (var capture in TestCaptures)
     {
         CaptureSet.Add(capture);
     }
 }
Beispiel #15
0
        static async Task UserInputHandler(ISourceBlock <UserInputEvent> source)
        {
            // Read from the source buffer until the source buffer has no
            // available output data.
            while (await source.OutputAvailableAsync())
            {
                var input = source.Receive();
                if (input == UserInputEvent.ButtonPress)
                {
                    if (boardState == clock)
                    {
                        boardState = countdown;
                    }
                    else
                    {
                        boardState = clock;
                    }
                }

                if (input == UserInputEvent.RotateRight && boardState == countdown)
                {
                    countdown.Increase();
                }
                else if (input == UserInputEvent.RotateLeft && boardState == countdown)
                {
                    countdown.Decrease();
                }
            }
        }
Beispiel #16
0
        /// <summary>
        ///     Generates all legal <see cref="IPawn" /> moves
        /// </summary>
        /// <param name="boardState"></param>
        public override void GenerateMoves(IBoardState boardState)
        {
            IChessPieceMover cpm = ModelLocator.ChessPieceMover;

            MoveSet.Clear();
            ChessPosition oneSpaceFromLocation = Color == ChessColor.White ? cpm.North(Location) : cpm.South(Location);
            bool          oneSpaceMoveIsLegal  = !boardState.Contains(oneSpaceFromLocation);

            if (oneSpaceMoveIsLegal)
            {
                MoveSet.Add(oneSpaceFromLocation);
            }
            else
            {
                return;
            }

            ChessPosition twoSpaceFromLocation = Color == ChessColor.White
                ? cpm.North(oneSpaceFromLocation)
                : cpm.South(oneSpaceFromLocation);
            bool twoSpaceMoveIsLegal = !boardState.Contains(twoSpaceFromLocation);

            if (!HasMoved && twoSpaceMoveIsLegal)
            {
                MoveSet.Add(Color == ChessColor.White
                    ? cpm.North(cpm.North(Location))
                    : cpm.South(cpm.South(Location)));
            }
        }
Beispiel #17
0
        /// <summary>
        ///     Is a capture legal?
        /// </summary>
        /// <returns></returns>
        private bool IsCaptureLegal(IPiece piece, ICapture capture, IBoardState state)
        {
            piece.GenerateCaptures(state, ActivePlayerBoardState);
            bool canPieceCapture             = piece.CanCaptureAt(capture.EndingPosition);
            bool doesCaptureLeaveKingInCheck = DoesPotentialMoveLeaveKingInCheck(capture);

            return(canPieceCapture && !doesCaptureLeaveKingInCheck);
        }
        private Path ValidatePathForDiscoveredCheck(IBoardState <ChessPieceEntity> boardState, Path path)
        {
            var validPath = new Path(
                path.Where(move => !_checkDetectionService.DoesMoveLeaveUsInCheck(boardState, move))
                );

            return(!validPath.Any() ? null : validPath);
        }
Beispiel #19
0
        private ChessPosition GenerateCaptureWest(IBoardState enemyPieces, IChessPieceMover cpm)
        {
            ChessPosition potentialCapture =
                Color == ChessColor.White ? cpm.NorthWest(Location) : cpm.SouthWest(Location);
            bool isPieceAtCaptureLocation = enemyPieces.Contains(potentialCapture);

            return(isPieceAtCaptureLocation ? potentialCapture : ChessPosition.None);
        }
Beispiel #20
0
 public UpdatePieceAction(
     IBoardEntityFactory <TEntity> entityFactory,
     IBoardActionProvider <TEntity> actionProvider,
     IBoardState <TEntity> boardState
     ) : base(actionProvider, boardState)
 {
     _entityFactory = entityFactory;
 }
Beispiel #21
0
        private void GenerateEastMoves(IBoardState boardState, IChessPieceMover cpm)
        {
            ChessPosition nextMove = cpm.East(Location);

            if (!boardState.Contains(nextMove))
            {
                MoveSet.Add(nextMove);
            }
        }
        public IBoardAction Create(int moveType, IBoardState <TEntity> boardState)
        {
            if (Actions.ContainsKey(moveType))
            {
                return(Actions[moveType](boardState));
            }

            throw new NotImplementedException($"Action: {moveType} not implemented");
        }
Beispiel #23
0
        private void GenerateEastNorthEastMove(IBoardState boardState, IChessPieceMover cpm)
        {
            ChessPosition move = cpm.East(cpm.NorthEast(Location));

            if (!boardState.Contains(move))
            {
                MoveSet.Add(move);
            }
        }
Beispiel #24
0
        /// <summary>
        ///     Creates the state of the enemy board.
        /// </summary>
        /// <param name="boardState"></param>
        /// <param name="owningPlayerBoardState"></param>
        /// <returns></returns>
        protected IBoardState CreateEnemyBoardState(IBoardState boardState, IBoardState owningPlayerBoardState)
        {
            IBoardState state = ModelLocator.BoardState;

            state.Add(boardState);
            state.Remove(owningPlayerBoardState);

            return(state);
        }
Beispiel #25
0
        private void GenerateSouthSouthWestMove(IBoardState boardState, IChessPieceMover cpm)
        {
            ChessPosition move = cpm.South(cpm.SouthWest(Location));

            if (!boardState.Contains(move))
            {
                MoveSet.Add(move);
            }
        }
Beispiel #26
0
        public override void GenerateThreatened(IBoardState boardState, IBoardState owningPlayerBoardState)
        {
            IChessPieceMover cpm = ModelLocator.ChessPieceMover;

            ThreatenSet.Clear();

            ThreatenSet.Add(GenerateThreatenedEast(cpm));
            ThreatenSet.Add(GenerateThreatenedWest(cpm));
        }
Beispiel #27
0
        public Form1(IPlayerCreator playerCreator,IBoardState initialBoard)
        {
            this.initialBoard = initialBoard;
            squaresData = new Dictionary<int, SquareData>();
            this.playerCreator = playerCreator;

            InitializeComponent();
            depthCombo.SelectedIndex = 3;
        }
Beispiel #28
0
        /// <summary>
        ///     Is a move legal?
        /// </summary>
        /// <returns></returns>
        private bool IsMoveLegal(IPiece piece, IMove move, IBoardState state)
        {
            piece.GenerateMoves(state);

            bool canPieceMove             = piece.CanMoveTo(move.EndingPosition);
            bool doesMoveLeaveKingInCheck = DoesPotentialMoveLeaveKingInCheck(move);

            return(canPieceMove && !doesMoveLeaveKingInCheck);
        }
Beispiel #29
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="boardState"></param>
        /// <param name="move"></param>
        /// <param name="performCheckTest">
        /// This has a small performance impact when reverse engineering SAN from the board move
        /// (approx 20ms a game on my rig) which is why it's optional and defaults to off</param>
        /// <returns></returns>
        public StandardAlgebraicNotation BuildFrom(IBoardState <ChessPieceEntity> boardState, BoardMove move, bool performCheckTest = false)
        {
            var fromItem = boardState.GetItem(move.From);

            var piece    = fromItem.Item.Piece;
            int?fromFile = null;
            int?fromRank = null;
            var toFile   = move.To.X;
            var toRank   = move.To.Y;
            var moveType = boardState.IsEmpty(move.To) ? SanMoveTypes.Move : SanMoveTypes.Take;

            // Are they any other pieces,
            //      of same type as the from item
            //      that can also move to the same location
            var otherPieces = boardState.GetItems()
                              .Where(i => !i.Location.Equals(move.From))
                              .Where(i => i.Item.Is(fromItem.Item.Player, fromItem.Item.Piece))
                              .ThatCanMoveTo(move.To);

            // TODO: That I need this resharper disable is probably a smell
            // ReSharper disable PossibleMultipleEnumeration
            if (otherPieces.Any())
            {
                fromFile = move.From.X;
                var file = fromFile;
                otherPieces = otherPieces
                              .Where(i => i.Location.X == file);
            }
            if (otherPieces.Any())
            {
                fromRank    = move.From.Y;
                otherPieces = new List <LocatedItem <ChessPieceEntity> >();
            }

            if (otherPieces.Any())
            {
                Throw.InvalidSan($"Unable to disambiguate {move}");
            }
            // ReSharper restore PossibleMultipleEnumeration

            if (piece == ChessPieceName.Pawn && moveType == SanMoveTypes.Take)
            {
                fromFile = fromItem.Location.X;
            }

            ChessPieceName?promotionPiece = null;

            if (move.ExtraData is ChessPieceEntityFactory.ChessPieceEntityFactoryTypeExtraData data)
            {
                promotionPiece = data.PieceName;
            }

            var inCheck = performCheckTest && _checkDetectionService.DoesMoveCauseCheck(boardState, move);

            return(new StandardAlgebraicNotation(piece, fromFile, fromRank, toFile, toRank, moveType, promotionPiece, inCheck));
        }
Beispiel #30
0
        /// <summary>
        ///     Generates all squares that are threatened by this piece for the given boardstate.
        /// </summary>
        /// <param name="boardState">Full board state</param>
        /// <param name="owningPlayerBoardState">Used to ignore this other pieces of the same color.</param>
        public virtual void GenerateThreatened(IBoardState boardState, IBoardState owningPlayerBoardState)
        {
            ThreatenSet.Clear();

            GenerateMoves(boardState);
            GenerateCaptures(boardState, owningPlayerBoardState);

            ThreatenSet.Add(MoveSet);
            ThreatenSet.Add(CaptureSet);
        }
Beispiel #31
0
        public bool IsValidPositionForTurnOnBoard(
            ICellCoordinates turnPosition,
            IBoardState board)
        {
            var matchingTurns = this._validTurns.Where(t =>
            {
                return(t.Position.Equals(turnPosition));
            });

            return(0 != matchingTurns.Count());
        }
Beispiel #32
0
 /// <summary>
 /// Constructor which perform alphabeta algorithm and set soruce ,destinationn coordinate and return captures list if exists
 /// </summary>
 /// <param name="board"></param>
 /// <param name="player"></param>
 /// <param name="depth"></param>
 public Move(IBoardState board, Player player, int depth)
 {
     Rules rule = new Rules();
     board.Board = board.ConvertBoardStateToBoard(board);
     var alphaBeta = new Alphabeta();
     Board temp = new Board();
     var srcCoord = new Coordinate();
     var destCoord = new Coordinate();
     IList<Coordinate> tempCaptures = new List<Coordinate>();
     if (depth%2 != 0)
         depth++;
     alphaBeta.AlphaBeta(board.Board, depth, Int32.MinValue, Int32.MaxValue, player, true, ref srcCoord, ref destCoord, ref temp, ref tempCaptures);
     if ((rule.InBounds(board.Board, srcCoord.X, srcCoord.Y)) && (rule.InBounds(board.Board, destCoord.X, destCoord.Y)))
     {
         board.Board = temp.Copy();
         board.BoardCells = board.ConvertBoardToBoardState(board.Board);
         Board = board;
     }
     bool pcCaptured = tempCaptures.Count > 0;
     board.DrawGame = board.CheckDraw(board.Board, board.Board[destCoord.X, destCoord.Y], pcCaptured);
 }
Beispiel #33
0
 /// <summary>
 /// Return IMove with current boardstate
 /// </summary>
 /// <param name="boardState"></param>
 /// <param name="depth"></param>
 /// <returns></returns>
 public IMove GetBoardMove(IBoardState boardState,int depth)
 {
     IMove move = new Move(boardState, playerColor, depth);
     return move;
 }
Beispiel #34
0
        /// <summary>
        /// Convert BoardState to Board (Coordinate[])
        /// </summary>
        /// <param name="boardState"></param>
        /// <returns></returns>
        public Board ConvertBoardStateToBoard(IBoardState boardState)
        {
            for (int i = 0; i < Board.Rows; i++)
            {
                int j = i%2 == 0 ? 7 : 6;

                int k=32;
                for (int shift=0; j >=0; k--, j -= 2, shift++)
                {
                    k = (8-i)*4 - shift;
                    Board[k].Status = boardState.BoardCells[i, j];
                    Board[k].X = 8 - i;
                    Board[k].Y = j + 1;

                }
            }

            return Board;
        }
 public BoardCollectionState(ILinkFactory linkFactory, IBoardState boardState)
 {
     this.linkFactory = linkFactory;
     this.boardState = boardState;
 }
Beispiel #36
0
        private void playerVsPCToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.ChooseStartPlayer();

            Player pcPlayer = this.ChoosePCPlayer();
            Player userPlayer = (pcPlayer == Player.Black) ? Player.White : Player.Black;

            players = new Dictionary<Player, IPlayer>();
            players.Add(pcPlayer, playerCreator.CreatePcPlayer(pcPlayer));
            players.Add(userPlayer, new UserPlayer(userPlayer));

            currBoard = initialBoard;
            this.PaintBoard();

            // first player is the PC
            if (pcPlayer == player)
            {
                int depth;
                try
                {
                    depth = int.Parse(depthCombo.Text);
                }
                catch (Exception)
                {
                    depth = 4;
                }
                IMove pcMove = players[player].GetBoardMove(currBoard,depth);
                this.PlayMove(pcMove.Board,false);
            }
        }
Beispiel #37
0
 public IMove GetBoardMove(IBoardState boardState,int depth)
 {
     return null;
 }
Beispiel #38
0
        private void PlayMove(IBoardState newBoard,bool needToContinueEating)
        {
            currBoard = newBoard;

            GameState stateAfterMove = currBoard.GetGameState(player);
            this.PaintBoard();
            if (stateAfterMove == GameState.Won)
            {
                MessageBox.Show(player.ToString()+" "+Resources.Won);
                players = null;
                return;
            }
            if (stateAfterMove == GameState.Lost)
            {
                MessageBox.Show(player.ToString() + " " + Resources.Lost);
                players = null;
                return;
            }
            if (stateAfterMove == GameState.Draw)
            {
                MessageBox.Show(Resources.Draw);
                players = null;
                return;
            }

            // check if player needs to continue eating
            if (needToContinueEating)
            {
                return;
            }

            // switch players

            if (player == Player.White)
            {
                player = Player.Black;
            }
            else
            {
                player = Player.White;
            }
            playersTurn.BackColor = this.ConvertToColor();

            if (players[player] is UserPlayer)
            {
                return;
            }
            else
            {
                InteractivePause(new TimeSpan(0,0,0,0,1000));
            }

            int depth;
            try
            {
                depth = int.Parse(depthCombo.Text);
            }
            catch (Exception)
            {
                depth = 4;
            }
            IMove pcMove = players[player].GetBoardMove(currBoard,depth);
            this.PlayMove(pcMove.Board,false);
        }