Exemple #1
0
        public IEnumerator WaitForNextMove()
        {
            // Enable the board
            SetEnabled(true);

            while (true)
            {
                for (int i = 0; i < Rows.Length; i++)
                {
                    // Query the row for the next move on it
                    StartCoroutine(Rows[i].GetNextMove());

                    // On the first row that gets clicked
                    if (Rows[i].ColumnClicked != -1)
                    {
                        // Get the move that was requested
                        LatestPlayerMove = new TicTacToeMove
                        {
                            row = i,
                            col = Rows[i].ColumnClicked
                        };

                        // Reset the row
                        Rows[i].ColumnClicked = -1;

                        // Disable the board
                        SetEnabled(false);
                        yield break;
                    }
                }

                yield return(null);
            }
        }
Exemple #2
0
        public TicTacToeMove GetAndResetMove()
        {
            var move = LatestPlayerMove;

            LatestPlayerMove = null;
            return(move);
        }
Exemple #3
0
 internal void Apply(TicTacToeMove move)
 {
     Squares[move.Index] = move.PlayerSymbol;
     CheckForEndConditions(move.PlayerSymbol);
     lastMoveTaken = _getTime();
     StateChanged(this, EventArgs.Empty);
 }
        /// <summary>
        /// Simulate AI player by performing a random move.
        /// </summary>
        private void AIPlay()
        {
            // Generate a random move
            TicTacToeMove move = new TicTacToeMove()
            {
                X      = random.Next(0, rowCount),
                Y      = random.Next(0, columnCount),
                Player = ConstData.OString
            };

            // Try generating another move if the first one was not legal
            while (!IsLegalMove(move))
            {
                move = new TicTacToeMove()
                {
                    X      = random.Next(0, rowCount),
                    Y      = random.Next(0, columnCount),
                    Player = ConstData.OString
                };
            }

            // Send the move to the server
            currentMove = move;
            try
            {
                proxy.GameStepAsync(playerID, currentMove.X, currentMove.Y, currentMove.Player);
                state = TicTacToeState.WaitingForService;
            }
            catch (Exception)
            {
                state = TicTacToeState.ServiceNotAvailable;
            }
        }
Exemple #5
0
        private GameState AddMoveToGameState(string playerId, TicTacToeMove move, GameState gameState, Match match)
        {
            var occupantPlayer     = playerId == match.playerOneId ? OccupantType.PLAYER_ONE : OccupantType.PLAYER_TWO;
            var playerMovePosition = move.row * 3 + move.col;

            if (gameState.boardState[playerMovePosition] != (int)OccupantType.NONE)
            {
                return(null);
            }

            gameState.boardState[playerMovePosition] = (int)occupantPlayer;

            // Pass the turn to the other player
            switch (occupantPlayer)
            {
            case OccupantType.PLAYER_ONE:
                gameState.currentPlayerId = match.playerTwoId;
                break;

            case OccupantType.PLAYER_TWO:
                gameState.currentPlayerId = match.playerOneId;
                break;
            }

            gameState.winner = (int)GetCurrentGameResult(gameState).winner;

            return(gameState);
        }
        /// <summary>
        /// Occurs when the "new game" button clicked.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void newGameButton_Click(object sender, EventArgs e)
        {
            if (state == TicTacToeState.GameOver)
            {
                // Instruct the server to restart the game
                try
                {
                    proxy.RestartGameAsync(playerID);

                    // Reset the local variables
                    moves       = new List <TicTacToeMove>();
                    currentMove = null;
                    if (random.Next(0, 10) > 5)
                    {
                        state = TicTacToeState.PlayerTurn;
                    }
                    else
                    {
                        state = TicTacToeState.AITurn;
                    }
                    text = MakeYourStepText;
                }
                catch (Exception)
                {
                    state = TicTacToeState.ServiceNotAvailable;
                }
            }
        }
        //
        protected TicTacToeMove GetMoveForPlayer(Player p)
        {
            lastMove = null;

            playerThread = new Thread(p.Move);
            playerThread.Start(game.GameBoard);


            // register a listener
            p.PlayerMoved += new PlayerMovedHandler(player_PlayerMoved);

            // lastMove is assigned in the player_PlayerMoved handler
            while (lastMove == null)
            {
                ;
            }

            // if we get here the player moved

            // unregister the listenter
            p.PlayerMoved -= player_PlayerMoved;


            // kill the thread
            playerThread.Abort();

            return(p.CurrentMove);
        }
 /// <summary>
 /// Constructs a new PlayerMovedArgs object with the specified Move and Player
 /// </summary>
 /// <param name="m">The move to make</param>
 /// <param name="player">The player making the move</param>
 public PlayerMovedArgs(TicTacToeMove m, Player player)
     : base()
 {
     this.player = player;
     move = m;
     
 }
