예제 #1
0
        public void GameClassDisplaysMoveUpdatesAfter1Second()
        {
            Board board = new Board(3);
            Mock<IPlayer> player1 = new Mock<IPlayer>();
            player1.Setup(player => player.GetCharacterType()).Returns(BoardCharacter.X);
            Mock<IPlayer> player2 = new Mock<IPlayer>();
            player2.Setup(player => player.GetCharacterType()).Returns(BoardCharacter.Zero);
            var firstPlayerMoves = new Queue<Tuple<int, int>>(new[]
            {
                Tuple.Create(0, 0), Tuple.Create(0, 1), Tuple.Create(2, 0), Tuple.Create(2, 1), Tuple.Create(1, 2)
            });
            player1.Setup(player => player.MakeMove(board)).Returns(() => firstPlayerMoves.Dequeue());

            var secondPlayerMoves = new Queue<Tuple<int, int>>(new[]
            {
                Tuple.Create(1, 0), Tuple.Create(1, 1), Tuple.Create(0, 2), Tuple.Create(2, 2)
            });
            player2.Setup(player => player.MakeMove(board)).Returns(() => secondPlayerMoves.Dequeue());

            Game game = new Game(board, player1.Object, player2.Object, gameSubscriber.Object);

            List<DateTime> updateTimes = new List<DateTime>();
            gameSubscriber.Setup(x => x.GameUpdate(It.IsAny<string>())).Callback(() => updateTimes.Add(DateTime.Now));
            DateTime start = DateTime.Now;
            game.Run();
            DateTime previousDateTime = start;
            foreach (var updateTime in updateTimes)
            {
                Assert.IsTrue(updateTime - previousDateTime > new TimeSpan(0,0,0,0,900));
                Assert.IsTrue(updateTime - previousDateTime < new TimeSpan(0, 0, 0, 1, 100));
                previousDateTime = updateTime;
            }
        }
예제 #2
0
 public virtual void Run()
 {
     var game = new Game();
     SelectPlayers(game);
     Play(game);
     PrintResult(game);
 }
예제 #3
0
        public void GameClassDisplaysBoardAtEachMove()
        {
            Board board = new Board(3);
            Mock<IPlayer> player1 = new Mock<IPlayer>();
            player1.Setup(player => player.GetCharacterType()).Returns(BoardCharacter.X);
            Mock<IPlayer> player2 = new Mock<IPlayer>();
            player2.Setup(player => player.GetCharacterType()).Returns(BoardCharacter.Zero);
            var firstPlayerMoves = new Queue<Tuple<int, int>>(new[]
            {
                Tuple.Create(0, 0), Tuple.Create(0, 1), Tuple.Create(0, 2)
            });
            player1.Setup(player => player.MakeMove(board)).Returns(() => firstPlayerMoves.Dequeue());

            var secondPlayerMoves = new Queue<Tuple<int, int>>(new[]
            {
                Tuple.Create(1, 0), Tuple.Create(1, 1)
            });
            player2.Setup(player => player.MakeMove(board)).Returns(() => secondPlayerMoves.Dequeue());

            Game game = new Game(board, player1.Object, player2.Object, gameSubscriber.Object, 0);
            game.Run();
            gameSubscriber.Verify(g => g.GameUpdate(It.Is<string>(s => s == "X _ _\n_ _ _\n_ _ _")), Times.Once());
            gameSubscriber.Verify(g => g.GameUpdate(It.Is<string>(s => s == "X _ _\nO _ _\n_ _ _")), Times.Once());
            gameSubscriber.Verify(g => g.GameUpdate(It.Is<string>(s => s == "X X _\nO _ _\n_ _ _")), Times.Once());
            gameSubscriber.Verify(g => g.GameUpdate(It.Is<string>(s => s == "X X _\nO O _\n_ _ _")), Times.Once());
            gameSubscriber.Verify(g => g.GameUpdate(It.Is<string>(s => s == "X X X\nO O _\n_ _ _")), Times.Once());
        }
