public StrategyTree Create(ChanceTree playerChanceTree, ActionTree actionTree)
        {
            Creator c = new Creator {
                ActionTree = actionTree, PlayerChanceTree = playerChanceTree
            };

            // Start from 1 because the root is skipped.
            c.NodeCount = 1;
            c.Walk();
            c.StrategyTree = new StrategyTree(c.NodeCount);
            c.NodeCount    = 1;
            c.Walk();
            // Set root
            c.StrategyTree.SetDepth(0, 0);
            c.StrategyTree.Nodes[0].IsDealerAction = false;
            c.StrategyTree.Nodes[0].Position       = actionTree.Nodes[0].Position;
            c.StrategyTree.Nodes[0].Amount         = 0;
            c.StrategyTree.Nodes[0].Probab         = 0;

            c.StrategyTree.Version.Description = String.Format("Strategy tree from {0}, {1}",
                                                               actionTree.Version.Description,
                                                               playerChanceTree.Version.Description);

            return(c.StrategyTree);
        }
示例#2
0
        protected override bool OnNodeBeginFunc(UFToUniAdapter aTree, int aNode, List <VisActionTreeContext> stack, int depth)
        {
            VisActionTreeContext context = stack[depth];

            ActionTree tree = (ActionTree)(aTree.UfTree);

            context.Tree = tree;

            if (depth == 0)
            {
                context.State = new StrategicState(tree.PlayersCount);
            }
            else
            {
                context.State = stack[depth - 1].State.GetNextState(tree.Nodes[aNode]);
            }

            context.Id             = aNode.ToString();
            context.IsDealerAction = false;
            context.Position       = tree.Nodes[aNode].Position;
            context.Round          = tree.Nodes[aNode].Round;
            context.ActivePlayers  = tree.Nodes[aNode].ActivePlayers;
            context.ActionLabel    = depth == 0 ? "" : tree.Nodes[aNode].ToStrategicString(null);

            return(base.OnNodeBeginFunc(aTree, aNode, stack, depth));
        }
示例#3
0
    public void PlayEliminate(List <MonsterAnimInfo> monsterAnimss, ActionTree actionTree)
    {
        for (int j = 0; j < monsterAnimss.Count; j++)
        {
            OrderAction     order           = new OrderAction();
            MonsterAnimInfo monsterAnimInfo = monsterAnimss[j];

            FightMonsterItem item = GetItemByRunId(monsterAnimInfo.monsterInfo.runId);

            switch (monsterAnimInfo.animationType)
            {
            case CellAnimType.clear:
                order.AddNode(new ShowEffectActor(item.transform, "effect_cell_bomb", fightModule.transform));
                order.AddNode(new PlaySoundActor("remove"));
                order.AddNode(new ScaleActor((RectTransform)item.transform, new Vector3(0, 0, 0), 0.1f));
                order.AddNode(new DestroyActor(item.gameObject));
                break;

            case CellAnimType.wreck:
                order.AddNode(new ShowEffectActor(item.transform, "effect_cell_bomb", fightModule.transform));
                order.AddNode(new PlaySoundActor("remove"));
                order.AddNode(new ScaleActor((RectTransform)item.transform, new Vector3(0, 0, 0), 0.1f));
                //if (monsterAnimInfo.monsterInfo.IsNull())
                //{
                //    order.AddNode(new DestroyActor(item.gameObject));
                //}else
                //{
                order.AddNode(new ChangeMonsterActor(item, monsterAnimInfo.monsterInfo));
                //}
                break;
            }
            actionTree.AddNode(order);
        }
    }
