public int Evaluate(Board.Board board, int evaluatingPlayer)
        {
            int score = 0;
            int winningPositionFor = board.CheckTerminalPosition();
            int signum             = evaluatingPlayer == 0 ? 1 : -1;

            if (winningPositionFor == 0)
            {
                score += 1000;
            }
            if (winningPositionFor == 1)
            {
                score -= 1000;
            }
            score = score * signum;

            score = score +
                    CountGoldCaptures(board) * GOLD_CAPTURES_WEIGHT * signum +
                    CountSilverCaptures(board) * SILVER_CAPTURES_WEIGHT * signum +
                    CalculateSouthBias(board) * SOUTH_BIAS_WEIGHT / board.width * signum +
                    CalculateFlagshipLiberties(board) * FLAGSHIP_LIBERTY_WEIGHT * signum;


            return(score);
        }
Esempio n. 2
0
        private void GetAvailableMovesInInterval(Board.Board board, List <KeyValuePair <int, int> > availableMoves, int rowInterval, int colInterval)
        {
            int row = this.CurrentLocation_x;
            int col = this.CurrentLocation_y;

            for (int i = 0; i <= 7; i++)
            {
                row += rowInterval;
                col += colInterval;
                if (board.IsInRange(row, col))
                {
                    var piece = board.Instance[row, col];
                    if (piece == null)
                    {
                        availableMoves.Add(new KeyValuePair <int, int>(row, col));
                    }
                    else
                    {
                        if (piece.Color != this.Color)
                        {
                            availableMoves.Add(new KeyValuePair <int, int>(row, col));
                        }
                        break;
                    }
                }
                else
                {
                    break;
                }
            }
        }
Esempio n. 3
0
        public static void AddQuietMove(Board.Board board, int move, MoveList list)
        {
            Debug.Assert(Validators.SqOnBoard(MoveOperations.FromSq(move)));
            Debug.Assert(Validators.SqOnBoard(MoveOperations.ToSq(move)));


            list.Moves[list.Count].Move = move;

            /* Captures generate 1.000.000 or higher score, therefore we have to
             * score the move just below this, to ensure this is second highest priority for search
             * after capture moves.
             */
            if (board.SearchKillers[0, board.Ply] == move)
            {
                list.Moves[list.Count].Score = 900000;
            }
            else if (board.SearchKillers[1, board.Ply] == move)
            {
                list.Moves[list.Count].Score = 800000;
            }
            else
            {
                int from = MoveOperations.FromSq(move);
                int to   = MoveOperations.ToSq(move);
                list.Moves[list.Count].Score = board.SearchHistory[board[from], to];
            }

            list.Count++;
        }
Esempio n. 4
0
 protected override void Awake()
 {
     base.Awake();
     m_enemyMover  = GetComponent <EnemyMover>();
     m_enemySensor = GetComponent <EnemySensor>();
     m_board       = FindObjectOfType <Board.Board>();
 }
