示例#1
0
		protected Logic(Board.Data boardData, Vector2D[] homeSquares)
		{
			Board = new Board(boardData);
			this.homeSquares = homeSquares;
			availableColorFinder = new AvailableColorFinder(Board, homeSquares);
			turns = new int[homeSquares.Length];
		}
示例#2
0
 public ExpressConveyorBelt(Board board, Tile baseTile, TileDirection direction, TurnDirection turn, int x,
     int y)
     : base(board, baseTile, x, y)
 {
     Direction = direction;
     Turn = turn;
 }
示例#3
0
    public static Board Board(Board boardPrefab)
    {
        Board board = Instantiate<Board>(boardPrefab);
        board.Init(Instance.UISignals);

        return board;
    }
示例#4
0
		protected Logic(int width, int height, Vector2D[] homeSquares)
		{
			Board = new Board(width, height);
			this.homeSquares = homeSquares;
			availableColorFinder = new AvailableColorFinder(Board, homeSquares);
			turns = new int[homeSquares.Length];
		}
    public void BuildLevel(Board board)
    {
        var children = new List<GameObject>();
        foreach (Transform child in transform)
            children.Add(child.gameObject);
        children.ForEach(child => Destroy(child));

        originalMatrix = board.Grid;
        matrix = PrepareMatrix(originalMatrix);
        int n = board.NoRooms;
        floors = new Floor[matrix.GetLength(0)-2,matrix.GetLength(1)-2];
        walls = new Wall[matrix.GetLength(0)-1, matrix.GetLength(1)-1];
        Rooms = new Room[n];
        graph = new Graph();
        for (int i = 0; i < n; ++i)
        {
            Rooms[i] = new Room(i+1, DefaultFloorMaterial);
        }
        RoomPropertiesPanel.InitializePanel(n);
        Vector3 shift = new Vector3(((matrix.GetLength(1) - 2) * unit) / 2, 0f, ((matrix.GetLength(0) - 2) * -unit) / 2);
        this.transform.position = shift;
        SpawnWalls();
        SpawnFloors();
        SpawnDoors();
        foreach (var room in Rooms)
        {
            room.SetRoomMaterial();
        }
        isSaved = false;
    }
示例#6
0
 public void onBoardChange(Player p, Board b)
 {
     if (LotusGame.get().players[LotusGame.get().currentPlayer] != p)
     {
         currentState.onBoardChange(p, b);
     }
 }
示例#7
0
        public void EqualsReturnsTrueWhenEqual()
        {
            int[,] data1 = {
                {9,0,0, 0,0,5, 6,8,1 },
                {0,6,0, 2,8,0, 7,0,0 },
                {0,0,0, 0,0,6, 9,0,5 },
                {0,8,0, 0,0,2, 0,4,6 },
                {0,0,5, 0,0,0, 3,0,0 },
                {1,9,0, 5,0,0, 0,7,0 },
                {8,0,2, 9,0,0, 0,0,0 },
                {0,0,9, 0,2,7, 0,6,0 },
                {6,7,4, 8,0,0, 0,0,3 }
            };

            int[,] data2 = {
                {9,0,0, 0,0,5, 6,8,1 },
                {0,6,0, 2,8,0, 7,0,0 },
                {0,0,0, 0,0,6, 9,0,5 },
                {0,8,0, 0,0,2, 0,4,6 },
                {0,0,5, 0,0,0, 3,0,0 },
                {1,9,0, 5,0,0, 0,7,0 },
                {8,0,2, 9,0,0, 0,0,0 },
                {0,0,9, 0,2,7, 0,6,0 },
                {6,7,4, 8,0,0, 0,0,3 }
            };

            IBoard board1 = new Board(data1);
            IBoard board2 = new Board(data2);

            Assert.True(board1.Equals(board2));
            Assert.True(board2.Equals(board1));
            Assert.True(board1.Equals(board1));
            Assert.True(board2.Equals(board2));
        }
示例#8
0
 public State(Board board, Goat g,
     Tiger t)
 {
     this.goat = g;
     this.tiger = t;
     this.board = board;
 }
示例#9
0
        public void UpdateSquares(Board instanceBoard)
        {
            for (int i = 0; i < _allSquares.LongLength; i++)
            {
                int y = i%15; //rows
                int x = i/15; //columns
                Square s = instanceBoard.Get(x,y);
                //remove tile
                BoardSquare thisGuy = _allSquares[x,y];
                thisGuy.MySquare = s;
                thisGuy.PlacedTile = null;
                //add tile if exists
                if (!s.IsEmpty)
                {
                    Scrabble.Core.Types.Tile t = (Scrabble.Core.Types.Tile)s.Tile;
                    _allSquares[x, y].PlacedTile = new Tile(t.Letter.ToString(), t.Score);
                }
                else if (s.WordMultiplier > 0 || s.LetterMultiplier > 0)
                {
                    //special square, need to display accordingly
                    thisGuy.SquareContainer.Background = ("#" + s.Gradient).ToBrush();
                }                   

            }
            Redraw();
                
        }
示例#10
0
 public ToolTipInstance(Board board, XNA.Rectangle rect, string title, string desc, int originalNum = -1)
     : base(board, rect)
 {
     this.title = title;
     this.desc = desc;
     this.originalNum = originalNum;
 }
示例#11
0
 public ToolTipInstance(Board board, SerializationForm json)
     : base(board, json)
 {
     title = json.title;
     desc = json.desc;
     originalNum = json.originalnum;
 }
示例#12
0
	// Use this for initialization
	void Start () {
		rend = gameObject.GetComponent<SpriteRenderer> ();
		rend.enabled = false;
		board = GameObject.FindWithTag ("Board").GetComponent<Board>();
		menu = GameObject.FindWithTag ("Menu");

	}
示例#13
0
 public void CheckIfAddNullFigureThrowsException()
 {
     var board = new Board();
     var position = new Position(6, 6);
     IFigure figure = null;
     board.AddFigure(figure, position);
 }
示例#14
0
        public void _003_Does_Particular_Cell_Exist()
        {
            var board = new Board();
            var expected = board.CellExists(new Coordinate(3, 4));

            Assert.IsTrue(expected);
        }  
示例#15
0
        public IEnumerable<Movement> FindMoves(Board board)
        {
            List<Tuple<Block, FlagCombination>> allValidCombinations = new List<Tuple<Block, FlagCombination>>();
            for (int i = 0; i < board.Width; i++)
            {
                for (int j = 0; j < board.Height; j++)
                {
                    Block current = board.Grid[i, j];
                    if (current.State != BlockState.Value || current.Value == 0)
                        continue;

                    var neighbors = new NeighborList(board.Grid, current);
                    if (board.isBlockSolved(current, neighbors))
                        continue;

                    int flagCount = neighbors.GetFlagCount();
                    var unknown = neighbors.GetUnknownBlocks().ToList();

                    allValidCombinations.Add(new Tuple<Block, FlagCombination>(current,
                        board.getValidCombinations(unknown, current.Value - flagCount)));
                }
            }

            yield break;
        }