示例#4
0
        static void Main(string[] args)
        {
            Tree <Student> student = new Tree <Student>(Tree <Student> .CompareFuncByMark);

            student.onAdd += ShowMessage;
            student.AddNodeRecursion(new Student("Sasha", "Epam", new DateTime(2019, 5, 5), -10));
            student.AddNodeRecursion(new Student("Sasha", "Epam", new DateTime(2019, 5, 5), 1));
            student.AddNodeRecursion(new Student("Sasha", "Epam", new DateTime(2019, 5, 5), -5));
            student.AddNodeRecursion(new Student("Sasha", "Epam", new DateTime(2019, 5, 5), 6));
            student.AddNodeRecursion(new Student("Sasha", "Epam", new DateTime(2019, 5, 5), -11));
            student.AddNodeRecursion(new Student("Sasha", "Epam", new DateTime(2019, 5, 5), 20));
            student.AddNodeRecursion(new Student("Sasha", "Epam", new DateTime(2019, 5, 5), -8));
            student.AddNodeRecursion(new Student("Sasha", "Epam", new DateTime(2019, 5, 5), 2));
            student.AddNodeRecursion(new Student("Sasha", "Epam", new DateTime(2019, 5, 5), -12));
            student.AddNodeRecursion(new Student("Sasha", "Epam", new DateTime(2019, 5, 5), 0));
            student.AddNodeRecursion(new Student("Sasha", "Epam", new DateTime(2019, 5, 5), -45));
            student.AddNodeRecursion(new Student("Sasha", "Epam", new DateTime(2019, 5, 5), 100));


            Console.WriteLine("Tree:");
            ActionTree.TreeAHeadDirectRecursion(student.root);
            Console.WriteLine("Count of Childrens:");
            student.onCount += ShowMessage;
            student.CountChildrens(student.root);

            Console.ReadKey();
        }
示例#5
0
    public void Flow(ActionTree actionTree)
    {
        FloorModel.Instance.Flow();

        List <FloorAnimInfo> anims = FloorModel.Instance.anims[0];

        for (int i = 0; i < anims.Count; i++)
        {
            FloorAnimInfo animInfo = anims[i];

            FightFloorItem item = GetItemByRunId(animInfo.floorInfo.runId);
            if (item != null)
            {
                ParallelAction paralle = new ParallelAction();

                Vector2 toPos = PosMgr.GetFightCellPos(animInfo.floorInfo.posX, animInfo.floorInfo.posY);
                paralle.AddNode(new MoveActor((RectTransform)item.transform, new Vector3(toPos.x, toPos.y, 0), 0, 0.3f));

                OrderAction orderAction = new OrderAction();

                orderAction.AddNode(new ScaleActor((RectTransform)item.transform, new Vector3(0.5f, 0.5f, 1), 0.1f));
                orderAction.AddNode(new WaitActor(100));
                orderAction.AddNode(new ScaleActor((RectTransform)item.transform, new Vector3(1, 1, 1), 0.1f));
                paralle.AddNode(orderAction);

                actionTree.AddNode(paralle);
            }
        }
    }
示例#6
0
 public void InitActionTreeCallback()
 {
     ActionTree.SuspendLayout();
     int selectedIndex = -1;
     if (ActionTree.SelectedNode != null)
         selectedIndex = ActionTree.Nodes.IndexOf(ActionTree.SelectedNode);
     ActionTree.Nodes.Clear();
     foreach (IPBComposite composite in PB.CurrentProfile.Branch.Children)
     {
         TreeNode node = new TreeNode(composite.Title);
         node.ForeColor = composite.Color;
         node.Tag = composite;
         if (composite is GroupComposite)
         {
             ActionTreeAddChildren((GroupComposite)composite, node);
         }
         ActionTree.Nodes.Add(node);
     }
     //ActionTree.ExpandAll();
     if (selectedIndex != -1)
     {
         if (selectedIndex < ActionTree.Nodes.Count)
             ActionTree.SelectedNode = ActionTree.Nodes[selectedIndex];
         else
             ActionTree.SelectedNode = ActionTree.Nodes[ActionTree.Nodes.Count - 1];
     }
     ActionTree.ResumeLayout();
 }
示例#7
0
    public void PlayEliminate(List <CoverAnimInfo> coverAnimss, ActionTree actionTree)
    {
        for (int j = 0; j < coverAnimss.Count; j++)
        {
            OrderAction   order         = new OrderAction();
            CoverAnimInfo coverAnimInfo = coverAnimss[j];

            FightCoverItem item = GetItemByRunId(coverAnimInfo.coverInfo.runId);

            switch (coverAnimInfo.animationType)
            {
            case CellAnimType.clear:
                order.AddNode(new ShowEffectActor(item.transform, "effect_cell_bomb", fightModule.transform));
                order.AddNode(new PlaySoundActor("remove"));
                order.AddNode(new ScaleActor((RectTransform)item.transform, new Vector3(0, 0, 0), 0.1f));
                order.AddNode(new DestroyActor(item.gameObject));
                break;

            case CellAnimType.wreck:
                order.AddNode(new ShowEffectActor(item.transform, "effect_cell_bomb", fightModule.transform));
                order.AddNode(new PlaySoundActor("remove"));
                order.AddNode(new ScaleActor((RectTransform)item.transform, new Vector3(0, 0, 0), 0.1f));
                order.AddNode(new ChangeCoverActor(this, item, coverAnimInfo.coverInfo));
                break;
            }
            actionTree.AddNode(order);
        }
    }