Exemple #9
0
        // when a user double clicks a square on the TicTacToeForm this method receives the
        // event message
        // the current move is set and the alreadyMoved flag is set to true so that the
        // which breaks the while loop in the Move method
        void SquareDoubleClicked(object sender, TicTacToeBoardClickedEventArgs args)
        {
            // unregister the double clicked event
            ticTacToeForm.SquareDoubleClicked -= SquareDoubleClicked;

            currentMove  = new TicTacToeMove(args.BoardPosition, this.PlayerPiece);
            alreadyMoved = true;
        }
Exemple #10
0
        /// <summary>
        /// Undoes the last move
        /// </summary>
        public void UndoLastMove()
        {
            TicTacToeMove lastMove = moves.Pop();

            board.UndoMove(lastMove);

            SwapTurns();
        }
		// when a user double clicks a square on the TicTacToeForm this method receives the 
		// event message
		// the current move is set and the alreadyMoved flag is set to true so that the 
		// which breaks the while loop in the Move method
		void SquareClicked(object sender, TicTacToeBoardClickedEventArgs args)
		{
			// unregister the double clicked event
			//HACK:            ticTacToeForm.SquareDoubleClicked -= SquareDoubleClicked;

			currentMove = new TicTacToeMove(args.BoardPosition, this.PlayerPiece);
			alreadyMoved = true;
		}
 /// <summary>
 /// Constructs a new Node
 /// </summary>
 /// <param name="b">The board that the Node will use to evaluate itself and generate its children</param>
 /// <param name="parent">The parent of this node</param>
 /// <param name="move">The move from the parent's board that generated this node's board</param>
 public Node(Board b, Node parent, TicTacToeMove move)
 {
     this.board = b;
     this.parent = parent;
     this.move = move;
     if (parent != null)
         myPiece = Board.GetOponentPiece(parent.MyPiece);
     children = new List<Node>();
 }
Exemple #13
0
 /// <summary>
 /// Constructs a new Node
 /// </summary>
 /// <param name="b">The board that the Node will use to evaluate itself and generate its children</param>
 /// <param name="parent">The parent of this node</param>
 /// <param name="move">The move from the parent's board that generated this node's board</param>
 public Node(Board b, Node parent, TicTacToeMove move)
 {
     this.board  = b;
     this.parent = parent;
     this.move   = move;
     if (parent != null)
     {
         myPiece = Board.GetOponentPiece(parent.MyPiece);
     }
     children = new List <Node>();
 }
Exemple #14
0
        // gets a random move.  this can be used to make game play interesting
        // particularly in the beginning of the game or if you wish to weaken the computer's
        // play by adding randomness.
        protected TicTacToeMove GetRandomMove(Board b)
        {
            int    openPositions = b.OpenPositions.Length;
            Random rGen          = new Random();

            int squareToMoveTo = rGen.Next(openPositions);

            TicTacToeMove move = new TicTacToeMove(squareToMoveTo, this.PlayerPiece);

            return(move);
        }
Exemple #15
0
        public void UndoMove(TicTacToeMove m)
        {
            if (!IsOnBoard(m.Position))
            {
                throw new InvalidMoveException("Can't undo a move on an invalid square!");
            }

            // just reset the position
            Point p = GetPoint(m.Position);

            board[p.X, p.Y] = 0;
        }
Exemple #16
0
 private void HandleNewLocalMove(TicTacToeMove move)
 {
     if (ApplicationModel.IsHost)
     {
         var newGameState = AddMoveToGameState(ApplicationModel.CurrentPlayer.Entity.Id, move, ApplicationModel.CurrentGameState, ApplicationModel.CurrentMatch);
         gameStateHandler.SendGameState(newGameState);
     }
     else
     {
         gameStateHandler.SendMove(move);
     }
 }
Exemple #17
0
        /// <summary>
        /// Check if a move is legal.
        /// </summary>
        /// <param name="move">Move to validate.</param>
        /// <returns>True if the move is legal and false otherwise.</returns>
        private bool IsLegalMove(TicTacToeMove move)
        {
            for (int i = 0; i < moves.Count; i++)
            {
                // Check if the square is occupied
                if (move.X == moves[i].X && move.Y == moves[i].Y)
                {
                    return(false);
                }
            }

            return(true);
        }
Exemple #18
0
        private void HandleOnMoveReceived(string playerId, TicTacToeMove move)
        {
            var gameState = AddMoveToGameState(playerId, move, ApplicationModel.CurrentGameState, ApplicationModel.CurrentMatch);

            if (gameState == null)
            {
                Debug.LogError($"Invalid move received from the player {playerId}");
                return;
            }

            ApplicationModel.CurrentGameState = gameState;
            gameStateHandler.SendGameState(gameState);
            ApplicationModel.NewTurnToUpdate = true;
        }