예제 #4
0
 public virtual void PrintResult(Game game)
 {
     if (game.IsDraw())
         output.WriteLine("Draw!");
     else
         output.WriteLine("Player {0} Wins!", game.Winner);
 }
예제 #5
0
 public virtual void Play(Game game)
 {
     while (!game.IsOver())
     {
         var move = Player(game.CurrentPlayer).GetNextMove();
         game.MakeMove(move);
     }
 }
예제 #6
0
파일: Program.cs 프로젝트: Version3/Csharp
        static void Main()
        {
            MyInfo myID = new MyInfo();
            Game theGame = new Game();

            myID.StudentInfo();
            theGame.Play();
        }
예제 #7
0
파일: Game.cs 프로젝트: Selma1/Tic-tac-toe
		public static bool Equals(Game g1, Game g2)
		{
			bool player1 = Player.Equals (g1.Player1, g2.Player1);
			bool player2 = Player.Equals (g1.Player2, g2.Player2);
			bool rounds = Round.Equals (g1.Rounds, g2.Rounds);
			bool current = Round.Equals (g1.Current, g2.Current);
			return (player1 && player2 && rounds && current);
		}
예제 #8
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);
      }
예제 #9
0
 public void GameClassDisplaysBoardAtStartOfGame()
 {
     Board board = new Board(3);
     IPlayer player1 = new ComputerPlayer(BoardCharacter.X);
     IPlayer player2 = new ComputerPlayer(BoardCharacter.Zero);
     Game game = new Game(board, player1, player2, gameSubscriber.Object, 0);
     game.Run();
     gameSubscriber.Verify(g => g.GameBegin(It.Is<string>(s => IsEmptyBoard(s))), Times.Once());
 }
예제 #10
0
		public TicTacToeGame (IReader reader, IDisplayer displayer, IBoardFormatter formatter, IPlayerFactory player_factory, IRoundFactory round_factory, Game game, IGameRepository game_repository)
		{
			_game = game;
			_reader = reader;
			_displayer = displayer;
			_formatter = formatter;
			_player_factory = player_factory;
			_round_factory = round_factory;
			_game_repository = game_repository;
		}
예제 #11
0
		public TicTacToeRound (IReader reader, IDisplayer displayer, IBoardFormatter formatter, Game game, IGameRepository game_repository)
		{
			_reader = reader;
			_displayer = displayer;
			_game = game;
			_round = _game.Current;
			_checker = new BoardWinChecker (_round.Board);
			_formatter = formatter;
			_game_repository = game_repository;
		}
예제 #12
0
		public bool Save (Game game)
		{
			string json = JsonConvert.SerializeObject(game, Newtonsoft.Json.Formatting.Indented,
				new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects });

			using (StreamWriter outfile = new StreamWriter(@"game.json"))
			{
				outfile.Write(json);
			}

			return true;
		}
예제 #13
0
 //At this moment move is just random.
 public int getMove(Game game)
 {
     Random randomGen = new System.Random();
     while(1==1)
     {
         int move = randomGen.Next(0, 8);
         if (game.getBoard()[move/3, move%3] == 0)
         {
             return move;
         }
     }
 }
예제 #14
0
        public virtual void SelectPlayers(Game game)
        {
            string choice;
            do
            {
                output.Write("Select player (X or O): ");
                choice = input.ReadLine().ToUpper();
                output.WriteLine();
            } while (!"XO".Contains(choice));

            var computer = "XO".Replace(choice, "");
            SetPlayer(choice, new HumanPlayer(game, input, output));
            SetPlayer(computer, new ComputerPlayer(game));
        }
예제 #15
0
파일: Program.cs 프로젝트: tnimas/TicTacToe
 static void Main()
 {
     //           try
     //           {
         var game = new Game();
         game.Init();
     //
     //            }
     //            catch (Exception e)
     //            {
     //                throw;
     //                MessageBox.Show(e.Message);
     //            }
 }
예제 #16
0
		public bool Save (Game game)
		{
			
			StreamWriter wr = new StreamWriter ("game.xml");
				
			var serializer = new DataContractSerializer(game.GetType(), null, 
				0x7FFF /*maxItemsInObjectGraph*/, 
				false /*ignoreExtensionDataObject*/, 
				true /*preserveObjectReferences : this is where the magic happens */, 
				null /*dataContractSurrogate*/);
			serializer.WriteObject(wr.BaseStream, game);

			wr.Close ();

			return true;
		}