示例#8
0
        public void Solve(ActionTree at, HePocketKind[] sbCards, HePocketKind[] bbCards)
        {
            Ct = CreateCt(sbCards, bbCards);
            var gv = new double[2];

            Strategies = EqLp.Solve(at, Ct, out gv);
            GameValues = gv;
        }
示例#9
0
        protected override void OnTreeBeginFunc(UFToUniAdapter aTree, int aRoot)
        {
            ActionTree tree = (ActionTree)(aTree.UfTree);

            GraphAttributes.label    = tree.Version.Description;
            GraphAttributes.fontsize = 20;
            base.OnTreeBeginFunc(aTree, aRoot);
        }
        public void Test_LeducHe()
        {
            _gd = XmlSerializerExt.Deserialize <GameDefinition>(
                Props.Global.Expand("${bds.DataDir}ai.pkr.metastrategy/leduc-he.gamedef.xml"));
            ActionTree tree = CreateActionTreeByGameDef.Create(_gd);

            VerifyActionTree(tree, _expLeducHe);
        }
示例#11
0
        private static void ProcessGameContext(GameContext context)
        {
            int            nodeId = context.Global.NodeId++;
            GameDefinition gd     = context.Global.GameDef;
            ActionTree     tree   = context.Global.Tree;

            // Store it before we possible change the state to skip dealer actions.
            int lastActor = context.GameState.LastActor;
            int round     = context.GameState.Round;

            while (!context.GameState.IsGameOver && context.GameState.IsDealerActing)
            {
                List <Ak> kinds = context.GameState.GetAllowedActions(gd);
                foreach (Ak kind in kinds)
                {
                    PokerAction action = new PokerAction
                    {
                        Kind     = kind,
                        Position = context.GameState.CurrentActor
                    };
                    context.GameState.UpdateByAction(action, gd);
                }
            }

            if (tree != null)
            {
                tree.SetDepth(nodeId, (byte)context.Depth);
                tree.Nodes[nodeId].Position      = lastActor;
                tree.Nodes[nodeId].Amount        = context.Amount;
                tree.Nodes[nodeId].ActivePlayers = context.GameState.GetActivePlayers();
                tree.Nodes[nodeId].Round         = round;
            }

            if (context.GameState.IsGameOver)
            {
                return;
            }

            // Deal next cards.
            List <Ak> actions = context.GameState.GetAllowedActions(gd);

            foreach (Ak actionKind in actions)
            {
                GameContext childContext = new GameContext(context);
                childContext.Depth++;
                int         position = context.GameState.CurrentActor;
                PokerAction a        = new PokerAction(actionKind, position, 0, "");
                if (a.Kind == Ak.r)
                {
                    a.Amount = gd.BetStructure[context.GameState.Round];
                }
                childContext.GameState.UpdateByAction(a, gd);
                childContext.Amount = childContext.GameState.Players[position].InPot -
                                      context.GameState.Players[position].InPot;
                ProcessGameContext(childContext);
                context.ChildCount += childContext.ChildCount + 1;
            }
        }
示例#12
0
        public static StrategyTree CreateStrategyTree(GameDefinition gd, int pos)
        {
            ChanceTree   ct  = CreateChanceTreeByGameDef.Create(gd);
            ChanceTree   pct = ExtractPlayerChanceTree.ExtractS(ct, 0);
            ActionTree   at  = CreateActionTreeByGameDef.Create(gd);
            StrategyTree st  = CreateStrategyTreeByChanceAndActionTrees.CreateS(pct, at);

            return(st);
        }
示例#13
0
 public void InitActionTree()
 {
     if (!IsValid)
         return;
     if (ActionTree.InvokeRequired)
         ActionTree.BeginInvoke(new guiInvokeCB(InitActionTreeCallback));
     else
         InitActionTreeCallback();
 }
