Ejemplo n.º 1
0
        public PlayerTask DoAI(List <PlayerTask> tasks)
        {
            IScore score       = new AggroScore();
            Game   currentGame = Session.Game;

            if (currentGame.CurrentPlayer.Choice == null)
            {
                List <OptionNode> solutions = OptionNode.GetSolutions(currentGame, currentGame.CurrentPlayer.Id, score, 10, 500);
                var solution = new List <PlayerTask>();
                solutions.OrderByDescending(p => p.Score).First().PlayerTasks(ref solution);
                return(solution.First());
            }

            if (currentGame.CurrentPlayer.Choice.ChoiceType == ChoiceType.MULLIGAN)
            {
                return(tasks[Rand.Next(0, tasks.Count)]);
                //return ChooseTask.Mulligan(currentGame.CurrentPlayer,
                //    score.MulliganRule()
                //        .Invoke(
                //            currentGame.CurrentPlayer.Choice.Choices.Select(p => currentGame.IdEntityDic[p]).ToList()));
            }

            // random ai!!
            return(tasks[Rand.Next(0, tasks.Count)]);
        }
        public override PlayerTask GetMove(POGame game)
        {
            //StopWatch.StartWithReset();

            int threadCount = 4;
            var player      = game.CurrentPlayer;
            var opponent    = game.CurrentOpponent;

            var validOpts = game.Simulate(player.Options()).Where(x => x.Value != null);
            var optsCount = validOpts.Count();
            var history   = opponent.PlayHistory;

            // Implement a simple Mulligan Rule
            if (player.MulliganState == Mulligan.INPUT)
            {
                List <int> mulligan = new AggroScore().MulliganRule().Invoke(player.Choice.Choices.Select(p => game.getGame().IdEntityDic[p]).ToList());
                return(ChooseTask.Mulligan(player, mulligan));
            }

            countProbabilities();

            MCTS       mcts   = new MCTS(game, DecksDict, ProbabilitiesDict, TurnDepth, TimeBudget, Selection, StateRate, ExplorationConstant);
            PlayerTask result = mcts.Search();

            //StopWatch.StopWithMessage(String.Format("Compute {0} options in {1} ms", optcount, StopWatch.ElapsedMilliseconds));

            //Console.WriteLine("Final task: " + result);
            return(result);

            void countProbabilities()
            {
                /* ----------- Counting probabilities ------------ */
                foreach (KeyValuePair <string, List <Card> > deck in DecksDict)
                {
                    int similarCount      = 0;
                    var playedCards       = history.Select(h => h.SourceCard).ToList();
                    var deckCards         = deck.Value;
                    var deckCardsDistinct = deckCards.Distinct().ToList();

                    playedCards
                    .ForEach(playedCard =>
                    {
                        deckCardsDistinct.ForEach(deckCard =>
                        {
                            if (playedCard.Name == deckCard.Name)
                            {
                                similarCount++;
                            }
                        });
                    });

                    double probability = Math.Round((double)similarCount / deckCards.Count(), 2);
                    ProbabilitiesDict[deck.Key] = probability;
                    //if (probability > 0) Console.WriteLine(deck.Key + " has probability of " + ProbabilitiesDict[deck.Key] * 100 + "%");
                }
            }
        }
Ejemplo n.º 3
0
        public static void OneTurn()
        {
            var game = new Game(
                new GameConfig()
            {
                StartPlayer      = 1,
                Player1Name      = "FitzVonGerald",
                Player1HeroClass = CardClass.WARRIOR,
                Player1Deck      = Decks.AggroPirateWarrior,
                Player2Name      = "RehHausZuckFuchs",
                Player2HeroClass = CardClass.SHAMAN,
                Player2Deck      = Decks.MidrangeJadeShaman,
                FillDecks        = false,
                Shuffle          = false,
                SkipMulligan     = false
            });

            game.Player1.BaseMana = 10;
            game.StartGame();

            var aiPlayer1 = new AggroScore();
            var aiPlayer2 = new AggroScore();

            game.Process(ChooseTask.Mulligan(game.Player1, aiPlayer1.MulliganRule().Invoke(game.Player1.Choice.Choices.Select(p => game.IdEntityDic[p]).ToList())));
            game.Process(ChooseTask.Mulligan(game.Player2, aiPlayer2.MulliganRule().Invoke(game.Player2.Choice.Choices.Select(p => game.IdEntityDic[p]).ToList())));

            game.MainReady();

            while (game.CurrentPlayer == game.Player1)
            {
                Console.WriteLine($"* Calculating solutions *** Player 1 ***");

                List <OptionNode> solutions = OptionNode.GetSolutions(game, game.Player1.Id, aiPlayer1, 10, 500);

                var solution = new List <PlayerTask>();
                solutions.OrderByDescending(p => p.Score).First().PlayerTasks(ref solution);
                Console.WriteLine($"- Player 1 - <{game.CurrentPlayer.Name}> ---------------------------");

                foreach (PlayerTask task in solution)
                {
                    Console.WriteLine(task.FullPrint());
                    game.Process(task);
                    if (game.CurrentPlayer.Choice != null)
                    {
                        break;
                    }
                }
            }

            Console.WriteLine(game.Player1.HandZone.FullPrint());
            Console.WriteLine(game.Player1.BoardZone.FullPrint());
        }