Esempio n. 5
0
        private (bool Castled, string Error) CastleQueenSide(Board.Board board)
        {
            KeyValuePair <int, int> rookPos, rookMove, kingMove;

            if (this.Color == PieceColorEnum.Black)
            {
                rookPos  = board.ConvertNotationForMove("a8");
                rookMove = board.ConvertNotationForMove("d8");
                kingMove = board.ConvertNotationForMove("c8");
            }
            else
            {
                rookPos  = board.ConvertNotationForMove("a1");
                rookMove = board.ConvertNotationForMove("d1");
                kingMove = board.ConvertNotationForMove("c1");
            }

            // can't castle if it puts in check. run a simulation
            King kingCopy = (King)board.DeepClone(this);

            Board.Board simBoard = (Board.Board)board.DeepClone(board);
            simBoard.MovePiece(kingCopy, kingMove.Key, kingMove.Value);
            if (!kingCopy.IsInCheck(simBoard))
            {
                return(false, "castling results in a check");
            }

            // castle
            Rook rook = (Rook)board.Instance[rookPos.Key, rookPos.Value];

            board.MovePiece(rook, rookMove.Key, rookMove.Value);
            board.MovePiece(this, kingMove.Key, kingMove.Value);

            return(true, string.Empty);
        }
        private long GetMovability(List <Move> move, IReadOnlyList <LogicalPiece> state, int depth)
        {
            if (depth == 0)
            {
                return(0);            // what even is tail-call optimisation. Thanks c#
            }
            Board.Board unrealBoard = new Board.Board(state);
            Board.Board board       = unrealBoard.With(move); // advance one step into the future to see what it has in stock for us

            PlayerColor ownColor      = move.First().Played.Color;
            PlayerColor opposingColor = ownColor.Opposing();

            List <Move> opponentMoves = CalculatePotentialMoves(board.LogicalState)
                                        .Where(selected =>
                                               selected.Played.Color.Equals(opposingColor)
                                               )
                                        .ToList();
            List <Move> predictedOpponentMove = GetHighestRewardMove(opponentMoves, board.LogicalState, depth - 1);

            Board.Board predictedNextState = board.With(predictedOpponentMove);

            var next = CalculatePotentialMoves(predictedNextState.LogicalState);

            return(MovabilityFor(next, ownColor) - MovabilityFor(next, opposingColor) * (depth / 10));
        }
Esempio n. 7
0
        public void PlaceShip_BoardContainsShip_CorrectlyPlacesShip()
        {
            // Arrange
            var shipToPlace = new Destroyer();

            var existingShipPlacement = new List <Point>
            {
                new Point {
                    X = 5, Y = 5
                },
                new Point {
                    X = 5, Y = 4
                },
                new Point {
                    X = 5, Y = 3
                },
                new Point {
                    X = 5, Y = 2
                }
            };

            var existingBoard = new Board.Board();

            existingBoard.Tiles.Where(t => existingShipPlacement.Contains(t.Coordinates)).ToList().ForEach(t => t.IsOccupied = true);

            // Act
            ShipPlacer.PlaceShip(existingBoard, shipToPlace);

            // Assert
            shipToPlace.Position.Should().NotContain(existingShipPlacement, "ship should be placed without colliding with ship on board");
        }
Esempio n. 8
0
        static void Main(string[] args)
        {
            Server.Server server        = new Server.Server(auto: false);
            Thread        packet_thread = new Thread(new ThreadStart(server.Run));

            packet_thread.Start();

            Board.Board board             = new Board.Board(server, "00:01:CA:AA:00:01", full_initialize: true);
            Thread      ping_thread       = new Thread(new ThreadStart(board.Ping));
            Thread      light_show_thread = new Thread(new ThreadStart(board.LightShow));

            // ping_thread.Start();
            // light_show_thread.Start();

            for (int i = 0; i < 5; i++)
            {
                board.TestFunction("sine");
                board.Delay(5000);
                board.TestFunction("step");
                board.Delay(5000);
            }
            board.TestFunction("abstract");
            board.Delay(5000);
            board.TestFunction("differentiate");
        }
Esempio n. 9
0
        public List <KeyValuePair <int, int> > AvailableMoves(Board.Board board)
        {
            List <KeyValuePair <int, int> > availableMoves = new List <KeyValuePair <int, int> >();

            GetAvailableMove(board, availableMoves, -1, -1);
            GetAvailableMove(board, availableMoves, -1, 1);
            GetAvailableMove(board, availableMoves, -1, 0);
            GetAvailableMove(board, availableMoves, 0, -1);
            GetAvailableMove(board, availableMoves, 0, 1);
            GetAvailableMove(board, availableMoves, 1, -1);
            GetAvailableMove(board, availableMoves, 1, 0);
            GetAvailableMove(board, availableMoves, 1, 1);

            // can't move anywhere the opposite king can also move
            // don't do this for the current color or else it gets stuck in recursion
            List <KeyValuePair <int, int> > otherKingMoves = new List <KeyValuePair <int, int> >();

            if (board.ColorToMove != this.Color)
            {
                if (this.Color == PieceColorEnum.Black)
                {
                    otherKingMoves = board.WhiteKing.AvailableMoves(board);
                }
                else
                {
                    otherKingMoves = board.BlackKing.AvailableMoves(board);
                }
            }

            return(availableMoves.Where(e => !otherKingMoves.Contains(e)).ToList());
        }