示例#14
0
        void Initialize()
        {
            DateTime startTime = DateTime.Now;

            _at = ActionTree.Read <ActionTree>(ActionTreeFile);
            if (IsVerbose)
            {
                Console.WriteLine("Action tree: {0}", _at.Version.ToString());
            }
            _init             = new InitData(this);
            _playersCount     = _at.PlayersCount;
            _epsilonLog       = new List <EpsilonLogEntry>();
            _snapshotSwitcher = new SnapshotSwitcher(OutputPath, GetSnapshotHeaderFileName(), SnapshotsCount);
            _curSnapshotInfo  = new SnapshotInfo(_snapshotSwitcher.CurrentSnapshotPath, _playersCount);
            IterationCounts   = new int[_playersCount];
            LastBrValues      = new double[_playersCount];
            _ptExt            = new Node[_playersCount][];

            _rng       = new System.Random(RngSeed);
            _mcDealer  = new McDealer(GameDef, _rng);
            _hands     = new int[_playersCount][].Fill(i => new int[_mcDealer.HandSize]);
            _handSizes = GameDef.GetHandSizes();
            _oppGv     = new double[_at.NodesCount];

            bool isNewSnapshot = !_snapshotSwitcher.IsSnapshotAvailable;

            if (isNewSnapshot)
            {
                CreateNewSnapshot();
            }
            //LoadSnapshot();

            CreatePlayerTrees();

            for (int p = 0; p < _playersCount; ++p)
            {
                if (TraceDir != null)
                {
                    Vis.Show(this, p, GetTraceFileName(p, "tree", "init-pt", "gv"));
                }
            }
            if (TraceDir != null)
            {
                VisChanceTree.Show(_init.PlayerCt, GetTraceFileName(0, "pct", "", "gv"));
            }

            PrintInitDone();

            // Clean-up
            _init = null;
            double time = (DateTime.Now - startTime).TotalSeconds;

            if (IsVerbose)
            {
                Console.WriteLine("Initialization done in {0:0.0} s", time);
            }
        }
示例#15
0
 private void RefreshActionTreeCallback(IPBComposite pbComp, Type type)
 {
     ActionTree.SuspendLayout();
     foreach (TreeNode node in ActionTree.Nodes)
     {
         UdateTreeNode(node, pbComp, type, true);
     }
     ActionTree.ResumeLayout();
 }
示例#16
0
 public static void Show(ActionTree t, string fileName)
 {
     using (TextWriter w = new StreamWriter(File.Open(fileName, FileMode.Create)))
     {
         VisActionTree vis = new VisActionTree {
             Output = w
         };
         vis.Show(t);
     }
 }
示例#17
0
 /// <summary>
 /// Refreshes all actions of specified type in ActionTree or all if type is null
 /// </summary>
 /// <param name="type"></param>
 public void RefreshActionTree(IPBComposite pbComp, Type type)
 {
     // Don't update ActionTree while PB is running to improve performance.
     if (PB.IsRunning || !IsValid)
         return;
     if (ActionTree.InvokeRequired)
         ActionTree.BeginInvoke(new refreshActionTreeDelegate(RefreshActionTreeCallback), pbComp, type);
     else
         RefreshActionTreeCallback(pbComp, type);
 }
示例#18
0
        /// <summary>
        /// Runs FictitiousPlay with the specified parameters.
        /// Some parameters are set by default (e.g. verbosity), the caller has a chance to overwrite them
        /// using Configure delegate.
        /// </summary>
        public StrategyTree[] Solve(ActionTree at, ChanceTree ct)
        {
            int playersCount = 2;

            DirectoryExt.Delete(BaseDir);
            Directory.CreateDirectory(BaseDir);

            string inputDir = Path.Combine(BaseDir, "input");

            Directory.CreateDirectory(inputDir);
            string traceDir = Path.Combine(BaseDir, "trace");

            string chanceTreeFile = Path.Combine(inputDir, "ct.dat");
            string actionTreeFile = Path.Combine(inputDir, "at.dat");

            ct.Write(chanceTreeFile);
            at.Write(actionTreeFile);

            if (VisualizeTrees)
            {
                VisActionTree.Show(at, actionTreeFile + ".gv");
                VisChanceTree.Show(ct, chanceTreeFile + ".gv");
            }

            Solver.ChanceTreeFile     = chanceTreeFile;
            Solver.EqualCa            = false;
            Solver.ActionTreeFile     = actionTreeFile;
            Solver.OutputPath         = BaseDir;
            Solver.SnapshotsCount     = 2;
            Solver.Epsilon            = Epsilon;
            Solver.ThreadsCount       = 6;
            Solver.IsVerbose          = true;
            Solver.IterationVerbosity = 10000;
            Solver.MaxIterationCount  = 1000000000;

            if (Configure != null)
            {
                Configure(Solver);
            }
            Solver.Solve();

            StrategyTree[] eqStrategies = new StrategyTree[playersCount];

            for (int p = 0; p < playersCount; ++p)
            {
                string fileName = Solver.CurrentSnapshotInfo.StrategyFile[p];
                eqStrategies[p] = StrategyTree.Read <StrategyTree>(fileName);
                if (VisualizeTrees)
                {
                    VisStrategyTree.Show(eqStrategies[p], fileName + ".gv");
                }
            }

            return(eqStrategies);
        }