Ejemplo n.º 4
0
        public override PlayerTask GetMove(POGame poGame)
        {
            int myPlayerId            = poGame.CurrentPlayer.PlayerId;
            List <PlayerTask> options = poGame.CurrentPlayer.Options();

            // Implement a simple Mulligan Rule
            if (poGame.CurrentPlayer.MulliganState == Mulligan.INPUT)
            {
                List <int> mulligan = new AggroScore().MulliganRule().Invoke(poGame.CurrentPlayer.Choice.Choices.Select(p => poGame.getGame().IdEntityDic[p]).ToList());               //all mulligan handlers are the same for each score
                return(ChooseTask.Mulligan(poGame.CurrentPlayer, mulligan));
            }



            var simulationResults = poGame.Simulate(options);

            double     bestWorth = getWorth(poGame, myPlayerId);         //best worth starts with the current field
            PlayerTask bestTask  = null;

            foreach (PlayerTask t in options)
            {
                double resultingWorth = Double.NegativeInfinity;
                if (simulationResults.ContainsKey(t) && t.PlayerTaskType != PlayerTaskType.END_TURN)
                {
                    POGame resultingGameState = simulationResults[t];
                    resultingWorth = getWorth(resultingGameState, myPlayerId);
                }
                else                  //TODO: think of something to do if the key is unvalid
                                      //for now, do nothing if the resulting value is negative
                {
                }

                if (bestWorth < resultingWorth)
                {
                    bestWorth = resultingWorth;
                    bestTask  = t;
                }
            }

            if (bestTask == null)
            {
                return(EndTurnTask.Any(poGame.CurrentPlayer));
            }

            return(bestTask);
        }
Ejemplo n.º 5
0
        public void Execute()
        {
            _game.Process(PlayerTask);

            var controller = _game.ControllerById(_playerId);

            _gameState = _game.State == State.RUNNING ? 0
                : (controller.PlayState == PlayState.WON ? 1 : -1);

            _endTurn = _game.CurrentPlayer.Id != _playerId ? 1 : 0;

            Hash = _game.Hash(GameTag.LAST_CARD_PLAYED);

            var aggroScore = new AggroScore(controller);

            Score = aggroScore.Rate();
        }
Ejemplo n.º 6
0
        public override PlayerTask GetMove(POGame poGame)
        {
            timeIsUp       = false;
            timer          = new Timer(28000);
            timer.Elapsed += whenTimeUp;
            timer.Enabled  = true;

            Controller player = poGame.CurrentPlayer;

            playerId = player.PlayerId;

            if (player.MulliganState == Mulligan.INPUT)
            {
                List <int> mulligan = new AggroScore().MulliganRule().Invoke(player.Choice.Choices.Select(p => poGame.getGame().IdEntityDic[p]).ToList());
                return(ChooseTask.Mulligan(player, mulligan));
            }

            IEnumerable <KeyValuePair <PlayerTask, POGame> > validOpts = poGame.Simulate(player.Options()).Where(x => x.Value != null);
            int countOptions = validOpts.Count();

            //AppendChildNodes(rootNode);

            int        bestScore  = Int32.MinValue;
            PlayerTask chosenTask = null;

            foreach (KeyValuePair <PlayerTask, POGame> option in validOpts)
            {
                int currentScore = MiniMax(0, option.Value, true, Int32.MinValue, Int32.MaxValue);
                //Console.WriteLine("Current Score: " + currentScore);
                if (currentScore > bestScore)
                {
                    bestScore  = currentScore;
                    chosenTask = option.Key;
                }
            }
            //Console.WriteLine("Best Score: " + bestScore);

            if (chosenTask == null)
            {
                chosenTask = player.Options().First(x => x.PlayerTaskType == PlayerTaskType.END_TURN);
            }

            //Console.WriteLine("Zugzeit " + stopWatch.Elapsed);
            //Console.WriteLine("Best Task: " + chosenTask);
            return(chosenTask);
        }
        public override PlayerTask GetMove(POGame game)
        {
            var player = game.CurrentPlayer;

            // Implement a simple Mulligan Rule
            if (player.MulliganState == Mulligan.INPUT)
            {
                List <int> mulligan = new AggroScore().MulliganRule().Invoke(player.Choice.Choices.Select(p => game.getGame().IdEntityDic[p]).ToList());
                return(ChooseTask.Mulligan(player, mulligan));
            }

            // Get all simulation results for simulations that didn't fail
            var validOpts = game.Simulate(player.Options()).Where(x => x.Value != null);

            // If all simulations failed, play end turn option (always exists), else best according to score function
            return(validOpts.Any() ?
                   validOpts.OrderBy(x => Score(x.Value, player.PlayerId)).Last().Key :
                   player.Options().First(x => x.PlayerTaskType == PlayerTaskType.END_TURN));
        }
Ejemplo n.º 8
0
        public override PlayerTask GetMove(POGame game)
        {
            var player = game.CurrentPlayer;

            _me = player;
            // Implement a simple Mulligan Rule
            if (player.MulliganState == Mulligan.INPUT)
            {
                List <int> mulligan = new AggroScore().MulliganRule().Invoke(player.Choice.Choices.Select(p => game.getGame().IdEntityDic[p]).ToList());
                return(ChooseTask.Mulligan(player, mulligan));
            }

            int depth;
            int beamWidth;

            // Check how much time we have left on this turn. The hard limit is 75 seconds so we already stop
            // beam searching when 60 seconds have passed, just to be sure.
            if (_watch.ElapsedMilliseconds < 30 * 1000)
            {             // We still have ample time, proceed with beam search
                depth     = 15;
                beamWidth = 12;
            }
            else
            {             // Time is running out, just simulate one timestep now
                depth     = 1;
                beamWidth = 1;
                //Console.WriteLine("Over 30s in turn already. Pausing beam search for this turn!");
            }

            _watch.Start();
            var move = BeamSearch(game, depth, playerbeamWidth: beamWidth, opponentBeamWidth: 1);

            _watch.Stop();

            if (move.PlayerTaskType == PlayerTaskType.END_TURN)
            {
                _watch.Reset();
            }

            return(move);
        }