예제 #17
0
		public TicTacToeRunner (IReader reader, IDisplayer displayer, IBoardFormatter formatter, IPlayerFactory player_factory, IRoundFactory round_factory, IGameFactory game_factory, IGameRepository game_repository)
		{
			_reader = reader;
			_displayer = displayer;
			_game_repository = game_repository;
			_game_factory = game_factory;
			_formatter = formatter;
			_round_factory = round_factory;
			_player_factory = player_factory;

			//on charge la partie dans le repo
			_game_model = _game_repository.Load();

			if(_game_model == null)
				_game_model = game_factory.Create (NUMBER_ROUND);
			
			_game = new TicTacToeGame (_reader, _displayer, formatter, player_factory, round_factory, _game_model, _game_repository);
		}
        static void Main(string[] args)
        {
            int delay = 400;
            int xWins = 0;
            int oWins = 0;
            int ties = 0;

            var sw = Stopwatch.StartNew();
            var loop = Parallel.For(0, 1000 * 100, i =>
            {
                var game = new Game(new Switcher(),
                            new WinDectector(),
                            new TieDetector(),
                            new Grid(new TileFactory<Tile>()),
                            new FirstPlayer("1", Piece.X, new ValidMoveGetter()),
                            new RandomPlayer("2", Piece.O, new ValidMoveGetter()));
                GameResults status;

                for (;;)
                {
                    //Thread.Sleep(delay);
                    status = game.PerformMove();
                    //DrawGrid(game.Grid);
                    if (status.IsFinished)
                        break;
                }
                if (status.Winner == null)
                    Interlocked.Increment(ref ties);
                else if (status.Winner.Piece == Piece.X)
                    Interlocked.Increment(ref xWins);
                else
                    Interlocked.Increment(ref oWins);
                //Thread.Sleep(delay);
                //Console.WriteLine("winner: " + (status.Winner == null ? "Tie" : status.Winner.Name));
                //Thread.Sleep(delay);
            });
            while (!loop.IsCompleted)
                Thread.Sleep(1000);
            Console.WriteLine("Time: " + sw.ElapsedMilliseconds);
            Console.WriteLine("Ties: " + ties);
            Console.WriteLine("X: " + xWins);
            Console.WriteLine("O: " + oWins);
            Console.Read();
        }
예제 #19
0
        public void PlayGame()
        {
            bool playGame = true;
            Console.WriteLine("Do you want to play a game? (Y/N)");
            while (playGame)
            {
                if (Console.ReadLine() != "Y")
                {
                    playGame = false;
                }
                else
                {
                    Game game = new Game(new Board(3), new ComputerPlayer(BoardCharacter.X), new ComputerPlayer(BoardCharacter.Zero), this);
                    game.Run();
                }
                Console.WriteLine("Do you want to play another game? (Y/N)");

            }
        }
예제 #20
0
        public override void MakeMove(ref Board aBoard)
        {
            int move;
            Game theGame = new Game();
            do
            {
                theGame.AskMove(GetPiece());
                string X = Convert.ToString(Console.ReadLine());
                if (X == "")
                {
                    move = Convert.ToInt32("9");
                }
                else
                {
                    move = Convert.ToInt32(int.Parse(X));
                }
            } while (!aBoard.IsLegalMove(move));

            aBoard.ReceiveMove(GetPiece(), move);
        }
        public void RunGames(IPlayer playerOne, IPlayer playerTwo, int count = 1)
        {
            for (int i = 0; i < count; i++)
            {
                var game = new Game(new Switcher(),
                            new WinDectector(),
                            new TieDetector(),
                            new Grid(new TileFactory<Tile>()),
                            playerOne,
                            playerTwo);
                GameResults status;

                for (;;)
                {
                    status = game.PerformMove();
                    if (status.IsFinished)
                        break;
                }
            }
        }