Exemple #19
0
        // Generate Children.  MAX Nodes have MIN children
        protected override void GenerateChildren()
        {
            // create child nodes for each of the availble positions
            int[] openPositions = board.OpenPositions;

            foreach (int i in openPositions)
            {
                Board         b = (Board)board.Clone();
                TicTacToeMove m = new TicTacToeMove(i, myPiece);

                b.MakeMove(i, myPiece);
                children.Add(new MinNode(b, this, m));
            }
        }
Exemple #20
0
        /// <summary>
        /// Makes the move for the specified player
        /// </summary>
        /// <param name="m">The move to make</param>
        /// <param name="p">The player making the move</param>
        public void MakeMove(TicTacToeMove m, Players p)
        {
            if (currentTurn != p)
            {
                throw new InvalidMoveException("You went out of turn!");
            }

            if (!board.IsValidSquare(m.Position))
            {
                throw new InvalidMoveException("Pick a square on the board!");
            }

            board.MakeMove(m.Position, m.Piece);

            moves.Push(m);

            SwapTurns();
        }
Exemple #21
0
        private IEnumerator UpdateGameAtNewTurn()
        {
            ApplicationModel.NewTurnToUpdate = false;
            Board.RenderBoard(ApplicationModel.CurrentGameState.boardState);

            var currentGameResult = (GameWinnerType)ApplicationModel.CurrentGameState.winner;

            if (currentGameResult != GameWinnerType.NONE)
            {
                UpdateUIWithGameResult(currentGameResult);
                yield return(null);
            }

            if (ApplicationModel.IsMyTurn)
            {
                TicTacToeMove nextMove = null;
                yield return(CoroutineHelper.Run <TicTacToeMove>(WaitAndGetNextMove(), (move) => { nextMove = move; }));

                HandleNewLocalMove(nextMove);
                ApplicationModel.NewTurnToUpdate = ApplicationModel.IsHost;
            }
        }
Exemple #22
0
        /// <summary>
        /// Select a move to designate as the current move by the position of the user's tap.
        /// </summary>
        /// <param name="touchBounds">Rectangle representing the user's touch input location.</param>
        private void HandlePickMoveInput(Rectangle touchBounds)
        {
            // Get the square that was tapped
            Point?square = GetIntersectedSquare(touchBounds);

            if (square.HasValue)
            {
                // Create a move for the square that was tapped
                TicTacToeMove move = new TicTacToeMove()
                {
                    Player = ConstData.XString,
                    X      = square.Value.X,
                    Y      = square.Value.Y
                };

                // If the move is legal then set it as the current move
                if (IsLegalMove(move))
                {
                    currentMove = move;
                }
            }
        }
        // Gets each players move applies it to the game board
        private void ProcessPlayerMoves()
        {
            while (!game.IsGameOver())
            {
                for (int i = 0; i < players.Count; i++)
                {
                    Player p = players[i];

                    TicTacToeMove playerMove = GetMoveForPlayer(p);

                    game.MakeMove(new TicTacToeMove(playerMove.Position, p.PlayerPiece));

                    // update the graphics
                    this.ticTacToePanel.Invalidate();


                    if (IsGameOver())
                    {
                        ShowEndOfGameMessage(players[i]);
                        FinishGame();
                    }
                }
            }
        }
        public void UndoMove(TicTacToeMove m)
        {

            
            if (!IsOnBoard(m.Position))
                throw new InvalidMoveException("Can't undo a move on an invalid square!");

            // just reset the position
            Point p = GetPoint(m.Position);
            board[p.X, p.Y] = 0;
        }
 /// <summary>
 /// Constructs a MIN node
 /// </summary>
 /// <param name="b">The board that this node represents</param>
 /// <param name="parent">This node's parent</param>
 /// <param name="m">The move that was made from the parent to lead to this node's board</param>
 public MinNode(Board b, Node parent, TicTacToeMove m)
     :base(b, parent, m)
 {
     
 }
 private void player_PlayerMoved(object sender, PlayerMovedArgs args)
 {
     lastMove = args.Move;
 }
        // Generates the node's children.  MIN nodes have MAX children
        protected override void GenerateChildren()
        {
            int[] openPositions = board.OpenPositions;



            foreach (int i in openPositions)
            {
                Board b = (Board)board.Clone();
                TicTacToeMove m = new TicTacToeMove(i, myPiece);

                b.MakeMove(i, myPiece);
                children.Add(new MaxNode(b, this, m));

            }
            
        }
Exemple #28
0
 /// <summary>
 /// Constructs a MIN node
 /// </summary>
 /// <param name="b">The board that this node represents</param>
 /// <param name="parent">This node's parent</param>
 /// <param name="m">The move that was made from the parent to lead to this node's board</param>
 public MinNode(Board b, Node parent, TicTacToeMove m)
     : base(b, parent, m)
 {
 }