Ejemplo n.º 9
0
        public override PlayerTask GetMove(POGame poGame)
        {
            var player = poGame.CurrentPlayer;

            if (player.MulliganState == Mulligan.INPUT)
            {
                List <int> mull = new AggroScore().MulliganRule().Invoke(player.Choice.Choices.Select(p => poGame.getGame().IdEntityDic[p]).ToList());
                return(ChooseTask.Mulligan(player, mull));
            }

            var sims   = poGame.Simulate(poGame.CurrentPlayer.Options());
            var scores = new List <(int, PlayerTask)>(sims.Count);

            foreach (KeyValuePair <PlayerTask, POGame> pair in sims)
            {
                if (pair.Value != null)
                {
                    scores.Add((Score(pair.Value, player.PlayerId), pair.Key));
                }
            }

            scores.Sort((x, y) => x.Item1.CompareTo(y.Item1));


            //Console.WriteLine("Options: "+player.Options().Count);
            //foreach(var sco in scores)
            //{
            //	Console.WriteLine("  " + sco.Item1 + ":" + sco.Item2.PlayerTaskType);
            //}

            var ret = scores.Last().Item2;

            //Console.WriteLine("Chosen: " + ret.PlayerTaskType);
            //Console.WriteLine("-----------");

            return(ret);
        }
        public override PlayerTask GetMove(POGame poGame)
        {
            start = DateTime.UtcNow;

            SabberStoneCore.Model.Entities.Controller player = poGame.CurrentPlayer;

            if (player.MulliganState == Mulligan.INPUT)
            {
                List <int> mull = new AggroScore().MulliganRule().Invoke(player.Choice.Choices.Select(p => poGame.getGame().IdEntityDic[p]).ToList());
                return(ChooseTask.Mulligan(player, mull));
            }

            List <PlayerTask> opts = poGame.CurrentPlayer.Options();

            //Handle if choose option instead of normal getmove
            //if (!opts.FindAll(x => x.PlayerTaskType == PlayerTaskType.END_TURN).Any())
            //{
            //	var sims = poGame.Simulate(poGame.CurrentPlayer.Options());
            //	var sim_scores = new List<(PlayerTask, int)>(sims.Count);

            //	foreach (KeyValuePair<PlayerTask, POGame> pair in sims)
            //	{
            //		if (pair.Value != null)
            //		{
            //			sim_scores.Add((pair.Key, Score(pair.Value, player.PlayerId)));
            //		}
            //	}

            //	sim_scores.Sort((x, y) => x.Item2.CompareTo(y.Item2));
            //	return sim_scores.Last().Item1;
            //}

            Dictionary <PlayerTask, POGame> sims = poGame.Simulate(poGame.CurrentPlayer.Options());

            //based on i of options[i]
            (PlayerTask, int)[] base_opts = new (PlayerTask, int)[sims.Where(x => x.Value != null).Count()];
Ejemplo n.º 11
0
        public static void TestFullGames()
        {
            int maxGames = 1000;
            int maxDepth = 10;
            int maxWidth = 14;

            int[] player1Stats = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
            int[] player2Stats = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0 };

            var gameConfig = new GameConfig()
            {
                StartPlayer      = -1,
                Player1Name      = "FitzVonGerald",
                Player1HeroClass = CardClass.PALADIN,
                Player1Deck      = new List <Card>()
                {
                    Cards.FromName("Blessing of Might"),
                    Cards.FromName("Blessing of Might"),
                    Cards.FromName("Gnomish Inventor"),
                    Cards.FromName("Gnomish Inventor"),
                    Cards.FromName("Goldshire Footman"),
                    Cards.FromName("Goldshire Footman"),
                    Cards.FromName("Hammer of Wrath"),
                    Cards.FromName("Hammer of Wrath"),
                    Cards.FromName("Hand of Protection"),
                    Cards.FromName("Hand of Protection"),
                    Cards.FromName("Holy Light"),
                    Cards.FromName("Holy Light"),
                    Cards.FromName("Ironforge Rifleman"),
                    Cards.FromName("Ironforge Rifleman"),
                    Cards.FromName("Light's Justice"),
                    Cards.FromName("Light's Justice"),
                    Cards.FromName("Lord of the Arena"),
                    Cards.FromName("Lord of the Arena"),
                    Cards.FromName("Nightblade"),
                    Cards.FromName("Nightblade"),
                    Cards.FromName("Raid Leader"),
                    Cards.FromName("Raid Leader"),
                    Cards.FromName("Stonetusk Boar"),
                    Cards.FromName("Stonetusk Boar"),
                    Cards.FromName("Stormpike Commando"),
                    Cards.FromName("Stormpike Commando"),
                    Cards.FromName("Stormwind Champion"),
                    Cards.FromName("Stormwind Champion"),
                    Cards.FromName("Stormwind Knight"),
                    Cards.FromName("Stormwind Knight")
                },
                Player2Name      = "RehHausZuckFuchs",
                Player2HeroClass = CardClass.PALADIN,
                Player2Deck      = new List <Card>()
                {
                    Cards.FromName("Blessing of Might"),
                    Cards.FromName("Blessing of Might"),
                    Cards.FromName("Gnomish Inventor"),
                    Cards.FromName("Gnomish Inventor"),
                    Cards.FromName("Goldshire Footman"),
                    Cards.FromName("Goldshire Footman"),
                    Cards.FromName("Hammer of Wrath"),
                    Cards.FromName("Hammer of Wrath"),
                    Cards.FromName("Hand of Protection"),
                    Cards.FromName("Hand of Protection"),
                    Cards.FromName("Holy Light"),
                    Cards.FromName("Holy Light"),
                    Cards.FromName("Ironforge Rifleman"),
                    Cards.FromName("Ironforge Rifleman"),
                    Cards.FromName("Light's Justice"),
                    Cards.FromName("Light's Justice"),
                    Cards.FromName("Lord of the Arena"),
                    Cards.FromName("Lord of the Arena"),
                    Cards.FromName("Nightblade"),
                    Cards.FromName("Nightblade"),
                    Cards.FromName("Raid Leader"),
                    Cards.FromName("Raid Leader"),
                    Cards.FromName("Stonetusk Boar"),
                    Cards.FromName("Stonetusk Boar"),
                    Cards.FromName("Stormpike Commando"),
                    Cards.FromName("Stormpike Commando"),
                    Cards.FromName("Stormwind Champion"),
                    Cards.FromName("Stormwind Champion"),
                    Cards.FromName("Stormwind Knight"),
                    Cards.FromName("Stormwind Knight")
                },
                FillDecks    = false,
                Shuffle      = true,
                SkipMulligan = false,
                Logging      = false,
                History      = false
            };

            for (int i = 0; i < maxGames; i++)
            {
                var game = new Game(gameConfig);
                game.StartGame();

                var aiPlayer1 = new AggroScore();
                var aiPlayer2 = new AggroScore();

                List <int> mulligan1 = aiPlayer1.MulliganRule().Invoke(game.Player1.Choice.Choices.Select(p => game.IdEntityDic[p]).ToList());
                List <int> mulligan2 = aiPlayer2.MulliganRule().Invoke(game.Player2.Choice.Choices.Select(p => game.IdEntityDic[p]).ToList());

                game.Process(ChooseTask.Mulligan(game.Player1, mulligan1));
                game.Process(ChooseTask.Mulligan(game.Player2, mulligan2));

                game.MainReady();

                while (game.State != State.COMPLETE)
                {
                    while (game.State == State.RUNNING && game.CurrentPlayer == game.Player1)
                    {
                        List <OptionNode> solutions = OptionNode.GetSolutions(game, game.Player1.Id, aiPlayer1, maxDepth, maxWidth);
                        var solution = new List <PlayerTask>();
                        solutions.OrderByDescending(p => p.Score).First().PlayerTasks(ref solution);
                        foreach (PlayerTask task in solution)
                        {
                            game.Process(task);
                            if (game.CurrentPlayer.Choice != null)
                            {
                                break;
                            }
                        }
                    }
                    while (game.State == State.RUNNING && game.CurrentPlayer == game.Player2)
                    {
                        List <OptionNode> solutions = OptionNode.GetSolutions(game, game.Player2.Id, aiPlayer2, maxDepth, maxWidth);
                        var solution = new List <PlayerTask>();
                        solutions.OrderByDescending(p => p.Score).First().PlayerTasks(ref solution);
                        foreach (PlayerTask task in solution)
                        {
                            game.Process(task);
                            if (game.CurrentPlayer.Choice != null)
                            {
                                break;
                            }
                        }
                    }
                }

                player1Stats[(int)game.Player1.PlayState]++;
                player2Stats[(int)game.Player2.PlayState]++;

                Console.WriteLine($"{i}.Game: {game.State}, Player1: {game.Player1.PlayState} / Player2: {game.Player2.PlayState}");
            }

            Console.WriteLine($"Player1: {String.Join(",", player1Stats)}");
            Console.WriteLine($"Player2: {String.Join(",", player2Stats)}");
        }