예제 #22
0
		public void Run ()
		{
			var returnCode = 2;

			while (returnCode == 2) {
				returnCode = _game.Start ();

				//Code : on quite
				if (returnCode == 0) {
					_game_repository.Delete ();
				}

				//[1] Code : on quitte en sauvegardant

				//Code : lancement d'une nouvelle partie
				if (returnCode == 2) {
					_displayer.Clear ();
					_displayer.Show ("Lancement d'une nouvelle partie !");
					_game_repository.Delete ();
					_game_model = _game_factory.Create (NUMBER_ROUND);
					_game = new TicTacToeGame (_reader, _displayer, _formatter, _player_factory, _round_factory, _game_model, _game_repository);
				}
			}
		}
예제 #23
0
      protected void InitializeGame()
      {
         string playerOneStr = comboBoxPlayer1.Text;
         string playerTwoStr = comboBoxPlayer2.Text;
                  
         Player playerOne = CreatePlayerInstance(playerOneStr, 'X');
         Player playerTwo = CreatePlayerInstance(playerTwoStr, 'O');

         if (playerOne == null || playerTwo == null)
         {
            throw new ConfigurationException("Both players must be set to either Human or AI in order to start a game.");
         }

         Game game = new Game(playerOne, playerTwo);
         Thread thread = new Thread(game.Start);                           
         game.GameUpdate += game_gameUpdate;
         thread.Start();
      }
예제 #24
0
      /// <summary>
      /// Called when a player object is given control, prompting the user for a move
      /// </summary>
      /// <param name="sender">Game instance requesting a human player's move</param>
      /// <param name="e"></param>
      private void player_promptForMove(object sender, EventArgs e)
      {
         gameActive = (Game)sender;

         for (int iX = 0; iX < 3; iX++)
         {
            for (int iY = 0; iY < 3; iY++)
            {
               string symbolStr = string.Empty;
               Player squareOwner = gameActive.Board.Squares[iX, iY].Owner;

               Control control = squareButtons[iX, iY];
               bool setEnabled = squareOwner == null;

               SafeEnableControl(control, setEnabled);
            }
         }
      }
예제 #25
0
파일: Player.cs 프로젝트: REast/TicTacToeAI
 /// <summary>
 /// Method called when the game passes control to this player
 /// </summary>
 /// <param name="game">Game object that this player belongs to</param>
 public abstract void PromptForMove(Game game);
예제 #26
0
        //Overloaded function, if a Player is given as parameter to the GameOver method it means that that player has won, else it's a tie.
        private void GameOver(Player p)
        {
            if (p.getNumber() == 1)
            {
                player1.win();
                player2.loss();
            }
            else
            {
                player1.loss();
                player2.win();
            }

            updateField();
            updateResults();
            MessageBox.Show(p.getName() + " won the game");
            game = null;
        }
예제 #27
0
 private void GameOver()
 {
     player1.tie();
     player2.tie();
     updateField();
     updateResults();
     MessageBox.Show("Game resulted in a tie");
     game = null;
 }
예제 #28
0
 public void newGame(object sender, EventArgs e)
 {
     if (player1 == null || player2 == null)
     {
         MessageBox.Show("Set the playernames first, if you need help click on the help button");
     }
     else
     {
         game = new Game(player1, player2);
         updateField();
         //If the starting player is controlled by AI the play method get's called with a generated move from the AI
         //else the program will wait for user input
         if (game.getCurrentPlayer().GetType() == new Computer("none", 0).GetType())
         {
             Computer c = (Computer)game.getCurrentPlayer();
             play(c.getMove(game));
         }
     }
 }
예제 #29
0
 public void InitializeGame()
 {
     first = new Mock<IPlayer>();
     second = new Mock<IPlayer>();
     first.Setup(player => player.GetCharacterType()).Returns(BoardCharacter.X);
     second.Setup(player => player.GetCharacterType()).Returns(BoardCharacter.Zero);
     board = new Board(3);
     game = new Game(board, first.Object, second.Object, null, 0);
 }
예제 #30
0
 public ComputerPlayer(Game game)
 {
     this.game = game;
 }