Exemplo n.º 1
0
		public void playTurnTest ()
		{
			string errMsg;
			int boardSize = 3;
			Player player1;
			Player[][] player;
			Board boardTEST;
			//L'objet PrivateObject permet d'acceder aux methodes et attributs
			//normalement prives de l'objet clone

			player1 = new Player("Bob", "O");
			boardTEST = new Board(boardSize);

			for (int i = 1; i <= 9;i++ )
			{
				boardTEST.playTurn(i, player1);
				player = boardTEST.BoardState;
				var length = player.GetLength (0);
				errMsg = "Erreur : playTurn n'a pas fonctionné sur la cellule "+i;
				if (i % length == 0){
					Assert.IsTrue(Board.Equals(player[i/length-1][length-1],player1),errMsg);
				} 
				else {
					Assert.IsTrue(Board.Equals(player[(int)Math.Truncate((double)(i / length))][i % length - 1],player1), errMsg);
				}
			}

		}
Exemplo n.º 2
0
		public Board (int size = 3)
		{
			_board_state = new Player[size][];
			for (int i = 0; i<size;i++) {
				_board_state[i] = new Player[size];
			}
		}
Exemplo n.º 3
0
        public bool changeField(int no)
        {
            if (board[no / 3, no % 3] == 0)
            {
                board[no / 3, no % 3] = currentPlayer.getNumber();

                if (isAwin(currentPlayer.getNumber()))
                {
                    return true;
                }
                else
                {
                    if (currentPlayer == player1)
                    {
                        currentPlayer = player2;
                    }
                    else
                    {
                        currentPlayer = player1;
                    }
                    return false;
                }

            }
            else
            {
                return false;
            }
        }
Exemplo n.º 4
0
 public void AskForPlayersMove(Player pl, Board gameBoard)
 {
     int gameBoardSize = gameBoard.GetBoardSize();
     ConsoleKeyInfo input ;
     do
     {
         Console.WriteLine(pl.GetPlayerName() + " it is your turn.  ");
         Console.Write("Move the cursor with the arrow keys \nand confirm the selection with spacebar");
         input = Console.ReadKey();
         if (input.Key == ConsoleKey.UpArrow)
         {
             selectedRow = selectedRow - 1;
         }
         if (input.Key == ConsoleKey.DownArrow)
         {
             selectedRow = selectedRow + 1;
         }
         if (input.Key == ConsoleKey.LeftArrow)
         {
             selectedColumn = selectedColumn - 1;
         }
         if (input.Key == ConsoleKey.RightArrow)
         {
             selectedColumn = selectedColumn + 1;
         }
         selectedRow = CorrectOutOfBounds(selectedRow, gameBoardSize);
         selectedColumn = CorrectOutOfBounds(selectedColumn, gameBoardSize);
         ClearScreen();
         Draw(gameBoard);
     } while (input.Key != ConsoleKey.Spacebar);
 }
Exemplo n.º 5
0
        private static bool MakePlay(Board board, string playerName, string play)
        {
            var player = new Player();

            if (board.Player1.Name.Equals(playerName))
            {
                player = board.Player1;
            }
            else if (board.Player2 == null)
            {
                player.Name = playerName;
                player.WaitingForOpponent = false;
                player.Simbolo = "O";

                board.Player2 = player;
            }
            else if (board.Player2.Name.Equals(playerName))
            {
                player = board.Player2;
            }
            else
            {
                return false; // player not in game
            }

            if (player.WaitingForOpponent) return false;

            int position = -1;
            int.TryParse(play, out position);

            var gameOver = board.Play(player, position);

            return true;
        }
Exemplo n.º 6
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;
     
 }
Exemplo n.º 7
0
 public bool IsVictory(Player currentPlayer)
 {
     bool victory = IsHorizontalWin(currentPlayer.Mark) || IsVerticalWin(currentPlayer.Mark) || IsDiagonalWin(currentPlayer.Mark);
     if (victory)
         currentPlayer.Score++;
     return victory;
 }
Exemplo n.º 8
0
 public void AskForPlayersMove(Player pl, Board gameBoard)
 {
     int gameBoardSize = gameBoard.GetBoardSize();
     selectedColumn = moves[moveCount, 0];
     selectedRow = moves[moveCount, 1];
     moveCount++;
 }