Ejemplo n.º 12
0
        public static void FullGame()
        {
            var game = new Game(
                new GameConfig()
            {
                StartPlayer      = 1,
                Player1Name      = "FitzVonGerald",
                Player1HeroClass = CardClass.WARRIOR,
                Player1Deck      = Decks.AggroPirateWarrior,
                Player2Name      = "RehHausZuckFuchs",
                Player2HeroClass = CardClass.WARRIOR,
                Player2Deck      = Decks.AggroPirateWarrior,
                FillDecks        = false,
                Shuffle          = true,
                SkipMulligan     = false
            });

            game.StartGame();

            var aiPlayer1 = new AggroScore();
            var aiPlayer2 = new AggroScore();

            List <int> mulligan1 = aiPlayer1.MulliganRule().Invoke(game.Player1.Choice.Choices.Select(p => game.IdEntityDic[p]).ToList());
            List <int> mulligan2 = aiPlayer2.MulliganRule().Invoke(game.Player2.Choice.Choices.Select(p => game.IdEntityDic[p]).ToList());

            Console.WriteLine($"Player1: Mulligan {String.Join(",", mulligan1)}");
            Console.WriteLine($"Player2: Mulligan {String.Join(",", mulligan2)}");

            game.Process(ChooseTask.Mulligan(game.Player1, mulligan1));
            game.Process(ChooseTask.Mulligan(game.Player2, mulligan2));

            game.MainReady();

            while (game.State != State.COMPLETE)
            {
                Console.WriteLine("");
                Console.WriteLine($"Player1: {game.Player1.PlayState} / Player2: {game.Player2.PlayState} - " +
                                  $"ROUND {(game.Turn + 1) / 2} - {game.CurrentPlayer.Name}");
                Console.WriteLine($"Hero[P1]: {game.Player1.Hero.Health} / Hero[P2]: {game.Player2.Hero.Health}");
                Console.WriteLine("");
                while (game.State == State.RUNNING && game.CurrentPlayer == game.Player1)
                {
                    Console.WriteLine($"* Calculating solutions *** Player 1 ***");
                    List <OptionNode> solutions = OptionNode.GetSolutions(game, game.Player1.Id, aiPlayer1, 10, 500);
                    var solution = new List <PlayerTask>();
                    solutions.OrderByDescending(p => p.Score).First().PlayerTasks(ref solution);
                    Console.WriteLine($"- Player 1 - <{game.CurrentPlayer.Name}> ---------------------------");
                    foreach (PlayerTask task in solution)
                    {
                        Console.WriteLine(task.FullPrint());
                        game.Process(task);
                        if (game.CurrentPlayer.Choice != null)
                        {
                            Console.WriteLine($"* Recaclulating due to a final solution ...");
                            break;
                        }
                    }
                }

                // Random mode for Player 2
                Console.WriteLine($"- Player 2 - <{game.CurrentPlayer.Name}> ---------------------------");
                while (game.State == State.RUNNING && game.CurrentPlayer == game.Player2)
                {
                    //var options = game.Options(game.CurrentPlayer);
                    //var option = options[Rnd.Next(options.Count)];
                    //Log.Info($"[{option.FullPrint()}]");
                    //game.Process(option);
                    Console.WriteLine($"* Calculating solutions *** Player 2 ***");
                    List <OptionNode> solutions = OptionNode.GetSolutions(game, game.Player2.Id, aiPlayer2, 10, 500);
                    var solution = new List <PlayerTask>();
                    solutions.OrderByDescending(p => p.Score).First().PlayerTasks(ref solution);
                    Console.WriteLine($"- Player 2 - <{game.CurrentPlayer.Name}> ---------------------------");
                    foreach (PlayerTask task in solution)
                    {
                        Console.WriteLine(task.FullPrint());
                        game.Process(task);
                        if (game.CurrentPlayer.Choice != null)
                        {
                            Console.WriteLine($"* Recaclulating due to a final solution ...");
                            break;
                        }
                    }
                }
            }
            Console.WriteLine($"Game: {game.State}, Player1: {game.Player1.PlayState} / Player2: {game.Player2.PlayState}");
        }