示例#19
0
        private long FindActionTreeNodeIdx(StrategyTree tree, long sNodeIdx, long aNodeIdx, int hintChildIdx)
        {
            long actionTreeIdx = ActionTree.FindChildByAmount(aNodeIdx,
                                                              tree.Nodes[sNodeIdx].Amount, _actionTreeIndex, hintChildIdx);

            if (actionTreeIdx == -1)
            {
                throw new ApplicationException(String.Format("Cannot find action tree node, strategy node {0}", sNodeIdx));
            }
            return(actionTreeIdx);
        }
示例#20
0
        /// <summary>
        /// This functions simulate a typical use case: create trees in many runs of MC sampling, write them, read again
        /// and merge into the master tree. The master tree is than verified.
        /// </summary>
        private void GenerateAndVerifyCT(string name, GameDefinition gd, IChanceAbstraction[] chanceAbstractions, bool areAbstractionsEqual, int samplesCount, int runsCount, double avRelProbabEps, double avPotShareEps, double eqValEps, bool visualize)
        {
            CtMcGen.Tree masterTree = new CtMcGen.Tree();

            int rngSeed = (int)DateTime.Now.Ticks;

            for (int run = 0; run < runsCount; ++run)
            {
                CtMcGen.Tree runTree  = CtMcGen.Generate(gd, chanceAbstractions, areAbstractionsEqual, samplesCount, rngSeed, null);
                string       fileName = Path.Combine(_outDir, String.Format("{0}-{1}-ct.dat", gd.Name, name));
                runTree.Write(fileName);
                masterTree.Read(fileName);

                // Do not use the timer anymore because the tests are too fast.
                rngSeed++;
            }

            ChanceTree actCt = masterTree.ConvertToChanceTree();

            VisChanceTree.Show(actCt, Path.Combine(_outDir, String.Format("{0}-{1}-ct.gv", gd.Name, name)));
            VerifyChanceTree.VerifyS(actCt);
            ChanceTree expCt = CreateChanceTreeByAbstraction.CreateS(gd, chanceAbstractions);

            Assert.AreEqual(expCt.PlayersCount, actCt.PlayersCount);
            CompareChanceTrees cmp = new CompareChanceTrees();

            cmp.IsVerbose = visualize;
            cmp.Output    = Console.Out;
            cmp.Compare(expCt, actCt);
            VisChanceTree.Show(expCt, Path.Combine(_outDir, String.Format("{0}-{1}-ct-exp.gv", gd.Name, name)));
            Assert.Less(cmp.AverageRelProbabDiff, avRelProbabEps);
            for (int p = 0; p < chanceAbstractions.Length; ++p)
            {
                Assert.Less(cmp.AveragePotShareDiff[p], avRelProbabEps);
            }

            ActionTree at = CreateActionTreeByGameDef.Create(gd);

            double [] actEqValues, expEqValues;
            EqLp.Solve(at, actCt, out actEqValues);
            EqLp.Solve(at, expCt, out expEqValues);
            for (int p = 0; p < chanceAbstractions.Length; ++p)
            {
                if (visualize)
                {
                    Console.WriteLine("Eq pos: {0} exp: {1} act: {2}", p, expEqValues[p], actEqValues[p]);
                }
                Assert.AreEqual(expEqValues[p], actEqValues[p], eqValEps);
            }
            if (visualize)
            {
                Console.WriteLine();
            }
        }