Exemplo n.º 9
0
		protected bool checkLines ()
		{
			var length = _board.BoardState.GetLength (0);
			var board = _board.BoardState;

			Player prevValue;
			var winner = false;

			for (int line = 0; line < length; line++) {
				prevValue = board [0][line];
				for (int column = 0; column < length; column++) {

					if (board [column][line] == prevValue && prevValue != null) {
						winner = true;
					} else {
						winner = false;
						break;
					}
				}
				if (winner == true) {
					_winner = prevValue;
					return true;
				}

			}
			return false;
		}
Exemplo n.º 10
0
        public void PlayGame()
        {
            Initialize();
            int numPlayers = PromptForGameMode();

            if (numPlayers == 0)
            {
                _player1 = CreateComputerPlayer(0);
                _player2 = CreateComputerPlayer(0);
            }
            else if (numPlayers == 1)
            {
                _player1 = PromptToCreatePlayer();
                _player2 = CreateComputerPlayer(1);
            }
            else
            {
                _player1 = PromptToCreatePlayer("X");
                _player2 = PromptToCreatePlayer("O");
            }

            bool playAgain = false;
            do
            {
                _board = new Board();
                playAgain = ProcessTurnsAndAskToPlayAgain();
            } while (playAgain);
        }
Exemplo n.º 11
0
 public static void GameOver(Player p)
 {
     Console.WriteLine (
         (p.Action == Actions.HasWon) ? (p.Name + " has won!")
         : (p.Action == Actions.Tie) ? "Game ended in a tie."
         : "Game ceased"
     );
 }
Exemplo n.º 12
0
 public bool HasWon(Player p)
 {
     bool retval = false;
     foreach (int bits in WinBits) {
         retval |= ((p.Moves & bits) == bits);
     }
     return retval;
 }
Exemplo n.º 13
0
 public Player(Player p, Actions Action = Actions.Play)
 {
     this.Name = p.Name;
     this.Moves = p.Moves;
     this.Sign = p.Sign;
     this.NextMove = p.NextMove;
     this.Action = Action;
 }
Exemplo n.º 14
0
      /// <summary>
      /// Method called when the game passes control to this player
      /// </summary>
      /// <param name="game">Game object that this player belongs to</param>
      public override void PromptForMove(Game game)
      {
         Stopwatch stopwatch = new Stopwatch();
         stopwatch.Start();

         Square bestSquare = null;
         float bestValue = float.MinValue;

         _playerOpponent = game.Players[0];

         if (_playerOpponent == this)
         {
            _playerOpponent = game.Players[1];
         }

         Random rand = new Random();
         int equalSquares = 0;

         foreach (Square square in game.Board.Squares)
         {
            if (square.Owner == null)
            {
               square.Owner = this;
               float curValue = AlphaBetaPrune(game, int.MinValue, int.MaxValue, false);
               square.Owner = null;

               if (bestSquare == null || curValue > bestValue)
               {
                  bestValue = curValue;
                  bestSquare = square;
                  equalSquares = 0;
               }
               else if (curValue == bestValue)
               {
                  equalSquares++;
                  if (rand.Next(0,equalSquares + 1) == 0)
                  {
                     bestValue = curValue;
                     bestSquare = square;
                  }
               }
            }
         }

         int curTurnTime = (int)stopwatch.ElapsedMilliseconds;
         int turnTimeDiff = _minTurnTime - curTurnTime;

         Move move = new Move(this, bestSquare);

         Action playMove = () => game.PlayMove(move);

         int sleepMs = Math.Max(0, turnTimeDiff);

         // Ensure that the AI waits at least the minTurnTime before playing a move,
         // making the AI seem more human-like in that it won't make all of its moves near instantaniously.
         _timer = new Timer(PlayMoveAfterDelayCallback, playMove, sleepMs, Timeout.Infinite);
      }
Exemplo n.º 15
0
        public Game(int size)
        {
            Size = size;

            X = new Player("X");
            O = new Player("O");

            board = new string[Size, Size];
        }