Ejemplo n.º 13
0
        public static void FullGame()
        {
            var game = new Game(
                new GameConfig()
            {
                StartPlayer      = 1,
                Player1Name      = "WARRIOR Player1",
                Player1HeroClass = CardClass.WARRIOR,
                Player1Deck      = Decks.AggroPirateWarrior,
                Player2Name      = "WARRIOR Player2",
                Player2HeroClass = CardClass.WARRIOR,
                Player2Deck      = Decks.AggroPirateWarrior,
                FillDecks        = false,
                Shuffle          = true,
                SkipMulligan     = false
            });

            game.StartGame();

            var aiPlayer1 = new AggroScore();
            var aiPlayer2 = new AggroScore();

            List <int> mulligan1 = aiPlayer1.MulliganRule().Invoke(game.Player1.Choice.Choices.Select(p => game.IdEntityDic[p]).ToList());
            List <int> mulligan2 = aiPlayer2.MulliganRule().Invoke(game.Player2.Choice.Choices.Select(p => game.IdEntityDic[p]).ToList());

            Console.WriteLine($"Player1: Mulligan {String.Join(",", mulligan1)}");
            Console.WriteLine($"Player2: Mulligan {String.Join(",", mulligan2)}");

            game.Process(ChooseTask.Mulligan(game.Player1, mulligan1));
            game.Process(ChooseTask.Mulligan(game.Player2, mulligan2));
            //Console.WriteLine("############" + game.Turn);
            game.MainReady();
            int cur_turn;

            //CONNOR - Loop over all turns of the game
            while (game.State != State.COMPLETE)
            {
                Console.WriteLine("");
                Console.WriteLine($"Player1: {game.Player1.PlayState} / Player2: {game.Player2.PlayState} - " +
                                  $"ROUND {(game.Turn + 1) / 2} - {game.CurrentPlayer.Name}");
                Console.WriteLine($"Hero[P1]: {game.Player1.Hero.Health} / Hero[P2]: {game.Player2.Hero.Health}");
                Console.WriteLine("");
                //CONNOR - Loop over all plays that Player 1 will make in a turn
                while (game.State == State.RUNNING && game.CurrentPlayer == game.Player1)
                {
                    Console.WriteLine($"* Calculating solutions *** Player 1 ***");
                    //CONNOR - Get all options for the next play for the turn
                    List <OptionNode> solutions = OptionNode.GetSolutions(game, game.Player1.Id, aiPlayer1, 10, 500);
                    var solution = new List <PlayerTask>();
                    //CONNOR - Sort plays by decreasing score. The First() one is the highest score
                    solutions.OrderByDescending(p => p.Score).First().PlayerTasks(ref solution);
                    Console.WriteLine($"- Player 1 - <{game.CurrentPlayer.Name}> ---------------------------");
                    //CONNOR - Execute all tasks in that play
                    foreach (PlayerTask task in solution)
                    {
                        Console.WriteLine(task.FullPrint());
                        game.Process(task);
                        if (game.CurrentPlayer.Choice != null)
                        {
                            Console.WriteLine($"* Recaclulating due to a final solution ...");
                            break;
                        }
                    }
                    //This is the end of the turn for player1
                    //Console.WriteLine(">>>Player 1 HEALTH at " + game.Turn + " is " + game.CurrentPlayer.Hero.Health);
                }
                //This is the end of the turn for player1
                cur_turn = System.Convert.ToInt32(game.Turn);
                Console.WriteLine(">>>Player 1 HEALTH at " + (cur_turn - 1) + " is " + game.Player1.Hero.Health);

                //CONNOR - Loop over all plays that Player 2 will make in a turn
                // Random mode for Player 2
                Console.WriteLine($"- Player 2 - <{game.CurrentPlayer.Name}> ---------------------------");
                while (game.State == State.RUNNING && game.CurrentPlayer == game.Player2)
                {
                    //var options = game.Options(game.CurrentPlayer);
                    //var option = options[Rnd.Next(options.Count)];
                    //Log.Info($"[{option.FullPrint()}]");
                    //game.Process(option);
                    Console.WriteLine($"* Calculating solutions *** Player 2 ***");
                    List <OptionNode> solutions = OptionNode.GetSolutions(game, game.Player2.Id, aiPlayer2, 10, 500);
                    var solution = new List <PlayerTask>();
                    solutions.OrderByDescending(p => p.Score).First().PlayerTasks(ref solution);
                    Console.WriteLine($"- Player 2 - <{game.CurrentPlayer.Name}> ---------------------------");
                    foreach (PlayerTask task in solution)
                    {
                        Console.WriteLine(task.FullPrint());
                        game.Process(task);
                        if (game.CurrentPlayer.Choice != null)
                        {
                            Console.WriteLine($"* Recaclulating due to a final solution ...");
                            break;
                        }
                    }
                }
                //This is the end of the turn for player1
                cur_turn = System.Convert.ToInt32(game.Turn);
                Console.WriteLine(">>>Player 2 HEALTH at " + (cur_turn - 1) + " is " + game.Player2.Hero.Health);
            }
            Console.WriteLine($"Game: {game.State}, Player1: {game.Player1.PlayState} / Player2: {game.Player2.PlayState}");
        }