示例#16
0
    public void GameOfLife(int[,] board)
    {
        Board board2 = new Board (board);
        int row = board.GetLength (0);
        int col = board.GetLength (1);
        int[,] temp=new int[board.GetLength(0),board.GetLength(1)];

        for (int i=0; i<row; i++)
        for (int j=0; j<col; j++) {
            temp[i,j]=board[i,j];
        }
        for (int i=0; i<row; i++)
        for (int j=0; j<col; j++) {
            int count=board2.GetAdjacentPointCount(i,j);
            if(board[i,j]==1){
                if(count<2){//0 or 1
                    temp[i,j]=0;
                }
                else if(count<4){//2 or 3
                    temp[i,j]=1;
                }
                else if(count>3){//3,4,5,6,7,8
                    temp[i,j]=0;
                }
            }
            else if(count ==3){
                temp[i,j]=1;
            }
        }
        board = temp;
        b = temp;
    }
示例#17
0
 /// <summary>
 /// Construct a thread from an initial post and a board.
 /// </summary>
 /// <param name="board">The parent board out of the board cache.</param>
 /// <param name="op">The first post in the thread.</param>
 public Thread(Board board, APIPost op)
 {
     Board = board;
     Number = op.Number;
     Posts = new SortedDictionary<ulong, Post>();
     Merge(op);
 }
示例#18
0
        public void TestFindDirectWinningPossibilities_MultiplePossibilties()
        {
            //setup the initial condition
            var player1 = new Object();
            var player2 = new Object();
            Board board = new Board();

            board[1][0].OwningPlayer = player2;
            board[1][1].OwningPlayer = player2;
            board[1][2].OwningPlayer = player1;

            board[2][0].OwningPlayer = player2;
            board[2][1].OwningPlayer = player2;
            board[2][2].OwningPlayer = player1;

            board[3][0].OwningPlayer = player1;
            board[3][1].OwningPlayer = player1;
            board[3][2].OwningPlayer = player1;

            board[4][0].OwningPlayer = player1;
            board[4][1].OwningPlayer = player1;

            var winningPossibilites = AIHelper.FindDirectWinningPossibilities(board, player1);

            Assert.AreEqual(board[1][3], winningPossibilites[0]); //negative diagonal
            Assert.AreEqual(board[3][3], winningPossibilites[1]); //there's a vertical here as well
            Assert.AreEqual(board[4][2], winningPossibilites[2]); //horizontal across the middle
            Assert.AreEqual(3, winningPossibilites.Count);
        }
示例#19
0
 private void Awake()
 {
     List<Teleporter> teleporters = new List<Teleporter>() { new Teleporter(2, 12), new Teleporter(8, 3) };
     int finalPosition = 100;
     Dice dice = new Dice();
     board = new Board(dice, teleporters, finalPosition);
 }
示例#20
0
 // Constructor
 public Game(int playerCount)
 {
     numberOfPlayers = playerCount;
     players = new Player[numberOfPlayers];
     currentPlayer = players[InitFirstPlayer(numberOfPlayers)];
     board = new Board();
 }
示例#21
0
        public MainForm()
        {
            SuspendLayout();

            _humanBoard = new Board();
            _computerBoard = new Board(false);

            _humanPlayer = new HumanPlayer("You", _computerBoard);
            _computerPlayer = new ComputerPlayer("Computer");

            _scoreboard = new ScoreBoard(_humanPlayer, _computerPlayer, 10, 100);
            _controller = new GameController(_humanPlayer, _computerPlayer, _humanBoard, _computerBoard, _scoreboard);

            _shuffleButton = CreateButton(ShuffleCharacter.ToString(), ButtonBackColor);
            _newGameButton = CreateButton(NewGameCharacter.ToString(), ButtonBackColor);
            _startGameButton = CreateButton(StartGameCharacter.ToString(), ButtonBackColor);

            SetupWindow();
            LayoutControls();

            _scoreboard.GameEnded += OnGameEnded;

            _shuffleButton.Click += OnShuffleButtonClick;
            _startGameButton.Click += OnStartGameButtonClick;
            _newGameButton.Click += OnNewGameButtonClick;

            ResumeLayout();

            StartNewGame();
        }
示例#22
0
        public void doMove(Player p, Board b)
        {
            Console.WriteLine("This is the move when i'm angry!!!!!!!!!!!!!!");
            stateMachine.goingTo.coverOpponent(p, b);

            availableMoves = AICalc.getPossibleMoves(p, b);
        }
示例#23
0
		public override bool ShouldBePlayed(Board board)
        {
			if(board.MinionFriend.Count == 0 && board.MinionEnemy.Count == 0)
				return false;
				
            return true;
        }
示例#24
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Puzzle"/> class.
        /// 
        /// The solution and givens are both generated using the same random seed.
        /// </summary>
        /// <param name="Seed">The random seed to use.</param>
        public Puzzle(int Seed)
        {
            Random rnd = new Random(Seed);

            _solution = Factory.Solution(rnd);
            _givens = Factory.Puzzle(_solution, rnd, 4, 4, 4);
        }
示例#25
0
 public Move(Step step, Board board)
 {
     _board = board;
     Step = new Step(step);
     oldFrom = _board[(step.FromX << 3) + step.FromY];
     oldTo = _board[(step.ToX << 3) + step.ToY];
 }
			public WalkCommand(Point from,int width, int height,Board parent)
			{
				m_from = from;
				m_parent = parent;

				m_posibilities = CalculatePosibilities(width,height);
			}
示例#27
0
    public void CalculateGameOfLife(int[,] array)
    {
        board = new Board (array);
        row = array.GetLength (0);
        col = array.GetLength (1);
        int[,] temp=new int[array.GetLength(0),array.GetLength(1)];

        for (int i=0; i<row; i++)
        for (int j=0; j<col; j++) {
            temp[i,j]=array[i,j];
        }
        for (int i=0; i<row; i++)
        for (int j=0; j<col; j++) {
            int count=board.GetAdjacentPointCount(i,j);
            if(array[i,j]==1){
                if(count<2){//0 or 1
                    temp[i,j]=0;
                }
                else if(count<4){//2 or 3
                    temp[i,j]=1;
                }
                else if(count>3){//3,4,5,6,7,8
                    temp[i,j]=0;
                }
            }
            else if(count ==3){
                temp[i,j]=1;
            }
        }
        array = temp;
        mArray = temp;
    }