Esempio n. 10
0
        public List <KeyValuePair <int, int> > AvailableMoves(Board.Board board)
        {
            List <KeyValuePair <int, int> > availableMoves = new List <KeyValuePair <int, int> >();

            int colorEnumMultiplier = (this.Color == PieceColorEnum.White && !board.IsFlipped) || (this.Color == PieceColorEnum.Black && board.IsFlipped) ? -1 : 1;

            // check space row +/- 1
            if (board.Instance[this.CurrentLocation_x + colorEnumMultiplier, this.CurrentLocation_y] == null)
            {
                availableMoves.Add(new KeyValuePair <int, int>(this.CurrentLocation_x + colorEnumMultiplier, this.CurrentLocation_y));
            }

            // on home row, row +/- 2 available move. extra logic is because of the
            if (!this.HasMoved && this.CurrentLocation_x + (2 * colorEnumMultiplier) >= 0 && this.CurrentLocation_x + (2 * colorEnumMultiplier) <= 7)
            {
                if (board.Instance[this.CurrentLocation_x + (2 * colorEnumMultiplier), this.CurrentLocation_y] == null)
                {
                    availableMoves.Add(new KeyValuePair <int, int>(this.CurrentLocation_x + (2 * colorEnumMultiplier), this.CurrentLocation_y));
                }
            }

            // potential captures
            GetAvailableMove(board, availableMoves, colorEnumMultiplier, 1);
            GetAvailableMove(board, availableMoves, colorEnumMultiplier, -1);

            return(availableMoves);
        }
Esempio n. 11
0
        // Capture move
        private static void AddWhitePawnCapMove(Board.Board board, int from, int to, int capt,
                                                MoveList list)
        {
            Debug.Assert(Validators.PieceValidEmpty(capt), String.Format("Invalid capture square {0}", capt));
            Debug.Assert(Validators.SqOnBoard(from), String.Format("Invalid from square {0}", from));
            Debug.Assert(Validators.SqOnBoard(to), String.Format("Invalid to square {0}", to));

            // If White pawn promotion.
            if (Conversion.getRanksBrd(from) == (int)Rank.RANK_7)
            {
                MoveGen.AddCaptureMove(board,
                                       MoveOperations.CreateMove(from, to, capt, (int)Piece.wQ, 0),
                                       list);
                MoveGen.AddCaptureMove(board,
                                       MoveOperations.CreateMove(from, to, capt, (int)Piece.wR, 0),
                                       list);
                MoveGen.AddCaptureMove(board,
                                       MoveOperations.CreateMove(from, to, capt, (int)Piece.wB, 0),
                                       list);
                MoveGen.AddCaptureMove(board,
                                       MoveOperations.CreateMove(from, to, capt, (int)Piece.wN, 0),
                                       list);
            }
            else
            {
                MoveGen.AddCaptureMove(board,
                                       MoveOperations.CreateMove(from, to, capt, (int)Piece.EMPTY, 0), list);
            }
        }
Esempio n. 12
0
        public (int, int) GetNextMove(Board.Board board)
        {
            DateTime startTime            = DateTime.Now;
            LinkedList <(int, int)> moves = board.GetLegalMoves();

            (int, int)selectedMove = (-1, -1);
            int score = int.MinValue / 2;
            int value = score;
            int alpha = int.MinValue;
            int beta  = int.MaxValue;

            // treat no valid move options
            if (moves.Count == 0)
            {
            }

            foreach ((int, int)move in moves)
            {
                board.Move(move);

                if (board.remainingActions <= 1)
                {
                    value = AB(ref board, Math.Max(alpha, score), beta, depth - 1);
                }
                else
                {
                    value = -AB(ref board, -1 * beta, -1 * Math.Max(alpha, score), depth - 1);
                }

                if (value > score)
                {
                    score        = value;
                    selectedMove = move;
                }

                board.Undo();

                if (score > beta)
                {
                    break;
                }
            }

            DateTime endTime   = DateTime.Now;
            var      timeDelta = endTime - startTime;

            timer = timer - (int)timeDelta.TotalSeconds;
            Console.WriteLine($"{timer} seconds remaining");
            if (timer < 180)
            {
                depth = 3;
            }
            else if (timer < 45)
            {
                depth = 2;
            }

            return(selectedMove);
        }