示例#21
0
 public void PlayEliminate(List <FloorAnimInfo> floorAnimss, ActionTree actionTree)
 {
     for (int j = 0; j < floorAnimss.Count; j++)
     {
         OrderAction    order         = new OrderAction();
         FloorAnimInfo  floorAnimInfo = floorAnimss[j];
         FightFloorItem item          = GetItemByRunId(floorAnimInfo.floorInfo.runId);
         order.AddNode(new ScaleActor((RectTransform)item.transform, new Vector3(0, 0, 0), 0.1f));
         order.AddNode(new DestroyActor(item.gameObject));
         actionTree.AddNode(order);
     }
 }
示例#22
0
        public static ActionTree Create(GameDefinition gd)
        {
            // First pass - count nodes.
            GlobalContext gc = new GlobalContext {
                GameDef = gd
            };
            GameContext root = new GameContext {
                GameState = new GameState(gd), Global = gc
            };

            ProcessGameContext(root);
            // Create the tree, adding actions for blinds
            int        nodeCount = root.ChildCount + 1 + gd.MinPlayers;
            ActionTree tree      = new ActionTree(nodeCount);

            // Second pass - initialize nodes.
            gc.Tree = tree;

            // Start from the last blind node
            gc.NodeId  = gd.MinPlayers;
            root.Depth = gd.MinPlayers;

            ProcessGameContext(root);

            // Now fill the root and blind nodes (overwriting the last one, because it is wrong).

            gc.NodeId  = 0;
            root.Depth = 0;

            // Set data for root.
            tree.SetDepth(gc.NodeId, (byte)root.Depth++);
            tree.Nodes[gc.NodeId].Position      = gd.MinPlayers;
            tree.Nodes[gc.NodeId].Amount        = 0;
            tree.Nodes[gc.NodeId].ActivePlayers = root.GameState.GetActivePlayers();
            tree.Nodes[gc.NodeId].Round         = -1;

            gc.NodeId++;

            // Set data for blinds
            for (int p = 0; p < gd.MinPlayers; ++p)
            {
                tree.SetDepth(gc.NodeId, (byte)root.Depth++);
                tree.Nodes[gc.NodeId].Position      = p;
                tree.Nodes[gc.NodeId].Amount        = root.GameState.Players[p].InPot;
                tree.Nodes[gc.NodeId].ActivePlayers = root.GameState.GetActivePlayers();
                tree.Nodes[gc.NodeId].Round         = -1;
                gc.NodeId++;
            }

            tree.Version.Description = String.Format("Action tree (gamedef: {0})", gd.Name);

            return(tree);
        }
            public TestParams(FictitiousPlayMc_Test test, string gameDefFile,
                              IChanceAbstraction chanceAbstr, int [] cardCount, double epsilon)
            {
                Epsilon           = epsilon;
                GameDef           = XmlSerializerExt.Deserialize <GameDefinition>(Props.Global.Expand("${bds.DataDir}ai.pkr.metastrategy/${0}", gameDefFile));
                Name              = chanceAbstr.Name;
                ChanceAbstraction = chanceAbstr;

                ActionTree = CreateActionTreeByGameDef.Create(GameDef);
                Debug.Assert(GameDef.MinPlayers == 2);
                ChanceTree = CreateChanceTreeByAbstraction.CreateS(GameDef, new IChanceAbstraction[] { chanceAbstr, chanceAbstr });
                CardCount  = cardCount;
            }
 private unsafe void VerifyActionTree(ActionTree tree, VerificationData[] expected)
 {
     Assert.AreEqual(tree.PlayersCount, _gd.MinPlayers);
     Assert.AreEqual(expected.Length, tree.NodesCount);
     for (int i = 0; i < tree.NodesCount; ++i)
     {
         Assert.AreEqual(expected[i].Depth, tree.GetDepth(i), String.Format("Node id {0}", i));
         Assert.AreEqual(expected[i].Position, tree.Nodes[i].Position, String.Format("Node id {0}", i));
         Assert.AreEqual(expected[i].Amount, tree.Nodes[i].Amount, String.Format("Node id {0}", i));
         Assert.AreEqual(expected[i].Round, tree.Nodes[i].Round, String.Format("Node id {0}", i));
         Assert.AreEqual(expected[i].ActivePlayers, tree.Nodes[i].ActivePlayers, String.Format("Node id {0}", i));
     }
 }