示例#28
0
    public GameDescriptor(Board board, Unit.OwnerEnum turn)
    {
        units = new UnitInfo[BoardInfo.Row, BoardInfo.Col];
        grids = new Board.GridState[BoardInfo.Row, BoardInfo.Col];
        playerInfo = new int[2][] { new int[(int)(Unit.TypeEnum.Void)], new int[(int)(Unit.TypeEnum.Void)]};

        for (int i = 0; i < BoardInfo.Row; i++)
            for (int j = 0; j < BoardInfo.Col; j++)
            {
                units[i, j] = board.GetUnitInfo(new Position(i, j));
                if (units[i, j].type == Unit.TypeEnum.Bread)
                    units[i, j].type = Unit.TypeEnum.Void;
                grids[i, j] = board.GetGridState(new Position(i, j));
            }

        for(Unit.TypeEnum type = Unit.TypeEnum.Bread; type < Unit.TypeEnum.Void; type++) {
           playerInfo[(int)Unit.OwnerEnum.Black][(int)type] = board.GetPlayerInfo(type,Unit.OwnerEnum.Black);
           playerInfo[(int)Unit.OwnerEnum.White][(int)type] = board.GetPlayerInfo(type,Unit.OwnerEnum.White);
        }

        restResource = board.RestBread;

        hasMove = false;
        hasBuy = false;
        this.turn = turn;
    }
 public void BeforeEachTest()
 {
     Target = new Board();
     var positioner = new PiecePositioner(Target);
     positioner.SetupStandardPieces(1);
     positioner.SetupStandardPieces(8, false);
 }
示例#30
0
 public LayeredItem(Board board, Layer layer, int zm, int x, int y, int z)
     : base(board, x, y, z)
 {
     this.layer = layer;
     layer.Items.Add(this);
     this.zm = zm;
 }
示例#31
0
 public override void OnPlay(ref Board board, Card target = null, int index = 0, int choice = 0)
 {
     base.OnPlay(ref board, target, index);
     board.FriendCardDraw--;
     board.Resimulate();
 }
示例#32
0
 public override void OnPlay(ref Board board, Card target = null, int index = 0, int choice = 0)
 {
     base.OnPlay(ref board, target, index);
 }
示例#33
0
 /// <summary>
 /// 局面が全部更新された場合のコンストラクタ
 /// </summary>
 public BoardChangedEventArgs(Board board, bool isMovedByGui)
 {
     Board        = board;
     IsMovedByGui = IsMovedByGui;
 }
示例#34
0
 public Game()
 {
     state = State.INITIAL;
     turn  = new Turn();
     board = new SetBoard();
 }
示例#35
0
 public override void OnCastSpell(ref Board board, Card Spell)
 {
     base.OnCastSpell(ref board, Spell);
 }
示例#36
0
 public override void OnPlayOtherMinion(ref Board board, Card Minion)
 {
     base.OnPlayOtherMinion(ref board, Minion);
 }
示例#37
0
 public override void OnDeath(ref Board board)
 {
     base.OnDeath(ref board);
 }
示例#38
0
        public static string WriteHex(string hexStr, byte[] asmBytes, Board board)
        {
            if (asmBytes.Length > board.DataSize)
            {
                throw new AssembleException("烧录失败!字节超出限制");
            }
            List <byte> list = new List <byte>(asmBytes);
            // load hex file
            var             lines   = hexStr.Split('\r', '\n');
            List <IntelHex> hexFile = new List <IntelHex>();

            foreach (var line in lines)
            {
                try
                {
                    var hex = IntelHex.Parse(line);
                    if (hex != null)
                    {
                        hexFile.Add(hex);
                    }
                }
                catch (AssembleException ex)
                {
                    throw new AssembleException("固件读取失败!" + ex.Message);
                }
            }
            // find data position
            int index = hexFile.FindIndex(hex =>
            {
                if (hex.Data.Length < 0x10)
                {
                    return(false);
                }
                for (int i = 0; i < hex.Data.Length; i++)
                {
                    if (i < 2 && hex.Data[i] != 0xFF || i > 2 && hex.Data[i] != 0)
                    {
                        return(false);
                    }
                }
                return(true);
            });

            if (index == -1)
            {
                throw new AssembleException("固件读取失败!未找到数据结构");
            }
            int ver = hexFile[index].Data[2];

            if (ver < board.Version)
            {
                throw new AssembleException("固件版本不符,请使用最新版的固件");
            }
            // write data from asmBytes
            for (int i = 0; i < list.Count;)
            {
                int    len  = Math.Min(hexFile[index].DataSize, list.Count - i);
                byte[] data = hexFile[index].Data.ToArray();
                list.CopyTo(i, data, 0, len);
                hexFile[index].WriteData(data);
                i += len;
                index++;
            }
            // get string
            var str = new StringBuilder();

            foreach (var hex in hexFile)
            {
                str.AppendLine(hex.ToString());
            }
            return(str.ToString());
        }
        // Start is called before the first frame update
        private void Start()
        {
            string savedColorPalette = PlayerPrefs.GetString("ColorPalette");

            _currentColorPalette = savedColorPalette != "" ?
                                   Resources.Load <ColorPalette>("ColorPalettes/" + savedColorPalette) : Resources.Load <ColorPalette>("ColorPalettes/Day");

            _gameBoard    = FindObjectOfType <Board>();
            _spawner      = FindObjectOfType <Spawner>();
            _uiManager    = FindObjectOfType <UIManager>();
            _scoreManager = FindObjectOfType <ScoreManager>();

            // If the game is restarted we don't need main menu displayed again
            if (_isRestarted)
            {
                _uiManager.CloseMainMenu();
                _isRestarted = false;
                SoundManager.Instance.PlayStartSound();
            }

            _mainCamera = Camera.main;
            if (!_mainCamera)
            {
                Debug.Log("Cant get main camera");
                return;
            }

            _shapesInPlay         = new Shape[3];
            _numberOfShapesInPlay = _shapesInPlay.Length;

            _scoreManager.SetHighScore(PlayerPrefs.GetInt("highScore"));
            _uiManager.SetHighScoreUI(_scoreManager.GetHighScore());
            _uiManager.SetMainMenuHighScoreUI(_scoreManager.GetHighScore());

            if (!_gameBoard)
            {
                Debug.LogWarning("There is no game board");
                return;
            }

            if (!_spawner)
            {
                Debug.LogWarning("There is no spawner");
                return;
            }

            // Spawn first 3 shapes
            Shape spawnedShape = _spawner.SpawnShapeAtPositionWithScaleAndRandomRotation(
                new Vector3(1f, -3, -2),
                new Vector3(0.6f, 0.6f, 1.0f));

            _shapesInPlay[0] = spawnedShape;
            spawnedShape     = _spawner.SpawnShapeAtPositionWithScaleAndRandomRotation(
                new Vector3(4.5f, -3, -2),
                new Vector3(0.6f, 0.6f, 1.0f));
            _shapesInPlay[1] = spawnedShape;
            spawnedShape     = _spawner.SpawnShapeAtPositionWithScaleAndRandomRotation(
                new Vector3(8f, -3, -2),
                new Vector3(0.6f, 0.6f, 1.0f));
            _shapesInPlay[2] = spawnedShape;

            ChangeGameColorPalette(_currentColorPalette);
        }