Exemplo n.º 16
0
 public Cell GetSequenceCompletionCellFor(Player player)
 {
     Cell sequenceCompletionStep = null;
     if (this.Cells.Where(c => c.OccupiedBy == player).Count() == 2 && this.Cells.Where(c => c.IsFree).Count() > 0)
     {
         sequenceCompletionStep = this.Cells.Where(c => c.IsFree).SingleOrDefault();
     }
     return sequenceCompletionStep;
 }
Exemplo n.º 17
0
        /// <summary>
        /// Insert a marker at a given position for a given player
        /// </summary>
        /// <param name="player">The player number should be 0 or 1</param>
        /// <param name="position">The position where to place the marker, should be between 0 and 9</param>
        /// <returns>True if a winner was found</returns>
        public bool Play(Player player, int position)
        {
            if (IsGameOver)
                return false;

            PlaceMarker(player, position);

            return CheckWinner();
        }
Exemplo n.º 18
0
 public MainForm()
 {
     InitializeComponent();
     _cellMap = new Dictionary<Point, Button>();
     _computer = new Player() { Icon = "O", Name = "Computer" };
     _human = new Player() { Icon = "X", Name = "Human" };
     InitializeGrid();
     MapGridPoistionToControls();
     StartGame();
 }
Exemplo n.º 19
0
        public Player MakeNextMove(Player player)
        {
            Player p;
            do {
                p = UI.UserInput (player);
                if (p.Action == Actions.Play) {
                    p = FieldIsFree (p) ? MakeMove (p) : new Player (p, Actions.Repeat);
                }
            } while (p.Action == Actions.Repeat);

            return p;
        }
Exemplo n.º 20
0
        public void PlayerName_ValidInputs_CorrectResult()
        {
            //Arrange
            Player expectedName = new Player();
            expectedName.PlayerName = "Player1";

            //Act
            string actualPlayerName = "Player1";

            //Assert
            Assert.IsTrue(actualPlayerName == expectedName.PlayerName);
        }
Exemplo n.º 21
0
        public static Player UserInput(Player p)
        {
            int nextMove = 0;
            Actions action;

            Console.Write (p.Name + ": ");
            string input = Console.ReadLine ().ToLower ();
            action = input == "neu" ? Actions.New :
                     input == "ende" ? Actions.End :
                     (nextMove = Translate (input)) == 0 ? Actions.Repeat : Actions.Play;
            return new Player (p, nextMove, action);
        }
Exemplo n.º 22
0
        public void TestSetAndGetPlayerName_ValidInputs_CorrectResult()
        {
            //Arrange
            Player TestPlayer = new Player();
            string expectedPlayerName = "Mr.Big";

            //Act
            TestPlayer.SetPlayerName("Mr.Big",1);
            string actualPlayerName = TestPlayer.GetPlayerName();

            //Assert
            Assert.IsTrue(actualPlayerName == expectedPlayerName);
        }
Exemplo n.º 23
0
		public static bool Equals(Player p1,Player p2)
		{
			if (p1== null && p2 == null) {
				return true;
			} else if ((p1 == null && p2 != null) || (p1 != null && p2 == null)) {
				return false;
			} else {
				bool name = p1.Name == p2.Name;
				bool symbol = p1.Symbol == p2.Symbol;
				bool number_win = p1.NumberWin == p2.NumberWin;
				return (name && symbol && number_win);
			}
		}
Exemplo n.º 24
0
        public void TestSetPlayerNameWithEmptyString()
        {
            //Arrange
            Player TestPlayer = new Player();
            string expectedPlayerName = "Player 1";

            //Act
            TestPlayer.SetPlayerName("", 1);
            string actualPlayerName = TestPlayer.GetPlayerName();

            //Assert
            Assert.AreEqual(actualPlayerName, expectedPlayerName);
        }