Esempio n. 13
0
 /// <summary>
 /// Gets value indicating whether the move is valid or not
 /// </summary>
 /// <param name="piece">Piece instance</param>
 /// <param name="cell">Cell instance</param>
 /// <param name="board">Game board</param>
 /// <returns>Value indicating whether the move is valid or not</returns>
 public static bool IsMoveValid(Piece piece, Cell cell, Board.Board board)
 {
     if (PieceCanMove(piece, board).Contains(cell) || PieceCanCapture(piece, board).Contains(cell))
     {
         return(true);
     }
     return(false);
 }
Esempio n. 14
0
        /// <summary>
        /// Constructor used when landing the rover.
        /// </summary>
        /// <param name="x">The x coordinate of the landing site.</param>
        /// <param name="y">The y coordinate of the landing site.</param>
        /// <param name="orientation">The rovers starting orientation.</param>
        /// <param name="board">The plateau the rover will land on.</param>
        public MarsRover(int x, int y, Orientation orientation, Board.Board board)
        {
            _board      = board;
            _boardPeice = _board.Place(x, y);
            Orientation = orientation;

            AssertDrivable();
        }
Esempio n. 15
0
        public void Board_CorrectBoardSizeProvided_CreatesBoard()
        {
            // Act
            var board = new Board.Board();

            // Assert
            board.Tiles.Should().HaveCount(100, "board was created correctly");
        }
        public void GameInitializationOnlyOnePlayer()
        {
            var playerList = new List<IPlayer> { new Player("[Black]Gosho", ChessColor.Black) };
            var board = new Board.Board(GlobalConstants.StandartGameTotalBoardRows, GlobalConstants.StandartGameTotalBoardCols);

            var strategy = new KingSurvivalGameInitializationStrategy();
            strategy.Initialize(playerList, board);
        }
Esempio n. 17
0
        private bool IsIllegalMove(Move move)
        {
            var tempBoard = new Board.Board(_board);

            tempBoard.MovePiece(move);

            return(IsCheck(move.Color, tempBoard));
        }
Esempio n. 18
0
        private static void AddWhitePawnMove(Board.Board board, int from, int to,
                                             MoveList list)
        {
            Debug.Assert(Validators.SqOnBoard(from), String.Format("Invalid from square {0}", from));
            Debug.Assert(Validators.SqOnBoard(to), String.Format("Invalid to square {0}", to));

            MoveGen.AddWhitePawnCapMove(board, from, to, (int)Piece.EMPTY, list);
        }
        public void GameInitializationInvalidBoard()
        {
            var playerList = new List<IPlayer> { new Player("[Black]Gosho", ChessColor.Black), new Player("[White]Pesho", ChessColor.White) };
            var board = new Board.Board(5, GlobalConstants.StandartGameTotalBoardCols);

            var strategy = new KingSurvivalGameInitializationStrategy();
            strategy.Initialize(playerList, board);
        }
Esempio n. 20
0
            public TurnEvaluator(Board.Board board)
            {
                var gridBoard = board as GridBoard;

                strategies = new List <ITurnStrategy>()
                {
                    new StraitCapture(gridBoard)
                };
            }
Esempio n. 21
0
        private List <Move> GetLegalMoves(Vector2 position, Board.Board board)
        {
            var possibleMoves = GetPossibleMoves(position, board);

            var illegalMoves = possibleMoves.Where(IsIllegalMove).ToList();

            illegalMoves.ForEach(m => possibleMoves.Remove(m));
            return(possibleMoves);
        }