示例#40
0
        public int Run(Board board, int numToWin, int playerNumber = 2)
        {
            PLAYERNUM = playerNumber;
            var search = new BoardSearch(numToWin);

            var legalMoves = search.FindAllLegalMoves(board);

            var yourThreats = search.FindGroups(PLAYERNUM, board, 1);
            var oppThreats  = search.FindGroups(1, board, 1);

            int?columnToPlay = 0;

            //can you win?
            columnToPlay = MatchThreatsWithLegal(yourThreats, legalMoves);
            if (columnToPlay.HasValue)
            {
                return(columnToPlay.Value);
            }

            //should you block?
            columnToPlay = MatchThreatsWithLegal(oppThreats, legalMoves);
            if (columnToPlay.HasValue)
            {
                return(columnToPlay.Value);
            }

            //are there hidden forks for player 1?
            //look for threats with 2 blanks
            var forkThreats = search.FindGroups(1, board, 2);
            //do any threats share a blank?
            var forkPositions = new List <Position>();

            for (var i = 0; i < forkThreats.Count; i++)
            {
                var ft     = forkThreats[i];
                var blanks = ft.Coords.Where(c => c.Mark == 0);

                for (var j = 0; j < forkThreats.Count; j++)
                {
                    if (j == i)
                    {
                        continue;
                    }

                    var jft     = forkThreats[j];
                    var jBlanks = jft.Coords.Where(c => c.Mark == 0);

                    var shared = jBlanks.Intersect <Position>(blanks, new PositionEqualityComparer());
                    forkPositions.AddRange(shared);
                }
            }

            //are any blanks legal moves?
            columnToPlay = MatchPositionsThreatsWithLegal(forkPositions, legalMoves);
            if (columnToPlay.HasValue)
            {
                return(columnToPlay.Value);
            }

            //should we remove a legal move if it will harm us?
            //can player1 score after this move?
            //take all legal moves and transpose one row up - do any fulfill player 1 threats?
            var toRemove = new List <Position>();

            foreach (var legalMove in legalMoves)
            {
                var transposedMove = new Position(legalMove.Row + 1, legalMove.Col, 0);
                foreach (var threat in oppThreats)
                {
                    var blank = threat.Coords.Single(t => t.Mark == 0);
                    if (blank.Equals(transposedMove))
                    {
                        toRemove.Add(legalMove);
                    }
                }
            }

            toRemove.ForEach(r => legalMoves.Remove(r));

            //claimeven
            var claimevens = search.FindPossibleClaimEvens(board);

            foreach (var claimEven in claimevens)
            {
                foreach (var move in legalMoves)
                {
                    if (claimEven == move.Col)
                    {
                        return(claimEven);
                    }
                }
            }

            var moveIndex = random.Next(0, legalMoves.Count());

            return(legalMoves[moveIndex].Col);
        }
示例#41
0
        public override async Task Decide(Board board, Decider decider)
        {
            if (_tile.TileType.Suit == Suit.Jihai && _tile.Index < 4 && board.IsFirstGoAround)
            {
                if (board.Seats.SelectMany(s => s.Discards).Count(t => t.TileType == _tile.TileType) == 4)
                {
                    _nextState = new Abort();
                    return;
                }
            }

            var fourKanAbortIfNoRon = board.Seats.SelectMany(s => s.Melds).Count(m => m.IsKan) == 4 && board.Seats.Count(s => s.Melds.Any(m => m.IsKan)) > 1;

            var reactionTasks = new Task <DiscardResponse> [4];
            var clients       = new Client[4];

            for (var i = 0; i < 4; i++)
            {
                if (i == board.ActiveSeatIndex)
                {
                    reactionTasks[i] = Task.FromResult(DiscardResponse.Pass());
                    clients[i]       = new Client(i, DiscardActions.Pass);
                    continue;
                }

                var actions = GetPossibleActions(board, i, fourKanAbortIfNoRon);
                if (actions != DiscardActions.Pass)
                {
                    reactionTasks[i] = decider.OnDiscard(actions, i);
                    clients[i]       = new Client(i, actions);
                    continue;
                }

                reactionTasks[i] = Task.FromResult(DiscardResponse.Pass());
                clients[i]       = new Client(i, DiscardActions.Pass);
            }

            await Task.WhenAll(reactionTasks);

            for (var i = 0; i < 4; i++)
            {
                reactionTasks[i].Result.Execute(clients[i]);
                if (clients[i].IgnoredRon)
                {
                    _ignoredRonSeats.Add(i);
                }
            }

            var ronCount = clients.Count(c => c.Ron);

            if (ronCount == 3)
            {
                _nextState = new Abort();
                return;
            }

            if (ronCount > 0)
            {
                _nextState = new Ron(clients.Where(r => r.Ron).Select(r => r.SeatIndex));
                return;
            }

            if (fourKanAbortIfNoRon)
            {
                _nextState = new Abort();
                return;
            }

            var kan = clients.FirstOrDefault(c => c.Daiminkan);

            if (kan != null)
            {
                _nextState = new Daiminkan(kan.SeatIndex);
                return;
            }

            var pon = clients.FirstOrDefault(c => c.Pon);

            if (pon != null)
            {
                _nextState = new Pon(pon.SeatIndex, pon.Tile0 !, pon.Tile1 !, pon.Discard !);
                return;
            }

            var chii = clients.FirstOrDefault(c => c.Chii);

            if (chii != null)
            {
                _nextState = new Chii(chii.SeatIndex, chii.Tile0 !, chii.Tile1 !, chii.Discard !);
                return;
            }

            if (board.Wall.RemainingDraws == 0)
            {
                _nextState = new ExhaustiveDraw();
            }
            else
            {
                _nextState = new Draw((board.ActiveSeatIndex + 1) % 4);
            }
        }
示例#42
0
        public GameObject CreateShipModel(Vector3 position)
        {
            Vector3 facing = (Owner.PlayerNo == Players.PlayerNo.Player1) ? ShipFactory.ROTATION_FORWARD : ShipFactory.ROTATION_BACKWARD;

            position = new Vector3(0, 0, (Owner.PlayerNo == Players.PlayerNo.Player1) ? -4 : 4);

            GameObject shipPrefab = (GameObject)Resources.Load("Prefabs/ShipModel/ShipModel", typeof(GameObject));
            GameObject newShip    = MonoBehaviour.Instantiate(shipPrefab, position + new Vector3(0, 0.03f, 0), Quaternion.Euler(facing), Board.GetBoard());

            GameObject modelPrefab = GetShipModelPrefab();

            if (modelPrefab != null)
            {
                GameObject newModel = MonoBehaviour.Instantiate(modelPrefab, newShip.transform.Find("RotationHelper/RotationHelper2/ShipAllParts/ShipModels"));
                newModel.name = SpecialModel ?? FixTypeName(ModelInfo.ModelName);
            }

            SetShipIdText(newShip);

            return(newShip);
        }