Ejemplo n.º 14
0
        // determine the "fitness" of the deck by its performance against the control deck
        public static double EvaluateFitness(List <Card> deck)
        {
            var watch      = Stopwatch.StartNew();
            var gameConfig = new GameConfig()
            {
                StartPlayer      = 1,
                Player1Name      = "P1",
                Player1HeroClass = hero,
                Player1Deck      = deck,
                Player2Name      = "P2",
                Player2HeroClass = CardClass.WARRIOR,
                Player2Deck      = Decks.AggroPirateWarrior,
                FillDecks        = false,
                Shuffle          = true,
                SkipMulligan     = false,
                Logging          = false,
                History          = false
            };

            int player_wins  = 0;
            int control_wins = 0;

            // simulate games between the member deck and the control deck, tracking wins
            // most efficient performance seems to be 1 game / thread per core
            Parallel.For(0, games, options, i =>
            {
                var game = new Game(gameConfig);
                game.StartGame();

                var aiPlayer1 = new ControlScore();
                var aiPlayer2 = new AggroScore();

                List <int> mulligan1 = aiPlayer1.MulliganRule().Invoke(game.Player1.Choice.Choices.Select(p => game.IdEntityDic[p]).ToList());
                List <int> mulligan2 = aiPlayer2.MulliganRule().Invoke(game.Player2.Choice.Choices.Select(p => game.IdEntityDic[p]).ToList());

                game.Process(ChooseTask.Mulligan(game.Player1, mulligan1));
                game.Process(ChooseTask.Mulligan(game.Player2, mulligan2));

                game.MainReady();
                try
                {
                    while (game.State != State.COMPLETE)
                    {
                        //Console.WriteLine($"Hero[P1]: {game.Player1.Hero.Health} / Hero[P2]: {game.Player2.Hero.Health}");
                        while (game.State == State.RUNNING && game.CurrentPlayer == game.Player1)
                        {
                            List <OptionNode> solutions = OptionNode.GetSolutions(game, game.Player1.Id, aiPlayer1, 10, 500);
                            var solution = new List <PlayerTask>();
                            solutions.OrderByDescending(p => p.Score).First().PlayerTasks(ref solution);
                            foreach (PlayerTask task in solution)
                            {
                                //Console.WriteLine(task.FullPrint());
                                game.Process(task);
                                if (game.CurrentPlayer.Choice != null)
                                {
                                    break;
                                }
                            }
                        }
                        while (game.State == State.RUNNING && game.CurrentPlayer == game.Player2)
                        {
                            List <OptionNode> solutions = OptionNode.GetSolutions(game, game.Player2.Id, aiPlayer2, 10, 500);
                            var solution = new List <PlayerTask>();
                            solutions.OrderByDescending(p => p.Score).First().PlayerTasks(ref solution);
                            foreach (PlayerTask task in solution)
                            {
                                //Console.WriteLine(task.FullPrint());
                                game.Process(task);
                                if (game.CurrentPlayer.Choice != null)
                                {
                                    break;
                                }
                            }
                        }
                    }
                    if (game.Player1.PlayState == PlayState.WON)
                    {
                        Interlocked.Increment(ref player_wins);
                    }
                    else if (game.Player2.PlayState == PlayState.WON)
                    {
                        Interlocked.Increment(ref control_wins);
                    }
                }
                catch (Exception e) {
                    Console.WriteLine($"Exception caught: {e}");
                    Console.WriteLine("Composition of offending deck:");
                    foreach (Card card in deck)
                    {
                        Console.WriteLine($"{card.ToString()}");
                    }
                    Console.WriteLine("Awarding win to opponent.");
                    Interlocked.Increment(ref control_wins);
                }
                Console.WriteLine($"Player 1 Wins: {player_wins} / Player 2 Wins: {control_wins}");
            });
            watch.Stop();
            Console.WriteLine("");
            Console.WriteLine($"{games} games took {watch.ElapsedMilliseconds / 1000 / 60} minutes!");
            Console.WriteLine($"Player 1 (Population) {player_wins * 100 / games}% vs. Player 2 (Control) {control_wins * 100 / games}%!");
            Console.WriteLine("");
            return(player_wins * 100 / games);
        }
        public static string FullGame(string player1Class, string player1Strategy, List <Card> player1Deck, string player2Class, string player2Strategy, List <Card> player2Deck, ref string gameLogAddr)
        {
            string logsbuild = "";
            var    game      = getGame(player1Class, player1Deck, player2Class, player2Deck);

            game.StartGame();

            string startPlayer = game.CurrentPlayer.Name;
            object aiPlayer1   = new AggroScore();
            object aiPlayer2   = new AggroScore();

            switch (player1Strategy.ToLower())
            {
            case "control":
                aiPlayer1 = new ControlScore();
                break;

            case "fatigue":
                aiPlayer1 = new FatigueScore();
                break;

            case "midrange":
                aiPlayer1 = new MidRangeScore();
                break;

            case "ramp":
                aiPlayer1 = new RampScore();
                break;
            }
            switch (player2Strategy.ToLower())
            {
            case "control":
                aiPlayer2 = new ControlScore();
                break;

            case "fatigue":
                aiPlayer2 = new FatigueScore();
                break;

            case "midrange":
                aiPlayer2 = new MidRangeScore();
                break;

            case "ramp":
                aiPlayer2 = new RampScore();
                break;
            }

            List <int> mulligan1 = ((GamePlayer.Score.Score)aiPlayer1).MulliganRule().Invoke(game.Player1.Choice.Choices.Select(p => game.IdEntityDic[p]).ToList());
            List <int> mulligan2 = ((GamePlayer.Score.Score)aiPlayer2).MulliganRule().Invoke(game.Player2.Choice.Choices.Select(p => game.IdEntityDic[p]).ToList());

            logsbuild += $"Player1: Mulligan {string.Join(",", mulligan1)}";
            logsbuild += "\n";
            logsbuild += $"Player2: Mulligan {string.Join(",", mulligan2)}";
            logsbuild += "\n";

            string hand_log      = "Hand<P1>,";
            string temp_hand_log = "";

            game.Process(ChooseTask.Mulligan(game.Player1, mulligan1));
            game.Process(ChooseTask.Mulligan(game.Player2, mulligan2));

            game.MainReady();

            while (game.State != State.COMPLETE)
            {
                logsbuild += $"Player1: {game.Player1.PlayState} / Player2: {game.Player2.PlayState} - " +
                             $"ROUND {(game.Turn + 1) / 2} - {game.CurrentPlayer.Name}" + "\n";
                logsbuild += $"Hero[P1]: {game.Player1.Hero.Health} / Hero[P2]: {game.Player2.Hero.Health}" + "\n";
                for (int i = 0; i < game.Player1.HandZone.Count; i++)
                {
                    temp_hand_log = $"{game.Player1.HandZone[i]}";
                    hand_log     += temp_hand_log.Substring(1, temp_hand_log.Length - 1);
                    hand_log      = hand_log.Split2('[')[0] + ",";
                }
                logsbuild += "\n";

                //Console.WriteLine(logsbuild);
                //registerLogHandStats(logsbuild);

                while (game.State == State.RUNNING && game.CurrentPlayer == game.Player1)
                {
                    logsbuild += $"* Calculating solutions *** Player 1 ***" + "\n";

                    List <OptionNode> solutions = OptionNode.GetSolutions(game, game.Player1.Id, ((GamePlayer.Score.Score)aiPlayer1), maxDepth, maxWidth);
                    var solution = new List <PlayerTask>();
                    solutions.OrderByDescending(p => p.Score).First().PlayerTasks(ref solution);

                    logsbuild += $"- Player 1 - <{game.CurrentPlayer.Name}> ---------------------------" + "\n";
                    foreach (PlayerTask task in solution)
                    {
                        logsbuild += task.FullPrint() + "\n";

                        game.Process(task);
                        if (game.CurrentPlayer.Choice != null)
                        {
                            logsbuild += $"* Recaclulating due to a final solution ..." + "\n";
                            break;
                        }
                    }
                }

                logsbuild += $"- Player 2 - <{game.CurrentPlayer.Name}> ---------------------------" + "\n";
                while (game.State == State.RUNNING && game.CurrentPlayer == game.Player2)
                {
                    logsbuild += $"* Calculating solutions *** Player 2 ***" + "\n";
                    List <OptionNode> solutions = OptionNode.GetSolutions(game, game.Player2.Id, ((GamePlayer.Score.Score)aiPlayer2), maxDepth, maxWidth);
                    var solution = new List <PlayerTask>();
                    solutions.OrderByDescending(p => p.Score).First().PlayerTasks(ref solution);

                    logsbuild += $"- Player 2 - <{game.CurrentPlayer.Name}> ---------------------------" + "\n";
                    foreach (PlayerTask task in solution)
                    {
                        logsbuild += task.FullPrint() + "\n";
                        game.Process(task);
                        if (game.CurrentPlayer.Choice != null)
                        {
                            logsbuild += $"* Recaclulating due to a final solution ..." + "\n";
                            break;
                        }
                    }
                }
            }

            //hand_log = hand_log + "\n";
            //Console.WriteLine(hand_log);

            int healthdiff = game.Player1.Hero.Health - game.Player2.Hero.Health;

            logsbuild  += "Game: {game.State}, Player1: " + game.Player1.PlayState + " / Player2:" + game.Player2.PlayState + "healthdiff:" + healthdiff + "& turns:" + game.Turn;
            gameLogAddr = logsbuild + "\n" + hand_log;

            return("start player=" + startPlayer + ", Game: {game.State}, Player1: " + game.Player1.PlayState + " / Player2:" + game.Player2.PlayState + "healthdiff:" + healthdiff + "& turns:" + game.Turn);
        }