Exemplo n.º 25
0
        private int[] minimax(int depth, Player p)
        {
            // Generate all possible moves in a List of arrays
            List<int[]> availableMoves = generateMoves();
            // player is maximizing, enemy is minimizing
            int bestScore = p == player ? int.MinValue : int.MaxValue;
            int currentScore;
            int bestRow = -1;
            int bestCol = -1;
            // if there are no more available moves, evaluate score
            if (availableMoves.Count == 0)
            {
                bestScore = evaluateScore(depth);
            }
            else
            {
                foreach (int[] move in availableMoves)
                {
                    // test this move
                    node[move[0], move[1]].content = p;

                    if (p == player)
                    {
                        // calculate the minimax at this node of the enemy
                        currentScore = minimax(depth + 1, enemy)[0];
                        if (currentScore > bestScore)
                        {
                            bestScore = currentScore;
                            bestRow = move[0];
                            bestCol = move[1];
                        }
                    }
                    else
                    {
                        // calculate the minimax at this node of the player
                        currentScore = minimax(depth + 1, player)[0];
                        if (currentScore < bestScore)
                        {
                            bestScore = currentScore;
                            bestRow = move[0];
                            bestCol = move[1];
                        }
                    }
                    // undo move
                    node[move[0], move[1]].content = Player.Empty;
                }
            }
            return new int[] { bestScore, bestRow, bestCol };
        }
Exemplo n.º 26
0
 // Начало игры
 public void Start(string firstName, string secondName)
 {
     if (FirstPlayer.Name == firstName && SecondPlayer.Name == secondName && !isFirstLaunch)
     {
         // Продолжение игры
         SwitchPoint();
     }
     else
     {
         if (isFirstLaunch) isFirstLaunch = !isFirstLaunch;
         // Обнуление статистики
         FirstPlayer = new Player(firstName, Point.X);
         SecondPlayer = new Player(secondName, Point.O);
     }
 }
Exemplo n.º 27
0
    public HumanPlayer(TicTacToe.Player _type)
    {
        m_Type = _type;

        Button[] uiCells = TicTacToe.Instance.UICells;
        for (int i = 0; i < uiCells.Length; ++i)
        {
            BoxxedInt idx = new BoxxedInt()
            {
                data = i
            };
            uiCells[i].onClick.AddListener(new UnityEngine.Events.UnityAction(
                                               () => ClickEventReceived(idx.data)
                                               )
                                           );
        }
    }
Exemplo n.º 28
0
        public void GivenANewPieceToPlace_WhereSpaceIsEmpty_ReturnsTrue()
        {
            // Arrange
            Board board = new TicTacToe.Board(new char[][]
            {
                new char[] { 'X', '.', 'O' },
                new char[] { 'X', 'O', '.' },
                new char[] { '.', '.', '.' }
            });
            Player playerOne = new TicTacToe.Player('X');

            // Act
            var result = board.PlaceAPiece(2, 0, playerOne);

            // Assert
            Assert.True(result);
        }
Exemplo n.º 29
0
        public Game(Player p1, Player p2)
        {
            this.player1 = p1;
            this.player2 = p2;

            int num = randomGen.Next(0, 2);
            if (num == 1)
            {
                currentPlayer = player1;
            }
            else
            {
                currentPlayer = player2;
            }

            MessageBox.Show(currentPlayer.getName() + " will start");
        }
Exemplo n.º 30
0
        private static Board CreateNewBoard(string boardName, string playerNamer)
        {
            var player = new Player();
            player.Name = playerNamer;
            player.WaitingForOpponent = false;
            player.Simbolo = "X";

            var board = new Board();
            board.Name = boardName;
            board.Player1 = player;
            board.GameStarted = DateTime.Now;
            board.LastPlaySuccess = false;

            boards.Add(board);

            return board;
        }
Exemplo n.º 31
0
        private void PlayMove(Player player)
        {
            Retry:

            var move = player.FindMove(Area);

            while (move > Area - 1) {
                move = player.FindMove(Area);
            }

            var row = move / Size;
            var cell = move - (row * Size);

            if (board[row, cell] != blank) {
                goto Retry;
            }
            board[row, cell] = player.Tile;
        }
Exemplo n.º 32
0
		public static bool Equals(Player[][] p1,Player[][] p2)
		{
			bool result;
			int dim1 = p1.GetLength (0);
			int dim2 = p2.GetLength (0);
			//Si p1 et p2 n'ont pas la meme taille, on renvoie false
			if (dim1 != dim2) {
				return false;
			}

			for (int i = 0; i < dim1; i++) {
				for (int j = 0; j < dim2; j++) {
					result = Player.Equals (p1 [i] [j], p2 [i] [j]);
					if (!result) {
						return false;
					}
				}
			}
			return true;
		}