示例#43
0
 public virtual void Update(Board item)
 {
     Database.Entry(item).State = EntityState.Modified;
 }
示例#44
0
 public void MakeAMove(out int shapeId, out string placement, Board board, IDictionary <int, Shape> shapes, IGameDrawer renderer)
 {
     shapeId   = renderer.ChooseShape();
     placement = renderer.ChoosePlacement();
 }
示例#45
0
 private void AddUserAsBoardCreator(User user, Board board)
 {
     board.Creator = user;
 }
示例#46
0
 public override void Update(Board board, Wall wall)
 {
     board.ActiveSeat.Discard(_tile);
 }
示例#47
0
 public void Write(Board board)
 {
     _board = board;
 }
示例#48
0
        /// <summary>
        /// Da li postoji legalan potez koji blokira sah
        /// </summary>
        public static bool CanBlockAttacker(Board board, Field attackerField, bool white)
        {
            List <Field> allDefenders = new List <Field>();

            if (new Knight(true).GetType().Equals(attackerField.Piece.GetType()))
            {
                return(false);
            }
            else
            {
                int coef      = white ? 0 : 1;
                int attackerX = attackerField.X;
                int attackerY = attackerField.Y;
                int kingX     = board.CurrentKingFields[coef].X;
                int kingY     = board.CurrentKingFields[coef].Y;
                //lista svih polja od kralja do napadacke figure ukljucujuci i napadaca
                //ako napadamo neko od tih polja, sah je blokiran ili napadac pojeden
                List <Field> path = new List <Field>();

                if (attackerY == kingY && attackerX > kingX)
                {
                    path = ExploreNorth(board, board.CurrentKingFields[coef], attackerField);
                }

                if (attackerY == kingY && attackerX < kingX)
                {
                    path = ExploreSouth(board, board.CurrentKingFields[coef], attackerField);
                }

                if (attackerY > kingY && attackerX == kingX)
                {
                    path = ExploreEast(board, board.CurrentKingFields[coef], attackerField);
                }

                if (attackerY < kingY && attackerX == kingX)
                {
                    path = ExploreWest(board, board.CurrentKingFields[coef], attackerField);
                }

                if (attackerY > kingY && attackerX > kingX)
                {
                    path = ExploreNorthEast(board, board.CurrentKingFields[coef], attackerField);
                }

                if (attackerY < kingY && attackerX > kingX)
                {
                    path = ExploreNorthWest(board, board.CurrentKingFields[coef], attackerField);
                }

                if (attackerY > kingY && attackerX < kingX)
                {
                    path = ExploreSouthEast(board, board.CurrentKingFields[coef], attackerField);
                }

                if (attackerY < kingY && attackerX < kingX)
                {
                    path = ExploreSouthWest(board, board.CurrentKingFields[coef], attackerField);
                }



                for (int i = 0; i < path.Count; i++)
                {
                    List <Field> fieldDefenders = FieldAttackers(board, path[i], white);
                    if (fieldDefenders.Count > 0)
                    {
                        for (int j = 0; j < fieldDefenders.Count; j++)
                        {
                            //ispituje se validnost poteza od branioca do polja na putu path
                            Move defendingMove = new Move(fieldDefenders[j], path[i]);
                            if (Validator.TryMove(board, defendingMove, white, new ConsoleDisplay()))
                            {
                                return(true);
                            }
                        }
                    }
                }
                return(false);
            }
        }
示例#49
0
 public override void OnUpdate(Board board)
 {
 }
示例#50
0
 private GetBoardModel MapBoardToModel(Board addedBoard)
 {
     return(Mapper.Map <GetBoardModel>(addedBoard));
 }
示例#51
0
 public void Setup()
 {
     boardUnderTest = new Board(4, 3);
 }
示例#52
0
        /// <summary>
        /// Minimax with transpositions.
        ///
        /// Example - search depth 5
        /// 5    4   3   2   1
        /// A1 - B - E - F - G: Transposition added for each move
        /// A2 - C - E: Same transposition encountered at depth 3.
        /// -> No need to search deeper
        ///
        /// General guidelines
        /// * Don't save transposition values near the leaf nodes (depth 0, maybe 1)
        ///
        /// Example
        /// maximizing depth 4    alpha = 5, beta = 10
        ///
        /// minimizing depth 3    alpha = 5, beta = 10
        /// minimizing depth 3    value = 12 ok.
        /// minimizing depth 3    value = 8 ok. beta = 8
        /// minimizing depth 3    value = 4 -> prune and save as lowerbound. this move results to 4 or lower. return 4
        ///
        /// maximizing depth 2    alpha = 5, beta = 8
        /// maximizing depth 2    value = 13 -> prune and save as upperbound. this move results to 13 or higher. return 13
        /// maximizing depth 2    value = 6 ok. alpha = 6
        ///
        /// minimizing depth 1    alpha = 6 beta = 8
        /// transposition found: lowerbound, 4
        /// transposition found: upperbound, 13
        ///
        ///
        /// maximizing depth 4 receives 4 - ignored
        /// minimizing depth 3 receives 13 - ignored
        /// </summary>
        public static double ToDepthWithTranspositions(Board newBoard, int depth, double alpha, double beta, bool maximizingPlayer)
        {
            if (depth == 0)
            {
                return(newBoard.Evaluate(maximizingPlayer, false, false, depth));
            }

            // Check if solution already exists
            var transposition = newBoard.Shared.Transpositions.GetTranspositionForBoard(newBoard.BoardHash);

            if (transposition != null && transposition.Depth >= depth)
            {
                Diagnostics.IncrementTranspositionsFound();
                var transpositionEval = MoveResearch.CheckMateScoreAdjustToDepthFixed(transposition.Evaluation, depth);

                if (transposition.Type == NodeType.Exact)
                {
                    return(transpositionEval);
                }
                else if (transposition.Type == NodeType.UpperBound && transpositionEval < beta)
                {
                    beta = transpositionEval;
                }
                else if (transposition.Type == NodeType.LowerBound && transpositionEval > alpha)
                {
                    alpha = transpositionEval;
                }
                //else if (transposition.Type == NodeType.UpperBound && !maximizingPlayer && transposition.Evaluation <= alpha)
                //{
                //    // No need to search further, as score was worse than alpha
                //    return transposition.Evaluation;
                //}
                //else if (transposition.Type == NodeType.LowerBound && maximizingPlayer && transposition.Evaluation >= beta)
                //{
                //    // No need to search further, as score was worse than beta
                //    return transposition.Evaluation;
                //}
            }

            var allMoves = newBoard.Moves(maximizingPlayer, false);

            if (!allMoves.Any())
            {
                return(newBoard.Evaluate(maximizingPlayer, false, newBoard.IsCheck(!maximizingPlayer), depth));
            }

            if (maximizingPlayer)
            {
                var value = MoveResearch.DefaultAlpha;
                foreach (var move in allMoves)
                {
                    var nextBoard = new Board(newBoard, move);
                    value = ToDepthWithTranspositions(nextBoard, depth - 1, alpha, beta, false);
                    if (value >= beta)
                    {
                        // Eval is at least beta. Fail high
                        // Prune. Alpha is better than previous level beta. Don't want to use moves from this board set.

                        if (depth > 1)
                        {
                            nextBoard.Shared.Transpositions.Add(nextBoard.BoardHash, depth, value,
                                                                NodeType.LowerBound, nextBoard.Shared.GameTurnCount);
                        }
                        Diagnostics.IncrementBeta();
                        break;
                    }
                    else if (value > alpha)
                    {
                        // Value between alpha and beta. Save as exact score
                        // Update alpha for rest of iteration
                        alpha = value;
                        if (depth > 1)
                        {
                            nextBoard.Shared.Transpositions.Add(nextBoard.BoardHash, depth, value, NodeType.Exact, nextBoard.Shared.GameTurnCount);
                        }
                    }
                }
                return(value);
            }
            else
            {
                var value = MoveResearch.DefaultBeta;
                foreach (var move in allMoves)
                {
                    var nextBoard = new Board(newBoard, move);
                    value = ToDepthWithTranspositions(nextBoard, depth - 1, alpha, beta, true);
                    if (value <= alpha)
                    {
                        // Eval is at most alpha. Fail low
                        // Prune. Beta is smaller than previous level alpha. Don't want to use moves from this board set.

                        if (depth > 1)
                        {
                            nextBoard.Shared.Transpositions.Add(nextBoard.BoardHash, depth, value,
                                                                NodeType.UpperBound, nextBoard.Shared.GameTurnCount);
                        }
                        Diagnostics.IncrementAlpha();
                        break;
                    }
                    else if (value < beta)
                    {
                        // Value between alpha and beta. Save as exact score
                        // Update beta for rest of iteration
                        beta = value;
                        if (depth > 1)
                        {
                            // Add new transposition table
                            nextBoard.Shared.Transpositions.Add(nextBoard.BoardHash, depth, value, NodeType.Exact, nextBoard.Shared.GameTurnCount);
                        }
                    }
                }
                return(value);
            }
        }
        public void TestOCannotMoveFirst()
        {
            Board board = Board.create();

            Assert.IsFalse(board.move(2, 2, PieceType.PIECEO));
        }
