예제 #1
0
        public ActionResult DeleteConfirmed(string id)
        {
            CustomScore customScore = db.CustomScores.Find(id);

            db.CustomScores.Remove(customScore);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
예제 #2
0
 public ActionResult Edit([Bind(Include = "Id,IdNode,Value,Comment")] CustomScore customScore)
 {
     if (ModelState.IsValid)
     {
         db.Entry(customScore).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.Id     = new SelectList(db.Users, "Id", "FirstName", customScore.Id);
     ViewBag.IdNode = new SelectList(db.Nodes, "IdNode", "Name", customScore.IdNode);
     return(View(customScore));
 }
예제 #3
0
        // GET: CustomScores/Details/5
        public ActionResult Details(string id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            CustomScore customScore = db.CustomScores.Find(id);

            if (customScore == null)
            {
                return(HttpNotFound());
            }
            return(View(customScore));
        }
예제 #4
0
        // GET: CustomScores/Edit/5
        public ActionResult Edit(string id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            CustomScore customScore = db.CustomScores.Find(id);

            if (customScore == null)
            {
                return(HttpNotFound());
            }
            ViewBag.Id     = new SelectList(db.Users, "Id", "FirstName", customScore.Id);
            ViewBag.IdNode = new SelectList(db.Nodes, "IdNode", "Name", customScore.IdNode);
            return(View(customScore));
        }
예제 #5
0
        public override PlayerTask GetMove(POGame poGame)
        {
            var player = poGame.CurrentPlayer;

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

            if (poGame.CurrentPlayer.Options().Count == 1)
            {
                return(poGame.CurrentPlayer.Options()[0]);
            }

            POGame initialState = poGame.getCopy();

            Node root = new Node();

            Node  selectedNode;
            Node  nodeToSimulate;
            float scoreOfSimulation;
            int   iterations = 0;

            InitializeRoot(root, initialState);

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            while (stopwatch.ElapsedMilliseconds <= MAX_TIME)
            {
                poGame         = initialState;
                selectedNode   = Selection(root, iterations, ref poGame);
                nodeToSimulate = Expansion(selectedNode, ref poGame);

                for (int i = 0; i < NUM_SIMULATIONS; i++)
                {
                    scoreOfSimulation = Simulation(nodeToSimulate, poGame);
                    Backpropagation(nodeToSimulate, scoreOfSimulation);
                    iterations++;
                }
            }
            stopwatch.Stop();

            return(SelectAction.selectTask(SELECTION_ACTION_METHOD, root, iterations, EXPLORE_CONSTANT));
        }
예제 #6
0
        //POGame poGame2;
        public override PlayerTask GetMove(POGame poGame)
        {
            var player = poGame.CurrentPlayer;

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

#if DEBUG
            Console.WriteLine($"root:{GetGameHashCode(poGame)}");
#endif
            PlayerTask bestAction = null;
            if (poGame.CurrentPlayer.Options().Count == 1)
            {
                bestAction = poGame.CurrentPlayer.Options()[0];
            }
            else
            {
                stopwatchForThisTurn.Start();

                long       bestActionCode = 0;
                Trajectory trajectory     = new Trajectory();

                List <PlayerTask> taskToSimulate = new List <PlayerTask>(1);
                taskToSimulate.Add(null);
                POGame poGameRoot = poGame;

                Node root;
                long gameHashCodeRoot = GetGameHashCode(poGameRoot);
                if (!nodeHashMap.TryGetValue(gameHashCodeRoot, out root))
                {
                    root = new Node();
                    nodeHashMap.Add(gameHashCodeRoot, root);
                }

                Expand(root, poGameRoot);

                /*foreach (var child in root.edges)
                 * {
                 *      Console.WriteLine(child.actionHashCode);
                 * }*/

                long      think_time = (30 * 1000 - stopwatchForThisTurn.ElapsedMilliseconds) / Math.Max(3, 5 - movesInThisTurn);
                Stopwatch stopwatch  = new Stopwatch();
                stopwatch.Start();
                //for (int itr = 0; itr < 100; ++itr)
                while (stopwatch.ElapsedMilliseconds <= think_time)
                {
                    Node node = root;
                    poGame = poGameRoot.getCopy();
                    long gameHashCode       = gameHashCodeRoot;
                    long actionHashCodeNext = 0;
                    bool simulateResult     = true;
                    int  index = 0;
                    trajectory.Clear();

                    // traverse
                    do
                    {
                        index = Select(node);

                        /*if (index >= node.edges.Count)
                         * {
                         *      Console.WriteLine($"{index}, {node.edges.Count}, {node == root}");
                         *      Debugger.Break();
                         * }*/
                        actionHashCodeNext = node.edges[index].actionHashCode;

                        // Until the end of my own turn
                        if (actionHashCodeNext == 0)
                        {
                            trajectory.Add((node, index));
                            break;
                        }

                        taskToSimulate[0] = null;
                        foreach (PlayerTask task in poGame.CurrentPlayer.Options())
                        {
                            if (GetActionHashCode(task) == actionHashCodeNext)
                            {
                                taskToSimulate[0] = task;
                                break;
                            }
                        }
                        if (taskToSimulate[0] == null)
                        {
                            // Hash key conflict
                            return(poGame.CurrentPlayer.Options().First());

                            /*foreach (PlayerTask task in poGame.CurrentPlayer.Options())
                             * {
                             *      Console.WriteLine($"{task}, {GetActionHashCode(task)}");
                             * }
                             * Console.WriteLine("---");
                             * foreach (var edge in node.edges)
                             * {
                             *      Console.WriteLine($"{edge.task}, {edge.actionHashCode}");
                             * }
                             * poGame2 = node.poGame;
                             * Console.WriteLine(poGame2.Turn);
                             * Console.WriteLine(gameHashCode);
                             * Console.WriteLine("---");
                             * foreach (var minion in poGame.CurrentPlayer.BoardZone)
                             * {
                             *      Console.WriteLine(minion.CantAttackHeroes);
                             * }
                             * var tasks = poGame.CurrentPlayer.Options();
                             * foreach (PlayerTask task in tasks)
                             * {
                             *      Console.WriteLine($"{task}, {GetActionHashCode(task)}");
                             * }
                             * Debugger.Break();*/
                        }

                        poGame = poGame.Simulate(taskToSimulate)[taskToSimulate[0]];
                        long gameHashCodeNext = GetGameHashCode(poGame);
                        if (gameHashCode == gameHashCodeNext)
                        {
                            // loop
                            node.edges.RemoveAt(index);
                            continue;
                        }
                        gameHashCode = gameHashCodeNext;

                        trajectory.Add((node, index));

                        if (!nodeHashMap.TryGetValue(gameHashCode, out node))
                        {
                            node = new Node();
                            //node.poGame = poGame;
                            nodeHashMap.Add(gameHashCode, node);
                        }
                    } while (node.edges != null);

                    if (simulateResult == false)
                    {
                        continue;
                    }

                    if (actionHashCodeNext != 0)
                    {
#if DEBUG
                        Console.WriteLine($"expand:{gameHashCode}");
#endif
                        Expand(node, poGame);

                        float value = Simulate(node, poGame);
                        Backup(trajectory, value);
                    }
                    else
                    {
                        float value;
                        if (node.edges[index].visitCount == 0)
                        {
                            value = ScoreToValue(Score(poGame));
                        }
                        else
                        {
                            value = node.edges[index].totalValue / node.edges[index].visitCount;
                        }
                        Backup(trajectory, value);
                    }
                }
                stopwatch.Stop();
                //Console.WriteLine($"{think_time}, {root.visitCount}, {root.visitCount * 1000 / stopwatch.ElapsedMilliseconds} nps");

                // Choose the most visited node
                float best = Single.MinValue;
                foreach (Edge child in root.edges)
                {
                    if (child.visitCount >= best)
                    {
                        best           = child.visitCount;
                        bestActionCode = child.actionHashCode;
                    }
                }

                // Choose an action with a matching hash code
                foreach (PlayerTask task in poGameRoot.CurrentPlayer.Options())
                {
                    if (GetActionHashCode(task) == bestActionCode)
                    {
                        bestAction = task;
                        break;
                    }
                }
            }

            stopwatchForThisTurn.Stop();
            ++movesInThisTurn;
            if (bestAction.PlayerTaskType == PlayerTaskType.END_TURN)
            {
                //Console.WriteLine(movesInThisTurn);
                stopwatchForThisTurn.Reset();
                movesInThisTurn = 0;
                nodeHashMap.Clear();
            }

            return(bestAction);
        }
            /* Cannot be used when using threads
             * public void PrintLog(POGame game, IOrderedEnumerable<KeyValuePair<PlayerTask, int>> scoreres)
             * {
             *      var player = game.CurrentPlayer;
             *      var validOpts = game.Simulate(player.Options()).Where(x => x.Value != null);
             *      var score_res = scoreres;
             *      Console.WriteLine("Round Nr:" + Convert.ToString(game.Turn));
             *      Console.WriteLine("HeroHP: " + Convert.ToString(player.Hero.Health) + "\tOppHP: " + Convert.ToString(game.CurrentOpponent.Hero.Health));
             *      Console.WriteLine("HeroMinionHP: " + Convert.ToString(player.BoardZone.Sum(p => p.Health)) + "\tOppMinionHP: " + Convert.ToString(game.CurrentOpponent.BoardZone.Sum(p => p.Health)));
             *      Console.WriteLine("HeroMinionAtk: " + Convert.ToString(player.BoardZone.Sum(p => p.AttackDamage)) + "\tOppMinionAtk: " + Convert.ToString(game.CurrentOpponent.BoardZone.Sum(p => p.AttackDamage)));
             *      foreach (var tmp_score in score_res)
             *      {
             *
             *              Console.WriteLine(Convert.ToString(tmp_score.Key) + Convert.ToString(tmp_score.Value));
             *      }
             *      Console.WriteLine("-------------------------------------------------------");
             * }
             */
            public override PlayerTask GetMove(POGame game)
            {
                var player = game.CurrentPlayer;

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

                var opponent  = game.CurrentOpponent;
                var options   = player.Options();
                var validOpts = game.Simulate(options).Where(x => x.Value != null);
                var optcount  = validOpts.Count();



                if (game.Turn == 1)
                {
                    var opt1 = options.Where(x => x.HasSource && x.Source.Card.Name == "N'Zoth's First Mate");
                    if (opt1.Count() > 0)
                    {
                        /*
                         * Console.WriteLine(opt1);
                         * Console.WriteLine(opt1.First());
                         * Console.WriteLine(opt1.Last());
                         */
                        return(opt1.First());
                    }
                }


                if (game.Turn == 3)
                {
                    var opt2 = options.Where(x => x.HasSource && x.Source.Card.Name == "Fiery War Axe");
                    if (opt2.Count() > 0)
                    {
                        return(opt2.First());
                    }
                }
                if (game.Turn == 5)
                {
                    var opt2 = options.Where(x => x.HasSource && x.Source.Card.Name == "Arcanite Reaper");
                    if (opt2.Count() > 0)
                    {
                        return(opt2.First());
                    }
                }


                /*
                 * if (player.Hero.Health < DEFENSE_HEALTH_THRESHOLD * player.Hero.BaseHealth)
                 *      RuntimeScaling[0] += 0.1;
                 *
                 * if (opponent.Hero.Health < DEFENSE_HEALTH_THRESHOLD * opponent.Hero.Health)
                 *      RuntimeScaling[1] += 0.1;
                 */
                var returnValue = validOpts.Any() ?
                                  validOpts.Select(x => score(x, player.PlayerId, (optcount >= 5) ? ((optcount >= 25) ? 1 : 2) : 3)).OrderBy(x => x.Value).Last().Key :
                                  player.Options().First(x => x.PlayerTaskType == PlayerTaskType.END_TURN);

                return(returnValue);

                KeyValuePair <PlayerTask, int> score(KeyValuePair <PlayerTask, POGame> state, int player_id, int max_depth = 3)
                {
                    int max_score = int.MinValue;

                    if (max_depth > 0 && state.Value.CurrentPlayer.PlayerId == player_id)
                    {
                        var subactions = state.Value.Simulate(state.Value.CurrentPlayer.Options()).Where(x => x.Value != null);

                        foreach (var subaction in subactions)
                        {
                            max_score = Math.Max(max_score, score(subaction, player_id, max_depth - 1).Value);
                        }
                    }
                    max_score = Math.Max(max_score, Score(state.Value, player_id));
                    return(new KeyValuePair <PlayerTask, int>(state.Key, max_score));
                }
            }
        public override PlayerTask GetMove(POGame game)
        {
            if (!initialized)
            {
                Initialize(game);
            }

            // if there is a subagent
            if (subAgent != null)
            {
                // let subagent do the move, skip the following code
                return(subAgent.GetMove(game));
            }

            var player = game.CurrentPlayer;

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

            var opponent = game.CurrentOpponent;
            var options  = player.Options();

            var coins = options.Where(x => x.HasSource && x.Source.Card.Name == "The Coin");

            if (coins.Count() > 0)
            {
                return(coins.First());
            }

            var validOpts = game.Simulate(options).Where(x => x.Value != null);
            var optcount  = validOpts.Count();

#if DEBUG
            /*
             * var score_res = validOpts.Select(x => score(x, player.PlayerId, (optcount >= 5) ? ((optcount >= 25) ? 1 : 2) : 3)).OrderBy(x => x.Value);
             *
             *      Console.WriteLine("Round Nr:" + Convert.ToString(game.Turn));
             *      Console.WriteLine("HeroHP: " + Convert.ToString(player.Hero.Health) + "\tOppHP: " + Convert.ToString(game.CurrentOpponent.Hero.Health));
             *      Console.WriteLine("HeroMinionHP: " + Convert.ToString(player.BoardZone.Sum(p => p.Health)) + "\tOppMinionHP: " + Convert.ToString(game.CurrentOpponent.BoardZone.Sum(p => p.Health)));
             *      Console.WriteLine("HeroMinionAtk: " + Convert.ToString(player.BoardZone.Sum(p => p.AttackDamage)) + "\tOppMinionAtk: " + Convert.ToString(game.CurrentOpponent.BoardZone.Sum(p => p.AttackDamage)));
             *      foreach (var tmp_score in score_res)
             *      {
             *
             *              Console.WriteLine(Convert.ToString(tmp_score.Key) + Convert.ToString(tmp_score.Value));
             *      }
             *      Console.WriteLine("-------------------------------------------------------");
             * //PrintLog(game,  score_res);
             */
#endif

            if (player.Hero.Health < DEFENSE_HEALTH_THRESHOLD * player.Hero.BaseHealth)
            {
                RuntimeScaling[0] += 0.1;
            }

            if (opponent.Hero.Health < DEFENSE_HEALTH_THRESHOLD * opponent.Hero.Health)
            {
                RuntimeScaling[1] += 0.1;
            }

            var returnValue = validOpts.Any() ?
                              validOpts.Select(x => score(x, player.PlayerId, (optcount >= 5) ? ((optcount >= 25) ? 1 : 2) : 3)).OrderBy(x => x.Value).Last().Key :
                              player.Options().First(x => x.PlayerTaskType == PlayerTaskType.END_TURN);

            return(returnValue);

            KeyValuePair <PlayerTask, int> score(KeyValuePair <PlayerTask, POGame> state, int player_id, int max_depth = 3)
            {
                int max_score = int.MinValue;

                if (max_depth > 0 && state.Value.CurrentPlayer.PlayerId == player_id)
                {
                    var subactions = state.Value.Simulate(state.Value.CurrentPlayer.Options()).Where(x => x.Value != null);

                    foreach (var subaction in subactions)
                    {
                        max_score = Math.Max(max_score, score(subaction, player_id, max_depth - 1).Value);
                    }
                }
                max_score = Math.Max(max_score, Score(state.Value, player_id));
                return(new KeyValuePair <PlayerTask, int>(state.Key, max_score));
            }
        }
            public override PlayerTask GetMove(POGame game)
            {
                var player = game.CurrentPlayer;

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

                var opponent = game.CurrentOpponent;
                var options  = player.Options();



                var validOpts = game.Simulate(options).Where(x => x.Value != null);
                var optcount  = validOpts.Count();

#if DEBUG
                /*
                 * var score_res = validOpts.Select(x => score(x, player.PlayerId, (optcount >= 5) ? ((optcount >= 25) ? 1 : 2) : 3)).OrderBy(x => x.Value);
                 *
                 * Console.WriteLine("Round Nr:" + Convert.ToString(game.Turn));
                 * Console.WriteLine("HeroHP: " + Convert.ToString(player.Hero.Health) + "\tOppHP: " + Convert.ToString(game.CurrentOpponent.Hero.Health));
                 * Console.WriteLine("HeroMinionHP: " + Convert.ToString(player.BoardZone.Sum(p => p.Health)) + "\tOppMinionHP: " + Convert.ToString(game.CurrentOpponent.BoardZone.Sum(p => p.Health)));
                 * Console.WriteLine("HeroMinionAtk: " + Convert.ToString(player.BoardZone.Sum(p => p.AttackDamage)) + "\tOppMinionAtk: " + Convert.ToString(game.CurrentOpponent.BoardZone.Sum(p => p.AttackDamage)));
                 * Console.WriteLine("HeroNbMinions: " + Convert.ToString(player.BoardZone.Count) + "\tOppMinionNB: " + Convert.ToString(game.CurrentOpponent.BoardZone.Count));
                 *
                 *
                 * foreach (var tmp_score in score_res)
                 *      {
                 *
                 *              Console.WriteLine(Convert.ToString(tmp_score.Key) + Convert.ToString(tmp_score.Value));
                 *      }
                 *      Console.WriteLine("-------------------------------------------------------");
                 * //PrintLog(game,  score_res);
                 */
#endif


                /*
                 * if (player.Hero.Health < DEFENSE_HEALTH_THRESHOLD * player.Hero.BaseHealth)
                 *      RuntimeScaling[0] += 0.1;
                 *
                 * if (opponent.Hero.Health < DEFENSE_HEALTH_THRESHOLD * opponent.Hero.Health)
                 *      RuntimeScaling[1] += 0.1;
                 */
                var opt1 = options.Where(x => x.HasSource && x.Source.Card.Name == "Reno Jackson");
                //if (opt1.Count() > 0 && (player.Hero.Health - opponent.Hero.AttackDamage - opponent.BoardZone.Sum(p => p.AttackDamage) <= 3 || player.Hero.Health<10))
                //if (opt1.Count() > 0 && (player.Hero.Health - opponent.Hero.AttackDamage - opponent.BoardZone.Sum(p => p.AttackDamage) <= 6 ))
                if (opt1.Count() > 0 && (player.Hero.Health - opponent.Hero.AttackDamage - opponent.BoardZone.Sum(p => p.AttackDamage) <= 3 || player.Hero.Health < 10))
                {
                    var tmp_game = game.getCopy();
                    //Reno Jackson has 6 mana

                    int mana = (tmp_game.CurrentPlayer.RemainingMana - 6) > 0 ? (tmp_game.CurrentPlayer.RemainingMana - 6) : 0;
                    //Console.WriteLine("mana " + Convert.ToString(tmp_game.CurrentPlayer.BaseMana));

                    var validOptsLoc = tmp_game.Simulate(options).Where(x => x.Value != null);
                    var optcountLoc  = validOptsLoc.Count();

                    var score_resLoc = validOptsLoc.Select(x => score(x, player.PlayerId, (optcountLoc >= 5) ? ((optcountLoc >= 25) ? 1 : 2) : 3)).Where(x => (x.Key.Source == null || x.Key.Source.Cost <= mana || x.Value == Int32.MaxValue)).Where(x => Convert.ToString(x.Key).Contains("Fireblast") != true || mana >= 1).OrderBy(x => x.Value);

                    /*Console.WriteLine("OPTS");
                     *
                     * foreach (var tmp_score in score_resLoc)
                     * {
                     *
                     *      Console.WriteLine(Convert.ToString(tmp_score.Key) + Convert.ToString(tmp_score.Value));
                     * }
                     * Console.WriteLine("-------------------------------------------------------");
                     *
                     * Console.WriteLine("Round Nr:" + Convert.ToString(game.Turn));
                     * Console.WriteLine("HeroHP: " + Convert.ToString(player.Hero.Health) + "\tOppHP: " + Convert.ToString(game.CurrentOpponent.Hero.Health));
                     * Console.WriteLine("HeroMinionHP: " + Convert.ToString(player.BoardZone.Sum(p => p.Health)) + "\tOppMinionHP: " + Convert.ToString(game.CurrentOpponent.BoardZone.Sum(p => p.Health)));
                     * Console.WriteLine("HeroMinionAtk: " + Convert.ToString(player.BoardZone.Sum(p => p.AttackDamage)) + "\tOppMinionAtk: " + Convert.ToString(game.CurrentOpponent.BoardZone.Sum(p => p.AttackDamage)));
                     * Console.WriteLine("HeroNbMinions: " + Convert.ToString(player.BoardZone.Count) + "\tOppMinionNB: " + Convert.ToString(game.CurrentOpponent.BoardZone.Count));
                     *
                     * //Console.WriteLine("OPTS:" + Convert.ToString(score_res.First()));
                     * //Console.WriteLine("OPTS:" + Convert.ToString(score_res.Last()));
                     * //Console.WriteLine("OPTS:" + Convert.ToString(score_res.Count()));
                     */

                    if (score_resLoc.Count() > 1)
                    {
                        //Console.WriteLine("OPTION TAKEN" + Convert.ToString(score_resLoc.Last().Key));

                        return(score_resLoc.Last().Key);
                    }


                    //Console.WriteLine("REEEEEEEEEEENNNNNNNNNNNOOOOOOOOOOOOOOO:" + Convert.ToString(player.Hero.Health));
                    //Console.WriteLine("OPTS:" + Convert.ToString(opt1.First()));
                    return(opt1.First());
                }

                var returnValue = validOpts.Any() ?
                                  validOpts.Select(x => score(x, player.PlayerId, (optcount >= 5) ? ((optcount >= 25) ? 1 : 2) : 3)).OrderBy(x => x.Value).Where(x => Convert.ToString(x.Key).Contains("Reno Jackson") != true).Last().Key :
                                  player.Options().First(x => x.PlayerTaskType == PlayerTaskType.END_TURN);

                return(returnValue);

                KeyValuePair <PlayerTask, int> score(KeyValuePair <PlayerTask, POGame> state, int player_id, int max_depth = 3)
                {
                    int max_score = int.MinValue;

                    if (max_depth > 0 && state.Value.CurrentPlayer.PlayerId == player_id)
                    {
                        var subactions = state.Value.Simulate(state.Value.CurrentPlayer.Options()).Where(x => x.Value != null);

                        foreach (var subaction in subactions)
                        {
                            max_score = Math.Max(max_score, score(subaction, player_id, max_depth - 1).Value);
                        }
                    }
                    max_score = Math.Max(max_score, Score(state.Value, player_id));
                    return(new KeyValuePair <PlayerTask, int>(state.Key, max_score));
                }
            }
예제 #10
0
        public override PlayerTask GetMove(POGame poGame)
        {
            Controller player = poGame.CurrentPlayer;

            // Implement a simple Mulligan Rule
            if (player.MulliganState == Mulligan.INPUT)
            {
                List <int> mulligan = new MidRangeScore().MulliganRule().Invoke(player.Choice.Choices.Select(p => poGame.getGame().IdEntityDic[p]).ToList());
                switch (poGame.CurrentPlayer.HeroClass)
                {
                case CardClass.SHAMAN: goto case CardClass.HUNTER;

                case CardClass.PALADIN: goto case CardClass.HUNTER;

                case CardClass.DRUID: goto case CardClass.HUNTER;

                case CardClass.HUNTER:
                    mulligan = new CustomMidrangeScoreHempel {
                        Controller = player
                    }.MulliganRule().Invoke(player.Choice.Choices.Select(p => poGame.getGame().IdEntityDic[p]).ToList());
                    weights = new double[3] {
                        1.0, 1.0, 1.0
                    };
                    break;

                case CardClass.ROGUE: goto case CardClass.WARRIOR;

                case CardClass.WARLOCK: goto case CardClass.WARRIOR;

                case CardClass.WARRIOR:
                    mulligan = new CustomAggroScoreHempel {
                        Controller = player
                    }.MulliganRule().Invoke(player.Choice.Choices.Select(p => poGame.getGame().IdEntityDic[p]).ToList());
                    weights = new double[3] {
                        1.0, 0.3, 0.7
                    };
                    break;

                case CardClass.PRIEST: goto case CardClass.MAGE;

                case CardClass.MAGE:
                    mulligan = new CustomScore {
                        Controller = player
                    }.MulliganRule().Invoke(player.Choice.Choices.Select(p => poGame.getGame().IdEntityDic[p]).ToList());
                    weights = new double[3] {
                        0.5, 1.0, 1.0
                    };
                    break;

                default:
                    mulligan = new CustomMidrangeScoreHempel {
                        Controller = player
                    }.MulliganRule().Invoke(player.Choice.Choices.Select(p => poGame.getGame().IdEntityDic[p]).ToList());
                    weights = new double[3] {
                        1.0, 1.0, 1.0
                    };
                    break;
                }
                return(ChooseTask.Mulligan(player, mulligan));
            }

            if (newTurn)
            {
                var tree = new Tree(poGame, weights);
                newTurn = false;
                tree.GetNext();
                TaskList = new Stack <PlayerTask>();
                TaskList = tree.BestEndNode.GetTaskList();
            }

            if (TaskList.Any())
            {
                return(TaskList.Pop());
            }
            else
            {
                newTurn = true;
                return(player.Options().FindLast(x => x.PlayerTaskType == PlayerTaskType.END_TURN) ?? player.Options().First());
            }
        }
예제 #11
0
        public ActionResult SaveCustomScores(string[] customScores)
        {
            if (customScores == null)
            {
                return(Json(new { message = "" }));
            }
            var idinterview   = Convert.ToInt32(customScores.GetValue(2));
            var idcampaign    = db.Interviews.Find(Convert.ToInt32(idinterview)).IdCampaign;
            var interviews    = db.Interviews.Where(i => i.IdCampaign == idcampaign && i.Deleted == false);
            var campaignscore = 0.0;
            var cs            = new CustomScore();
            var iduser        = User.Identity.GetUserId();
            var iscomment     = customScores.GetValue(3).ToString();
            var idnode        = Convert.ToInt32(customScores.GetValue(0));
            var value         = customScores.GetValue(1);
            var param         = new object[3];

            param[0] = iduser;
            param[1] = idinterview;
            param[2] = idnode;
            var found = db.CustomScores.Find(param);

            if (found != null)
            {
                if (iscomment == "False" && !string.IsNullOrEmpty(value.ToString())) // Score
                {
                    found.Value = Convert.ToInt32(value);
                }
                else if (!string.IsNullOrEmpty(value.ToString())) // Comment
                {
                    found.Comment = value.ToString();
                }
            }
            else
            {
                cs.IdNode      = idnode;
                cs.Id          = iduser;
                cs.IdInterview = idinterview;
                if (iscomment == "False") // Score
                {
                    cs.Value = Convert.ToInt32(value);
                }
                else // Comment
                {
                    cs.Comment = value.ToString();
                }
                db.CustomScores.Add(cs);
            }
            db.SaveChanges();

            // Campaign Score
            foreach (var interview in interviews)
            {
                campaignscore += GetWeightedAverage(interview.IdInterview);
            }
            if (interviews.Any())
            {
                campaignscore = campaignscore / interviews.Count();
                db.Campaigns.Find(idcampaign).Score = Convert.ToInt32(campaignscore);
                db.SaveChanges();
            }

            return
                (Json(new { average = GetWeightedAverage(idinterview), message = "Custom scores successfully saved !!!" }));
        }
예제 #12
0
        public ActionResult Saved(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            var campaign = db.Campaigns.Include(c => c.ApplicationUsers).Include(a => a.Customer).FirstOrDefault(c => c.IdCampaign == id);

            if (campaign != null)
            {
                ViewBag.Customer = db.Customers.Find(campaign.IdCustomer).Name;
            }

            var interviews = db.Interviews.Where(o => o.IdCampaign == id).Where(o => !o.Deleted);

            ViewBag.Interviews = interviews.ToList();
            //ViewBag.Questions = db.Questions.Where(w => w.IdQuestionnaire == campaign.IdQuestionnaire).ToList();
            var autoscore =
                db.Questionnaires.Where(q => q.IdQuestionnaire == campaign.IdQuestionnaire)
                .Select(q => q.AutoScore)
                .FirstOrDefault();

            if (autoscore)
            {
                var interviewsscores = interviews.ToList().Select(i => new Tuple <Interview.Interview, double>(i, Convert.ToDouble(i.Score)));
                ViewBag.InterviewsScores = interviewsscores;
            }
            else
            {
                var listinterviewsscores = interviews.ToList().Select(i => new Tuple <Interview.Interview, double>(i, GetWeightedAverage(i.IdInterview)));
                ViewBag.InterviewsScores = listinterviewsscores;
            }

            // Get all nodes of the campaign's questionnaire
            var fullnodes = db.Nodes.Where(x => x.IdQuestionnaire == campaign.IdQuestionnaire).ToList();
            // Get Sub-nodes
            List <Node> nodes = null;
            // Get Principal nodes
            List <Node> pnodes = null;

            ViewBag.lvl = false;
            if (fullnodes.Any())
            {
                var root = fullnodes.FirstOrDefault(r => r.IsRoot);
                if (root != null)
                {
                    nodes            = fullnodes.Where(n => !n.IsRoot && n.IdParentNode != root.IdNode).ToList();
                    pnodes           = fullnodes.FindAll(p => p.IdParentNode == root.IdNode).ToList();
                    ViewBag.RootNode = root.IdNode;
                }
                if (nodes != null && nodes.Any())
                {
                    ViewBag.lvl = true;
                }
            }

            ViewBag.Nodes  = nodes;
            ViewBag.PNodes = pnodes;

            /* Get chart data and building a list (List<Tuple>) that will be inject the data into the chart, also update scores */

            /* Variables declaration */
            var dbfu = new ApplicationDbContext();

            var groups =
                dbfu.CandidateCampaigns.Where(cc => cc.IdCampaign == campaign.IdCampaign).Select(cc => cc.Group).Distinct().ToList();

            ViewBag.Groups = groups.OrderBy(g => g.Name).ToList();
            var list      = new List <Tuple <string, string, double, int> >(); // Groupe name, Node name, Total, Times
            var radarList = new List <Tuple <string, string, double> >();      // Group name, Node name, Score
            var nodeList  = new List <Node>();
            var average   = 0.0;
            var total     = 0.0;

            /* Build chart data list (List<Tuple>) */
            foreach (var group in groups)
            {
                var tmp = dbfu.Interviewees.Include(i => i.Interview)
                          .Where(i => i.Interview.IdCampaign == id)
                          .Join(dbfu.CandidateCampaigns.Where(cc => cc.IdGroup == group.IdGroup), i => i.IdCandidate, cc => cc.IdCandidate, (interviewee, candidateCampaign) => interviewee.Interview)
                          .Distinct().ToList();
                var intrv = tmp.Where(i => !i.Deleted);
                foreach (var interview in intrv)
                {
                    List <Tuple <int, double> > sc = null;
                    if (autoscore)
                    {
                        sc = GetNodesScore(interview.IdInterview);
                    }

                    foreach (var node in pnodes)
                    {
                        /* Update scores or Add if not exists */
                        var current = sc.Find(x => x.Item1 == node.IdNode);
                        if (autoscore && sc != null && current != null)
                        {
                            var cs = new CustomScore
                            {
                                Id          = User.Identity.GetUserId(),
                                IdNode      = node.IdNode,
                                IdInterview = interview.IdInterview
                            };

                            var val = Convert.ToInt32(current.Item2);
                            cs.Value = val;

                            var param = new object[3];
                            param[0] = cs.Id;
                            param[1] = cs.IdInterview;
                            param[2] = cs.IdNode;
                            var currentcs = db.CustomScores.Find(param);

                            if (currentcs != null)
                            {
                                currentcs.Value = cs.Value;
                            }
                            else
                            {
                                dbfu.CustomScores.Add(cs);
                            }

                            dbfu.SaveChanges();
                        }

                        /* Get scores by group for the chart */
                        var score = dbfu.CustomScores.FirstOrDefault(c => c.IdNode == node.IdNode && c.IdInterview == interview.IdInterview);
                        if (score != null)
                        {
                            var candi = dbfu.Interviewees.Where(i => i.IdInterview == interview.IdInterview).Select(i => i.Candidate).FirstOrDefault();
                            if (candi != null)
                            {
                                var idgroup =
                                    dbfu.CandidateCampaigns.Where(
                                        cc => cc.IdCampaign == interview.IdCampaign && cc.IdCandidate == candi.IdCandidate).Select(cc => cc.IdGroup).FirstOrDefault();
                                var count = 1;
                                if (idgroup == group.IdGroup)
                                {
                                    average = score.Value;
                                    if (list.Any())
                                    {
                                        var cur = list.Find(x => x.Item1 == group.Name && x.Item2 == node.Name);
                                        if (cur != null)
                                        {
                                            average = cur.Item3 + score.Value;
                                            count  += cur.Item4;
                                            list.Remove(cur);
                                        }
                                    }
                                    var nodename = node.Name;
                                    if (nodename.Length > 25)
                                    {
                                        nodename  = nodename.Substring(0, 25);
                                        nodename += "...";
                                    }
                                    list.Add(new Tuple <string, string, double, int>(group.Name, nodename, average, count));
                                    if (!nodeList.Contains(node))
                                    {
                                        nodeList.Add(node);
                                    }
                                }
                            }
                        }
                    }
                }
                total += average;
            }
            foreach (var item in list)
            {
                var tmp = item.Item3;
                if (item.Item4 > 0)
                {
                    tmp = item.Item3 / item.Item4;
                }
                radarList.Add(new Tuple <string, string, double>(item.Item1, item.Item2, tmp));
            }
            //radarList = list.Select(item => new Tuple<string, string, double>(item.Item1, item.Item2, item.Item3 / item.Item4)).ToList();
            //radarList.Sort((x, y) => string.Compare(y.Item1, x.Item1, StringComparison.Ordinal));
            var radar = radarList.OrderBy(r => r.Item1).ThenBy(r => r.Item2).ToList();

            ViewBag.Radar = radar;

            /* Average from CustomScores of nodes */
            var nodescore = (from n in pnodes
                             let cs = db.CustomScores.Include(i => i.Interview)
                                      .Where(x => x.IdNode == n.IdNode && x.Interview.IdCampaign == id && !x.Interview.Deleted).ToList()
                                      where cs.Count > 0
                                      select Tuple.Create(n.Name, Math.Round(cs.Average(x => x.Value), 2))).ToList();

            var snodescore = (from n in nodes
                              let cs = db.CustomScores.Include(i => i.Interview)
                                       .Where(x => x.IdNode == n.IdNode && x.Interview.IdCampaign == id && !x.Interview.Deleted).ToList()
                                       where cs.Count > 0
                                       select Tuple.Create(n.Name, Math.Round(cs.Average(x => x.Value), 2))).ToList();

            nodescore.AddRange(snodescore);
            //var part = 0.0;
            //var ci = new ConductInterviewController();
            //foreach (var interview in interviews)
            //{
            //    part += ci.GetInterviewScore(interview.IdInterview);
            //}
            //ViewBag.Part = (part/interviews.Count()).ToString(CultureInfo.InvariantCulture);
            ViewBag.Nodescore     = nodescore;
            ViewBag.Questionnaire = db.Campaigns.Include(c => c.Questionnaire).Where(c => c.IdCampaign == id).Select(c => c.Questionnaire.Name).Single();
            ViewBag.NodeList      = new SelectList(nodeList.ToList(), "IdNode", "Name");
            return(View(campaign));
        }