Esempio n. 22
0
 public Model(Dictionary.Dictionary GameDictionary, Language.Language Language)
 {
     this.GameLanguage = Language;
     TilesSet = new TilesSet(Language);
     this.Players = new List<Player.Player>();
     this.GameBoard = new Board.Board();
     this.GameDictionary = GameDictionary;
     this.PassCounter = 0;
 }
Esempio n. 23
0
        public static void AddEnPassantMove(Board.Board board, int move, MoveList list)
        {
            Debug.Assert(Validators.SqOnBoard(MoveOperations.FromSq(move)));
            Debug.Assert(Validators.SqOnBoard(MoveOperations.ToSq(move)));

            list.Moves[list.Count].Move  = move;
            list.Moves[list.Count].Score = 105 + 1000000;
            list.Count++;
        }
Esempio n. 24
0
        /// <summary>
        /// Gets value indicating whether the piece is covered by friendly piece
        /// </summary>
        /// <param name="piece">Piece instance</param>
        /// <param name="board">Game board</param>
        /// <returns>Value indicating whether the piece is covered by friendly piece</returns>
        public static bool IsPieceCoveredByFriendlyPiece(Piece piece, Board.Board board)
        {
            Piece tmpPiece = new Piece(piece.X, piece.Y, piece.Team == TeamType.WHITE ? TeamType.BLACK : TeamType.WHITE);

            Board.Board tmpBoard = new Board.Board(board);
            tmpBoard[tmpPiece.X, tmpPiece.Y].RemovePiece();
            tmpBoard[tmpPiece.X, tmpPiece.Y].SetPiece(tmpPiece);
            (bool res, var tmp) = IsPieceCanBeCapturedByEnemy(tmpPiece, tmpBoard);
            return(res);
        }
Esempio n. 25
0
        public static ICoordinator InitializeGame(int boardWidth = 5, int boardHeight = 5, int numberOfRobots = 1)
        {
            var board       = new Board.Board();
            var coordinator = new Coordinator(board);

            coordinator.InitializeBoard(boardWidth, boardHeight);
            coordinator.NumberOfRobotsAllowed = numberOfRobots;

            return(coordinator);
        }
        public void GameInitializationCheckPlayerCorrectName()
        {
            var playerList = new List<IPlayer> { new Player("[Black]Gosho", ChessColor.Black), new Player("[White]Pesho", ChessColor.White) };
            var board = new Board.Board(GlobalConstants.StandartGameTotalBoardRows, GlobalConstants.StandartGameTotalBoardCols);

            var strategy = new KingSurvivalGameInitializationStrategy();
            strategy.Initialize(playerList, board);

            Assert.AreEqual("[Black]Gosho", playerList[0].Name);
        }
Esempio n. 27
0
 public ChessMatch()
 {
     Board         = new Board.Board(8, 8);
     Round         = 1;
     CurrentPlayer = Color.White;
     Pieces        = new HashSet <Piece>();
     CatchedPieces = new HashSet <Piece>();
     InCheck       = false;
     StartMatch();
 }
Esempio n. 28
0
 public (bool Castled, string Error) Castle(CastleTypeEnum castleType, Board.Board board)
 {
     if (castleType == CastleTypeEnum.Kingside)
     {
         return(CastleKingSide(board));
     }
     else
     {
         return(CastleQueenSide(board));
     }
 }
Esempio n. 29
0
 /// <summary>
 /// Gets value indicating whether the team received a checkmate
 /// </summary>
 /// <param name="team">Team</param>
 /// <param name="board">Game board</param>
 /// <returns>Value indicating whether the team received a checkmate</returns>
 public static bool IsCheckMate(TeamType team, Board.Board board)
 {
     foreach (var cell in board)
     {
         if (!cell.IsEmpty && cell.Piece is King && cell.Piece.Team == team)
         {
             return(IsCheckMate((King)cell.Piece, board));
         }
     }
     throw new Exception("No King instance found on board for current team");
 }