示例#54
0
文件: Player.cs 项目: ganzmn/dotnet
 public Player(string name, Board playerBoard)
 {
     Name        = name;
     PlayerBoard = playerBoard;
 }
示例#55
0
 private void Awake()
 {
     m_board = FindObjectOfType <Board>().GetComponent <Board>();
 }
示例#56
0
 public Rules(Board _board)
 {
     this.board = _board;
 }
示例#57
0
        public static void processDB(string filename)
        {
            try {
                Dictionary <int, Action> inserts        = new Dictionary <int, Action>();
                HashSet <int>            discussionsIds = new HashSet <int>();
                using (StreamReader reader = new StreamReader(filename)) {
                    int i = 0;
                    while (!reader.EndOfStream)
                    {
                        string line = reader.ReadLine().Trim();
                        if (line == "")
                        {
                            continue;
                        }
                        if (i % 1000 == 0)
                        {
                            System.Console.Write("[" + (int)(i / 1000) + "]");
                        }
                        Dictionary <string, string> data;
                        try {
                            data = DictionaryConverter.FromDump(line);
                        } catch (Exception e) {
                            System.Console.Error.WriteLine("Error while trying to parse line: " + e.GetType().FullName + ": " + e.Message);
                            System.Console.Error.WriteLine(e.StackTrace);
                            continue;
                        }
                        int postId = int.Parse(data["Number"]);
                        try {
                            if (inserts.ContainsKey(postId))
                            {
                                System.Console.Write("-");
                            }
                            else if (Config.instance.mainConnection.GetCountByConditions(Post.TableSpec.instance, new ComparisonCondition(Post.TableSpec.instance.getIdSpec(), ComparisonType.EQUAL, postId.ToString())) > 0)
                            {
/*							Post post = Post.LoadById(postId);
 *                                                      if(post.title.StartsWith("%") || post.title.StartsWith("Re%3A") || post.body.StartsWith("%") || (post.thread.firstPost.id == post.id && post.thread.title.StartsWith("%"))) {
 *                                                              string title = data["Subject"];
 *                                                              string body = data["Body"];
 *                                                              inserts[postId] = () => {
 *                                                                      List<AbstractChange> changes = new List<AbstractChange> {
 *                                                                              new UpdateChange(
 *                                                                                      Post.TableSpec.instance,
 *                                                                                      new Dictionary<string, AbstractFieldValue> {
 *                                                                                              { Post.TableSpec.FIELD_TITLE, new ScalarFieldValue(title) },
 *                                                                                              { Post.TableSpec.FIELD_BODY, new ScalarFieldValue(body) },
 *                                                                                      },
 *                                                                                      post.id
 *                                                                              )
 *                                                                      };
 *                                                                      if(post.thread.firstPost.id == post.id) {
 *                                                                              changes.Add(
 *                                                                                      new UpdateChange(
 *                                                                                              Thread.TableSpec.instance,
 *                                                                                              new Dictionary<string, AbstractFieldValue> {
 *                                                                                                      { Thread.TableSpec.FIELD_TITLE, new ScalarFieldValue(title) },
 *                                                                                              },
 *                                                                                              post.thread.id
 *                                                                                      )
 *                                                                              );
 *                                                                      }
 *
 *                                                                      ChangeSetUtil.ApplyChanges(changes.ToArray());
 *                                                              };
 *                                                              Console.Write("+");
 *                                                      } else {
 *                                                              Console.Write("-");
 *                                                      }*/
                                System.Console.Write("-");
                            }
                            else
                            {
                                int localMain = int.Parse(data["Local_Main"]);
                                int main      = int.Parse(data["Main"]);
                                int UnixTime;
                                try {
                                    UnixTime = int.Parse(data["UnixTime"]);
                                } catch (OverflowException) {
                                    UnixTime = 1000 * 1000 * 1000;
                                }
                                if (UnixTime <= 0)
                                {
                                    UnixTime = 1000 * 1000 * 1000;
                                }
                                DateTime date = UNIX.AddSeconds(UnixTime).ToLocalTime();
                                User     user;
                                string   username = data["Username"];
                                try {
                                    user = User.LoadByName(username);
                                } catch (NotFoundInDBException) {
                                    System.Console.Error.WriteLine("Cannot find user '" + username + "'; creating one...");
                                    ChangeSetUtil.ApplyChanges(
                                        new InsertChange(
                                            User.TableSpec.instance,
                                            new Dictionary <string, AbstractFieldValue> {
                                        { User.TableSpec.FIELD_NAME, new ScalarFieldValue(username) },
                                        { User.TableSpec.FIELD_REGDATE, new ScalarFieldValue(date.ToUTCString()) },
                                        { User.TableSpec.FIELD_SHOWPOSTSTOUSERS, new ScalarFieldValue(User.ENUM_SHOWPOSTSTOUSERS_ALL) },
                                        { User.TableSpec.FIELD_BIOGRAPHY, new ScalarFieldValue("") },
                                        { User.TableSpec.FIELD_BIOGRAPHYUBB, new ScalarFieldValue("") },
                                        { User.TableSpec.FIELD_LOCATION, new ScalarFieldValue("") },
                                        { User.TableSpec.FIELD_SIGNATURE, new ScalarFieldValue("") },
                                        { User.TableSpec.FIELD_SIGNATUREUBB, new ScalarFieldValue("") },
                                        { User.TableSpec.FIELD_TITLE, new ScalarFieldValue("") },
                                        { User.TableSpec.FIELD_TOTALPOSTS, new ScalarFieldValue("0") },
                                        { User.TableSpec.FIELD_USERGROUPID, new ScalarFieldValue("1") },
                                    }
                                            )
                                        );
                                    user = User.LoadByName(data["Username"]);
                                }
                                string    title = data["Subject"];
                                string    body  = data["Body"];
                                PostLayer layer = PostLayer.LoadById(1);
                                if (data.ContainsKey("Layer"))
                                {
                                    layer = PostLayer.LoadById(int.Parse(data["Layer"]));
                                }
                                inserts[postId] = () => {
                                    bool isDiscussion = false;
                                    if (postId == main || postId == localMain)
                                    {
                                        //first post in the thread
                                        string legacyBoardName;
                                        if (discussions.ContainsKey(main) || (localMain != 0 && (localMain != postId || localMain != main)))
                                        {
                                            discussionsIds.Add(main);
                                            legacyBoardName = discussions[main];
                                            isDiscussion    = true;
                                        }
                                        else
                                        {
                                            legacyBoardName = data["Board"];
                                        }
                                        Board board;
                                        try {
                                            board = Board.LoadByLegacyName(legacyBoardName);
                                        } catch (NotFoundInDBException) {
                                            throw new ApplicationException("Cannot find board '" + legacyBoardName + "'");
                                        }
                                        board.CreateThread(user, title, body, layer, date, postId);
                                    }
                                    else
                                    {
                                        int parentId = int.Parse(data["Parent"]);
                                        if (parentId == 0)
                                        {
                                            parentId = localMain;
                                            if (parentId == 0)
                                            {
                                                parentId = main;
                                            }
                                        }
                                        Post parent;
                                        try {
                                            parent = Post.LoadById(parentId);
                                        } catch (NotFoundInDBException) {
                                            throw new ApplicationException("Cannot find parent post #" + parentId);
                                        }

                                        if (!isDiscussion && parent.thread.firstPostId != localMain)
                                        {
                                            System.Console.Write("d");
                                        }
                                        else
                                        {
                                            parent.Reply(user, title, body, layer, date, postId);
                                        }
                                    }
                                };
                                System.Console.Write("+");
                            }
                        } catch (Exception e) {
                            System.Console.Error.WriteLine("Cannot process post #" + postId + ": " + e.GetType().FullName + ": " + e.Message);
                            System.Console.Error.WriteLine(e.StackTrace);
                            System.Console.Write("!");
//						Console.ReadLine();
                        } finally {
                            i++;
                            if ((i % 50000) == 0)
                            {
                                Web.Core.RegistryCleaner.CleanRegistry <int, Post>();
                                Web.Core.RegistryCleaner.CleanRegistry <int, Thread>();
                                GC.Collect();
                                System.Console.Error.WriteLine();
                                System.Console.Error.WriteLine("Registry cleaned; garbage collected");
                                System.Console.Error.WriteLine();
                            }
                        }
                    }
                }

                System.Console.WriteLine();
                System.Console.WriteLine("Finished parsing");
                System.Console.WriteLine("Total inserts: " + inserts.Count);
                System.Console.ReadLine();
                int j = 0;
                foreach (var insert in inserts)
                {
                    if (j % 1000 == 0)
                    {
                        System.Console.Write("[" + (int)(j / 1000) + "]");
                    }
                    try {
                        insert.Value();
                        System.Console.Write("+");
                    } catch (Exception e) {
                        System.Console.Error.WriteLine("Cannot process post #" + insert.Key + ": " + e.GetType().FullName + ": " + e.Message);
                        System.Console.Error.WriteLine(e.StackTrace);
                        System.Console.Write("!");
//						Console.ReadLine();
                    } finally {
                        j++;
                    }
                }

                System.Console.WriteLine("Not found discussions:");
                foreach (int discussionId in discussionsIds.OrderBy(id => id))
                {
                    System.Console.WriteLine(discussionId);
                }
            } catch (Exception e) {
                System.Console.Error.WriteLine(e.GetType().FullName + ": " + e.Message);
                System.Console.Error.WriteLine(e.StackTrace);
            }
        }
        public void TestXMovesFirst()
        {
            Board board = Board.create();

            Assert.IsTrue(board.move(2, 2, PieceType.PIECEX));
        }