示例#25
0
        static int Main(string[] args)
        {
            if (!Parser.ParseArgumentsWithUsage(args, _cmdLine))
            {
                return(1);
            }

            if (_cmdLine.DebuggerLaunch)
            {
                Debugger.Launch();
            }

            GameDefinition gd = XmlSerializerExt.Deserialize <GameDefinition>(_cmdLine.GameDef.Get(Props.Global));

            string     chanceTreeFile = _cmdLine.ChanceTree.Get(Props.Global);
            ChanceTree ct;

            if (string.IsNullOrEmpty(chanceTreeFile))
            {
                ct = CreateChanceTreeByGameDef.Create(gd);
            }
            else
            {
                ct = ChanceTree.Read <ChanceTree>(chanceTreeFile);
            }

            ActionTree at = CreateActionTreeByGameDef.Create(gd);

            double []       values;
            StrategyTree [] st = EqLp.Solve(at, ct, out values);
            if (st == null)
            {
                Console.WriteLine("Cannot find solution");
                return(1);
            }
            string output   = _cmdLine.Output.Get(Props.Global);
            string basePath = string.IsNullOrEmpty(output) ? gd.Name : output;
            string baseDir  = Path.GetDirectoryName(basePath);
            string baseName = Path.GetFileNameWithoutExtension(basePath);

            for (int p = 0; p < st.Length; ++p)
            {
                string fileName = Path.Combine(baseDir, string.Format("{0}-{1}.dat", baseName, p));
                Console.WriteLine("Eq value pos {0}: {1}, file: {2}", p, values[p], fileName);
                st[p].Write(fileName);
            }



            return(0);
        }
示例#26
0
        /// <summary>
        /// Solves a game for one position. If solution is found, returns it, otherwise returns null.
        /// </summary>
        public static StrategyTree Solve(ActionTree at, ChanceTree ct, int heroPos, out double value)
        {
            EqLp solver = new EqLp {
                ChanceTree = ct, ActionTree = at, HeroPosition = heroPos
            };

            solver.Solve();
            value = solver.Value;
            if (!solver.IsLpSolutionFound)
            {
                return(null);
            }
            return(solver.Strategy);
        }
示例#27
0
 /// <summary>
 /// Solves a game for all positions. If solution for all positions is found, returns it, otherwise returns null.
 /// </summary>
 public static StrategyTree[] Solve(ActionTree at, ChanceTree ct, out double[] values)
 {
     StrategyTree [] strategies = new StrategyTree[2];
     values = new double[2];
     for (int heroPos = 0; heroPos < 2; ++heroPos)
     {
         strategies[heroPos] = Solve(at, ct, heroPos, out values[heroPos]);
         if (strategies[heroPos] == null)
         {
             return(null);
         }
     }
     return(strategies);
 }
示例#28
0
        private static void CreateOppActionTree()
        {
            Console.WriteLine("Creating new Opponent action tree from game def: {0} ...", _cmdLine.gameDef);

            _oppActionTree = new ActionTree(_gameDef, _bucketizer);

            _oppActionTree.Build();
            Console.WriteLine("Opponent action tree created.");

            // Workaround for disabled Assert dialog
            DefaultTraceListener trListener = (DefaultTraceListener)Debug.Listeners[0];

            trListener.AssertUiEnabled = true;
        }
示例#29
0
 public void InitActionTree()
 {
     if (!IsValid)
     {
         return;
     }
     if (ActionTree.InvokeRequired)
     {
         ActionTree.BeginInvoke(new GuiInvokeCB(InitActionTreeCallback));
     }
     else
     {
         InitActionTreeCallback();
     }
 }
示例#30
0
        public void Test_LeducHe()
        {
            GameDefinition gd = XmlSerializerExt.Deserialize <GameDefinition>(
                Props.Global.Expand("${bds.DataDir}ai.pkr.metastrategy/leduc-he.gamedef.xml"));

            ActionTree ct = CreateActionTreeByGameDef.Create(gd);

            using (TextWriter w = new StreamWriter(File.Open(Path.Combine(_outDir, "leduc-at.gv"), FileMode.Create)))
            {
                VisActionTree vis = new VisActionTree {
                    Output = w
                };
                vis.Show(ct);
            }
        }