Exemple #29
0
 /// <summary>
 /// Constructs a new PlayerMovedArgs object with the specified Move and Player
 /// </summary>
 /// <param name="m">The move to make</param>
 /// <param name="player">The player making the move</param>
 public PlayerMovedArgs(TicTacToeMove m, Player player)
     : base()
 {
     this.player = player;
     move        = m;
 }
		// gets a random move.  this can be used to make game play interesting
		// particularly in the beginning of the game or if you wish to weaken the computer's
		// play by adding randomness.
		protected TicTacToeMove GetRandomMove(Board b)
		{
			int openPositions = b.OpenPositions.Length;
			Random rGen = new Random();

			int squareToMoveTo = rGen.Next(openPositions);

			TicTacToeMove move = new TicTacToeMove(squareToMoveTo, this.PlayerPiece);
			return move;
		}
		protected TicTacToeMove GetMoveForPlayer(Player p)
		{
			lastMove = null;

//			playerThread = new Thread(p.Move);
//			playerThread.Start(game.GameBoard);

//			if (!xturn) { // computer
				p.Move (game.GameBoard);
				// make the change on the board
				lastMove = p.CurrentMove;	
				var row = lastMove.Position / 3;
				var col = lastMove.Position - (row * 3);
				var square = squares [row, col];
				square.Text = xturn ? "X" : "O";
//			}

			// register a listener
//			p.PlayerMoved += new PlayerMovedHandler(player_PlayerMoved);
//
//
//			p.Move (game.GameBoard); // computer only
//
//
//			// lastMove is assigned in the player_PlayerMoved handler
//			while (lastMove == null)
//				;
//
//			// if we get here the player moved
//
//			// unregister the listenter
//			p.PlayerMoved -= player_PlayerMoved;

			// kill the thread
			//playerThread.Abort();

			return p.CurrentMove;

		}
		void player_PlayerMoved(object sender, PlayerMovedArgs args)
		{
			lastMove = args.Move;
		}
		async Task DoTurn(int tappedRow, int tappedCol, uint length = 100)
		{
			var square = squares [tappedRow, tappedCol];
			var position = (tappedRow * 3) + (tappedCol);

			if (game.IsGameOver ()) {
				// game already over, no clicks allowed
			} else {
				if (!String.IsNullOrWhiteSpace (square.Text)) {
					// position already used
				} else {
					square.Text = xturn ? "X" : "O";

					var piece = xturn ? Board.Pieces.X : Board.Pieces.O;

					TicTacToeMove playerMove;
					if (Oturn) {
						// O turn
						playerMove = GetMoveForPlayer(players[1]); // computer
					} else {
						// X turn
						playerMove = new TicTacToeMove (position, piece);
						game.MakeMove (playerMove);
						playerMove = GetMoveForPlayer(players[1]); // computer
					}
					game.MakeMove (playerMove);

					System.Diagnostics.Debug.WriteLine ("Over: " + game.IsGameOver ());

					if (game.IsGameOver ()) {
						if (game.GameBoard.IsDraw())
							await DisplayAlert ("Game Drawn", "There was no winner", "OK", null);
						else
							await DisplayAlert ("Game Over", square.Text + " won", "OK", null);
					}

					xturn = !xturn;
				}
			}
		}
Exemple #34
0
 /// <summary>
 /// Makes the specified move
 /// </summary>
 /// <param name="m">The TicTacToe move to be made</param>
 ///
 public void MakeMove(TicTacToeMove m)
 {
     MakeMove(m, GetPlayerWhoHasPiece(m.Piece));
 }
        /// <summary>
        /// Makes the move for the specified player
        /// </summary>
        /// <param name="m">The move to make</param>
        /// <param name="p">The player making the move</param>
        public void MakeMove(TicTacToeMove m, Players p)
        {

            if (currentTurn != p)
            {
                throw new InvalidMoveException("You went out of turn!");
            }

            if (!board.IsValidSquare(m.Position))
                throw new InvalidMoveException("Pick a square on the board!");

            board.MakeMove(m.Position, m.Piece);

            moves.Push(m);

            SwapTurns();

        }
Exemple #36
0
 /// <summary>
 /// Handle a message describing a move performed.
 /// </summary>
 /// <param name="ticTacToeMove">A move that was performed.</param>
 private void NewMove(TicTacToeMove ticTacToeMove)
 {
     moves.Add(ticTacToeMove);
     currentMove = null;
     ConvertServerStateToClientState(ticTacToeMove.GameFlow);
 }
 /// <summary>
 /// Makes the specified move
 /// </summary>
 /// <param name="m">The TicTacToe move to be made</param>
 /// 
 public void MakeMove(TicTacToeMove m)
 {
     MakeMove(m, GetPlayerWhoHasPiece(m.Piece));
 }