示例#59
0
        public bool Initialize(out Board map, string filename = null)
        {
            var    currentAssembly = Assembly.GetExecutingAssembly();
            Stream stream          = null;

            if (filename == null)
            {
                stream = currentAssembly.GetManifestResourceStream("Fire_Emblem_Empires.Data.Chapter1T1.txt");
            }
            else
            {
                ResourceSet  reader = new ResourceSet("MapFiles.resources");
                string       data   = reader.GetString(filename);
                MemoryStream mem    = new MemoryStream();
                StreamWriter temp   = new StreamWriter(mem);
                temp.Write(data);
                temp.Flush();
                mem.Position = 0;
                stream       = mem;
            }
            mapFile = new StreamReader(stream);

            string mapSizeRegex = @"^([0-9]*)[X]([0-9]*)\s?$";

            mapSize = mapFile.ReadLine();

            map = new Board(0, 0);
            Match mapDimensions = Regex.Match(mapSize, mapSizeRegex);

            int numRows    = 0;
            int numColumns = 0;

            if (!int.TryParse(mapDimensions.Groups[1].ToString(), out numRows))
            {
                Console.WriteLine("The Row Format did not contain a number.");
                return(false);
            }
            if (!int.TryParse(mapDimensions.Groups[2].ToString(), out numColumns))
            {
                Console.WriteLine("The Column Format did not contain a number.");
                return(false);
            }

            map      = new Board((byte)numRows, (byte)numColumns);
            map.name = "Chapter1";

            regexString = string.Format("^([A-{0}][0-9]+)\\s([0-4])\\s?(.*)$", (char)('A' + numRows));

            string tileLocation = string.Format("([A-{0}])([0-9]*)", (char)('A' + numRows));

            string line;

            while ((line = mapFile.ReadLine()) != null)
            {
                Match  commentless         = Regex.Match(line, @"([^\/]*)\s?(\/\/.*)?");
                string lineWithoutComments = commentless.Groups[1].ToString();
                Match  tileInformation     = Regex.Match(lineWithoutComments, regexString);
                string index        = tileInformation.Groups[1].ToString();
                Match  locationInfo = Regex.Match(index, tileLocation);
                // sets row with 0 base index
                int row = locationInfo.Groups[1].ToString()[0] - 'A';
                // sets column with 0 base index
                int column;
                if (int.TryParse(locationInfo.Groups[2].ToString(), out column))
                {
                    column -= 1;
                }
                else
                {
                    Console.WriteLine("Unable to convert {0} from {1} to int.", locationInfo.Groups[0].ToString(), locationInfo.Groups[2].ToString());
                    return(false);
                }
                int terrain;
                int.TryParse(tileInformation.Groups[2].ToString(), out terrain);
                // will be empty string if no unit on tile
                string unitInfo = tileInformation.Groups[3].ToString();
                Unit   unit     = null;
                if (unitInfo != "")
                {
                    Match unitInformation = Regex.Match(unitInfo, unitRegex);
                    int   unitTeam;
                    int.TryParse(unitInformation.Groups[1].ToString(), out unitTeam);
                    int unitJob;
                    int.TryParse(unitInformation.Groups[2].ToString(), out unitJob);
                    if (unitInformation.Groups[3].ToString() == "R")
                    {
                        unit = CreateUnitWithJob((Team)unitTeam, unitJob);
                    }
                    else
                    {
                        string[] statsInfo = Regex.Split(unitInformation.Groups[4].ToString(), @"\D+");
                        byte     maxHealth;
                        byte.TryParse(statsInfo[0], out maxHealth);
                        byte currentHealth;
                        byte.TryParse(statsInfo[1], out currentHealth);
                        byte attack;
                        byte.TryParse(statsInfo[2], out attack);
                        byte speed;
                        byte.TryParse(statsInfo[3], out speed);
                        byte defense;
                        byte.TryParse(statsInfo[4], out defense);
                        byte resistance;
                        byte.TryParse(statsInfo[5], out resistance);
                        int canMove;
                        int.TryParse(statsInfo[6], out canMove);
                        unit = CreateUnitWithJob((Team)unitTeam, unitJob, maxHealth, currentHealth, attack, speed, defense, resistance, canMove == 0);
                    }
                }
                map.SetSpace(new Location((byte)row, (byte)column), new Tile((TileEnumeration)terrain, unit));
            }
            return(true);
        }