Ejemplo n.º 16
0
        //the game we need
        public static string FullGame(List <Card> player1Deck, int where, List <Card> player2Deck, string gameLogAddr)
        {
            string logsbuild = "";
            var    game      = getGame(player1Deck, player2Deck);

            Console.WriteLine("game heroes:" + game.Heroes[0].ToString() + " and " + game.Heroes[1].ToString());
            game.StartGame();
            string startPlayer = game.CurrentPlayer.Name;
            var    aiPlayer1   = new AggroScore();
            var    aiPlayer2   = new AggroScore();

            List <int> mulligan1 = aiPlayer1.MulliganRule().Invoke(game.Player1.Choice.Choices.Select(p => game.IdEntityDic[p]).ToList());
            List <int> mulligan2 = aiPlayer2.MulliganRule().Invoke(game.Player2.Choice.Choices.Select(p => game.IdEntityDic[p]).ToList());

            logsbuild += $"Player1: Mulligan {string.Join(",", mulligan1)}";
            logsbuild += "\n";
            logsbuild += $"Player2: Mulligan {string.Join(",", mulligan2)}";
            logsbuild += "\n";
            // Console.WriteLine($"Player1: Mulligan {string.Join(",", mulligan1)}");
            //Console.WriteLine($"Player2: Mulligan {string.Join(",", mulligan2)}");

            game.Process(ChooseTask.Mulligan(game.Player1, mulligan1));
            game.Process(ChooseTask.Mulligan(game.Player2, mulligan2));

            game.MainReady();

            while (game.State != State.COMPLETE)
            {
                //  Console.WriteLine("here:" + where);
                logsbuild += $"Player1: {game.Player1.PlayState} / Player2: {game.Player2.PlayState} - " +
                             $"ROUND {(game.Turn + 1) / 2} - {game.CurrentPlayer.Name}" + "\n";
                logsbuild += $"Hero[P1]: {game.Player1.Hero.Health} / Hero[P2]: {game.Player2.Hero.Health}" + "\n";
                logsbuild += "\n";
                //Console.WriteLine($"Player1: {game.Player1.PlayState} / Player2: {game.Player2.PlayState} - " +
                //  $"ROUND {(game.Turn + 1) / 2} - {game.CurrentPlayer.Name}");//I get round number here, can cut it off right here
                //Console.WriteLine($"Hero[P1]: {game.Player1.Hero.Health} / Hero[P2]: {game.Player2.Hero.Health}");
                //Console.WriteLine("");
                while (game.State == State.RUNNING && game.CurrentPlayer == game.Player1)
                {
                    logsbuild += $"* Calculating solutions *** Player 1 ***" + "\n";
                    //  Console.WriteLine($"* Calculating solutions *** Player 1 ***");//player 1's turn
                    List <OptionNode> solutions = OptionNode.GetSolutions(game, game.Player1.Id, aiPlayer1, maxDepth, maxWidth);
                    var solution = new List <PlayerTask>();
                    solutions.OrderByDescending(p => p.Score).First().PlayerTasks(ref solution);
                    //Console.WriteLine($"- Player 1 - <{game.CurrentPlayer.Name}> ---------------------------");
                    logsbuild += $"- Player 1 - <{game.CurrentPlayer.Name}> ---------------------------" + "\n";
                    foreach (PlayerTask task in solution)
                    {
                        logsbuild += task.FullPrint() + "\n";
                        //  Console.WriteLine(task.FullPrint());//important focus point for you. test this by first uncommenting it
                        string printedTask = task.FullPrint();    //CONNOR CODE
                        if (printedTask.IndexOf("play") != -1)    //CONNOR CODE
                        {                                         //CONNOR CODE
                            string card = task.Source.ToString(); //CONNOR CODE
                            //Console.WriteLine("Play: " + printedTask);      //ADDITION: if the tast is PlayCardTask, this code runs
                            //Console.WriteLine("Card is: " + card);//CONNOR CODE
                            CalculateFreqs(card);//CONNOR CODE
                            //CalculateTotalFreqs(card, cardStatistics);//CONNOR CODE
                        }//CONNOR CODE
                        else//CONNOR CODE
                        {//CONNOR CODE
                         // Console.WriteLine("Else: " + printedTask);//CONNOR CODE
                        }//CONNOR CODE
                        game.Process(task);
                        if (game.CurrentPlayer.Choice != null)
                        {
                            logsbuild += $"* Recaclulating due to a final solution ..." + "\n";
                            //    Console.WriteLine($"* Recaclulating due to a final solution ...");
                            break;
                        }
                    }
                }//hello hell0 hello is there anybody in there? Now that you can hear it
                 // GC.Collect();
                 // Random mode for Player 2
                 // Console.WriteLine($"- Player 2 - <{game.CurrentPlayer.Name}> ---------------------------");//player 2's turn
                logsbuild += $"- Player 2 - <{game.CurrentPlayer.Name}> ---------------------------" + "\n";
                while (game.State == State.RUNNING && game.CurrentPlayer == game.Player2)
                {
                    //var options = game.Options(game.CurrentPlayer);
                    //var option = options[Rnd.Next(options.Count)];
                    //Log.Info($"[{option.FullPrint()}]");
                    //game.Process(option);
                    //   Console.WriteLine($"* Calculating solutions *** Player 2 ***");
                    logsbuild += $"* Calculating solutions *** Player 2 ***" + "\n";
                    List <OptionNode> solutions = OptionNode.GetSolutions(game, game.Player2.Id, aiPlayer2, maxDepth, maxWidth);
                    var solution = new List <PlayerTask>();
                    solutions.OrderByDescending(p => p.Score).First().PlayerTasks(ref solution);
                    // Console.WriteLine($"- Player 2 - <{game.CurrentPlayer.Name}> ---------------------------");
                    logsbuild += $"- Player 2 - <{game.CurrentPlayer.Name}> ---------------------------" + "\n";
                    foreach (PlayerTask task in solution)
                    {
                        //   Console.WriteLine(task.FullPrint());//this is what you neeed to focus on right here
                        logsbuild += task.FullPrint() + "\n";
                        game.Process(task);
                        if (game.CurrentPlayer.Choice != null)
                        {
                            //     Console.WriteLine($"* Recaclulating due to a final solution ...");
                            logsbuild += $"* Recaclulating due to a final solution ..." + "\n";
                            break;
                        }
                    }
                }
                GC.Collect();
            }
            //Console.WriteLine($"Game: {game.State}, Player1: {game.Player1.PlayState} / Player2: {game.Player2.PlayState}");
            int healthdiff = game.Player1.Hero.Health - game.Player2.Hero.Health;

            logsbuild += "Game: {game.State}, Player1: " + game.Player1.PlayState + " / Player2:" + game.Player2.PlayState + "healthdiff:" + healthdiff + "& turns:" + game.Turn;

            /*using (StreamWriter tw = File.AppendText(gameLogAddr))
             * {
             *  tw.WriteLine(logsbuild);
             *  tw.Close();
             * }*/
            return("start player=" + startPlayer + ", Game: {game.State}, Player1: " + game.Player1.PlayState + " / Player2:" + game.Player2.PlayState + "healthdiff:" + healthdiff + "& turns:" + game.Turn);
        }