Esempio n. 30
0
        public List <KeyValuePair <int, int> > AvailableMoves(Board.Board board)
        {
            List <KeyValuePair <int, int> > availableMoves = new List <KeyValuePair <int, int> >();

            GetAvailableMovesInInterval(board, availableMoves, -1, -1);
            GetAvailableMovesInInterval(board, availableMoves, -1, 1);
            GetAvailableMovesInInterval(board, availableMoves, 1, 1);
            GetAvailableMovesInInterval(board, availableMoves, 1, -1);

            return(availableMoves);
        }
Esempio n. 31
0
        public (int, int) GetNextMove(Board.Board board)
        {
            Random random     = new Random();
            var    legalMoves = board.GetLegalMoves();

            int randomIndex = random.Next(legalMoves.Count);

            return(legalMoves.ToArray()[randomIndex]);

            throw new NotImplementedException();
        }
Esempio n. 32
0
 /// <summary>
 /// Gets value indicating whether the team received a checkmate
 /// </summary>
 /// <param name="player">Player instance</param>
 /// <param name="board">Game board</param>
 /// <returns>Value indicating whether the team received a checkmate</returns>
 public static bool IsCheckMate(Team team, Board.Board board)
 {
     foreach (var piece in team.Pieces)
     {
         if (piece is King)
         {
             return(IsCheckMate((King)piece, board));
         }
     }
     throw new Exception("No King instance found in Player piaces collection");
 }
Esempio n. 33
0
 private bool IsAllSquaresAlongCastleAreEmpty(int column1, int column2, Board.Board board)
 {
     for (int column = column1; column <= column2; ++column)
     {
         if (!board.IsEmpty(initialKingRow, column))
         {
             return(false);
         }
     }
     return(true);
 }
Esempio n. 34
0
        private List <Vector2> GetThreatPositionsForColor(PieceColor color, Board.Board board)
        {
            var threatPositionsForColor = new List <Vector2>();

            foreach (var data in board.ChessPieceData.Where(d => d.Color == color.Opposite()))
            {
                threatPositionsForColor.AddRange(GetThreatMoves(data.Position, board).Select(m => m.To));
            }

            return(threatPositionsForColor);
        }
Esempio n. 35
0
 public void SetGame(Game.Game game)
 {
     _game = game;
     _board = game.Board;
     InitialiseBuffer();
 }
Esempio n. 36
0
 public MoveProcessor(Board.Board initialBoard)
 {
     board = initialBoard;
 }
Esempio n. 37
0
        private void CreateEmulator()
        {
            lock (_syncRoot)
            {
                DestoryEmulator();

                _board = new Board.Board(new GdiVideo(_videoOutput), _kernel, _basic, _charGen);

                _drive = new DiskDrive.CBM1541(_driveKernel, _board.Serial);

                _board.SystemClock.OnPhaseEnd += _drive.DriveClock.Run;
                _board.OnLoadState += _drive.ReadDeviceState;
                _board.OnSaveState += _drive.WriteDeviceState;

                _keyboard = new Input.Keyboard(_board.SystemCias[0].PortA, _board.SystemCias[0].PortB, null);

                _emulatorRunning = true;
            }
        }
Esempio n. 38
0
 public void ResetGame()
 {
     GameBoard = new Board.Board();
     Players.Clear();
     CurrentPlayer = null;
     TilesSet = new TilesSet(GameLanguage);
     PassCounter = 0;
     GameBoard.SetEmpty(true);
 }
Esempio n. 39
0
        private void DestoryEmulator()
        {
            if (_board != null)
            {
                _board.SystemClock.OnPhaseEnd -= _drive.DriveClock.Run;
                _board.OnLoadState -= _drive.ReadDeviceState;
                _board.OnSaveState -= _drive.WriteDeviceState;

                _board = null;
                _drive = null;
                _keyboard = null;
            }
        }
Esempio n. 40
0
 public void WhenISetUpTheBeginnerBoardForCatan()
 {
     _board = (new SettlerBeginnerBoardConstructor()).ConstructBoard();
 }
Esempio n. 41
0
        private string validWhiteMove = "nbw"; // null black white

        #endregion Fields

        #region Constructors

        public MoveFinder(Board.Board board, Colors playerColor)
        {
            this.board = board;
            this.color = playerColor;
        }