示例#60
0
        static void Main(string[] args)
        {
            // variables
            sbyte ownSide;
            Board board = new Board();
            Stack <BoardState> undoStack = new Stack <BoardState>();

            UInt16 move;
            Tuple <UInt16, int, long, int> moveDepthTimeAndScore;

            string userMove, filthyMindMove = "INVALID_MOVE";

            File.Delete(LogFileName);
            string guiMessage = Console.ReadLine();

            File.AppendAllText(LogFileName, "\nGUI: " + guiMessage + Environment.NewLine);

            Console.WriteLine("id name Shutranj");
            Console.WriteLine("id author Okash Khawaja");
            Console.WriteLine("uciok");

            guiMessage = Console.ReadLine();
            File.AppendAllText(LogFileName, "GUI: " + guiMessage + Environment.NewLine);

            Console.WriteLine("readyok");

            guiMessage = Console.ReadLine();
            File.AppendAllText(LogFileName, "GUI: " + guiMessage + Environment.NewLine);

            guiMessage = Console.ReadLine();
            File.AppendAllText(LogFileName, "GUI: " + guiMessage + Environment.NewLine);

            guiMessage = Console.ReadLine();
            File.AppendAllText(LogFileName, "GUI: " + guiMessage + Environment.NewLine);

            /********** this is when the game begins **************/

            guiMessage = Console.ReadLine();
            File.AppendAllText(LogFileName, "GUI: " + guiMessage + Environment.NewLine);

            if (guiMessage == "quit" || guiMessage == "stop")
            {
                return;
            }
            userMove = ParseOutLastMove(guiMessage);

            guiMessage = Console.ReadLine();
            File.AppendAllText(LogFileName, "GUI: " + guiMessage + Environment.NewLine);

            // if empty then engine is playing white so make move first
            if (String.IsNullOrWhiteSpace(userMove))
            {
                ownSide = Side.White;

                moveDepthTimeAndScore = AlphaBeta2.IDASParallel(board, ownSide);

                move = moveDepthTimeAndScore.Item1;
                if (board.MakeMove(move))
                {
                    filthyMindMove = board.ConvertToAlgebraicNotation(move);
                    File.AppendAllText(LogFileName, String.Format(
                                           "Filthy Mind: {0} (Depth: {1} plies; Time: {2}ms; Score: {3}){4}", filthyMindMove,
                                           moveDepthTimeAndScore.Item2, moveDepthTimeAndScore.Item3, moveDepthTimeAndScore.Item4, Environment.NewLine));
                }

                // communicate move back to gui
                Console.WriteLine(BestMoveStringFormat, filthyMindMove);
            }
            else
            {
                ownSide = Side.Black;
            }



            while (true)
            {
                guiMessage = Console.ReadLine();
                File.AppendAllText(LogFileName, "GUI: " + guiMessage + Environment.NewLine);

                if (guiMessage == "quit" || guiMessage == "stop")
                {
                    break;
                }
                userMove = ParseOutLastMove(guiMessage);

                guiMessage = Console.ReadLine();
                File.AppendAllText(LogFileName, "GUI: " + guiMessage + Environment.NewLine);

                board.MakeUserMove(userMove);

                moveDepthTimeAndScore = AlphaBeta2.IDASParallel(board, ownSide);

                move = moveDepthTimeAndScore.Item1;
                if (board.MakeMove(move))
                {
                    filthyMindMove = board.ConvertToAlgebraicNotation(move);
                    File.AppendAllText(LogFileName, String.Format(
                                           "Filthy Mind: {0} (Depth: {1} plies; Time: {2}ms; Score: {3}){4}", filthyMindMove,
                                           moveDepthTimeAndScore.Item2, moveDepthTimeAndScore.Item3, moveDepthTimeAndScore.Item4, Environment.NewLine));
                }

                // communicate move back to gui
                Console.WriteLine(BestMoveStringFormat, filthyMindMove);
            }
        }