Exemple #1
0
        static void Main(string[] args)
        {
            string inputname = args[0];
            string outputname = args[1];

            string[] lines = File.ReadAllLines(inputname);

            int ncases = int.Parse(lines[0]);
            int nline = 0;
            IList<string> results = new List<string>();

            for (int k = 0; k < ncases; k++)
            {
                System.Console.WriteLine(string.Format("Solving Case #{0}", k + 1));
                nline++;
                string[] numbers = lines[nline].Split(' ');
                int maximum = int.Parse(numbers[0]);
                int reload = int.Parse(numbers[1]);
                nline++;
                numbers = lines[nline].Split(' ');
                List<int> nums = new List<int>();

                foreach (var number in numbers)
                    nums.Add(int.Parse(number));

                Planner planner = new Planner(maximum, reload);
                var result = planner.Run(nums);
                results.Add(string.Format("Case #{0}: {1}", k + 1, result));
            }

            File.WriteAllLines(outputname, results.ToArray());
        }
Exemple #2
0
 public WorkProvider(BotAvatar avatar, WorkflowProvider provider, WorkAgent workAgent, Planner<WorkItem> planner)
 {
     _avatar = avatar;
     _workflow = provider;
     _workAgent = workAgent;
     _planner = planner;
 }
 void Awake()
 {
     goalIndex = 0;
     planner = new Planner();
     goals = new List<WorldState>();
     buildingGroup = new GameObject();
     planList = new List<TreeNode>();
 }
        void OnEntityBuilt(Planner planner, UnityEngine.GameObject component)
        {
            ItemDefinition item = planner.GetOwnerItemDefinition();

            if (item.shortname == "mining.quarry")
            {
                updateQuarries();
            }
        }
Exemple #5
0
        public void GooglePlanner2Run()
        {
            Planner planner = new Planner(3, 1);

            Assert.AreEqual(1, planner.Decide(3, 1, 2));
            Assert.AreEqual(1, planner.Decide(3, 2, 3));
            Assert.AreEqual(3, planner.Decide(3, 3, 2));
            Assert.AreEqual(1, planner.Decide(1, 2, 1));
            Assert.AreEqual(15, planner.Run(new int[] { 1, 2, 3, 2, 1 }));
        }
 void OnEntityBuilt(Planner planner, GameObject gameObject)
 {
     cachedBlock = gameObject.GetComponent<BuildingBlock>();
     if (cachedBlock == null) return;
     if (cachedBlock.blockDefinition == null) return;
     if (cachedBlock.blockDefinition.fullName != "build/block.halfheight") return;
     cachedBlock.GetComponentInChildren<MeshCollider>().gameObject.AddComponent<TriggerBase>();
     cachedBlock.GetComponentInChildren<TriggerBase>().gameObject.layer = triggerLayer;
     cachedBlock.GetComponentInChildren<TriggerBase>().interestLayers = playerMask;
     timer.Once(0.1f, () => ResetBlock(cachedBlock) );
 }
Exemple #7
0
        public void GooglePlanner4Run()
        {
            Planner planner = new Planner(5, 1);

            Assert.AreEqual(1, planner.Decide(5, new int[] { 8, 9, 7, 1, 2, 9, 10, 8, 7, 10}));
            Assert.AreEqual(5, planner.Decide(5, new int[] { 9, 7, 1, 2, 9, 10, 8, 7, 10 }));
            Assert.AreEqual(0, planner.Decide(1, new int[] { 7, 1, 2, 9, 10, 8, 7, 10 }));
            Assert.AreEqual(0, planner.Decide(2, new int[] { 1, 2, 9, 10, 8, 7, 10 }));
            Assert.AreEqual(0, planner.Decide(3, new int[] { 2, 9, 10, 8, 7, 10 }));
            Assert.AreEqual(0, planner.Decide(4, new int[] { 9, 10, 8, 7, 10 }));
            Assert.AreEqual(5, planner.Decide(5, new int[] { 10, 8, 7, 10 }));
        }
Exemple #8
0
    // Use this for initialization
    //public void Init (FootstepPlanningTest planner, SteeringManager steeringManager, AnimationAnalyzer analyzer, NeighbourAgents agents, NeighbourObstacles obstacles, RootMotionComputer computer) {
    public void Init(Planner planner, SteeringManager steeringManager, AnimationAnalyzer analyzer, NeighbourAgents agents, NeighbourObstacles obstacles)
    {
        steering = steeringManager;

        planning = planner;
        if (planning != null && !planning.initialized)
            planning.Init(analyzer, agents, obstacles);

        navMeshLayer = 1 << LayerMask.NameToLayer("StaticWorld");

        initialized = true;
    }
Exemple #9
0
        public void GooglePlanner3Run()
        {
            Planner planner = new Planner(5, 1);

            Assert.AreEqual(1, planner.Decide(5, 1, 10));
            Assert.AreEqual(5, planner.Decide(5, 10, 2));
            Assert.AreEqual(0, planner.Decide(1, 2, 9));
            Assert.AreEqual(2, planner.Decide(2, 9, 3));
            Assert.AreEqual(0, planner.Decide(1, 3, 8));
            Assert.AreEqual(2, planner.Decide(2, 8, 4));
            Assert.AreEqual(0, planner.Decide(1, 4, 7));
            Assert.AreEqual(2, planner.Decide(2, 7, 5));
            Assert.AreEqual(0, planner.Decide(1, 5, 6));
        }
Exemple #10
0
    //public void Init(AnimationAnalyzer analyzer, FootstepPlanningTest planner,
    public void Init(AnimationAnalyzer analyzer, Planner planner, 
	                 AnimationEngine animEngine, CollisionReaction collisionReact, 
	                 NavMeshWayPoints navMeshWaypoints, SteeringManager steering,
	                 NeighbourAgents agents, NeighbourObstacles obstacles,
	                 PlaceFootSteps steps)
    {
        planning = planner;
        if (planning != null && !planning.initialized)
            planning.Init(analyzer,agents,obstacles);

        engine = animEngine;
        if (engine != null && !engine.initialized)
            engine.Init(analyzer,planning,agents,obstacles);

        collision = collisionReact;
        if (collision != null && !collision.initialized)
            collision.Init(analyzer,planner,engine,agents,obstacles);

        waypoints = navMeshWaypoints;
        //if (waypoints != null && !waypoints.initialized)
        //	waypoints.Init(planning,steering,analyzer,agents,obstacles);

        neighborhood = agents;
        if (neighborhood != null && !neighborhood.initialized)
            neighborhood.Init();

        footsteps = steps;
        if (footsteps != null && !footsteps.initiated)
            footsteps.Init(analyzer,planner,engine,neighborhood,obstacles);

        nObstacles = obstacles;
        if (nObstacles != null && !nObstacles.initialized)
            nObstacles.Init();

        timeSinceLastPlan = 0;
        timeSinceLastWaypoints = 0;

        previousGoalPosition = planning.goalStateTransform.position;
        previousCurrentGoalPosition = planning.currentGoal;

        previousActionsSinceLastPlan = -1;

        newWaypoint = false;

        initialized = true;
    }
Exemple #11
0
    //public void Init (AnimationAnalyzer animAnalyzer, AnimationEngine animEngine, FootstepPlanningTest planner,
    public void Init(AnimationAnalyzer animAnalyzer, AnimationEngine animEngine, Planner planner,
	                  NeighbourAgents agents, NeighbourObstacles obstacles, CollisionReaction colReact)
    {
        analyzer = animAnalyzer;
        if (analyzer != null && !analyzer.initialized)
            analyzer.Init();

        planning = planner;
        if (planning != null && !planning.initialized)
            planning.Init(analyzer, agents, obstacles);

        engine = animEngine;
        if (engine != null && !engine.initialized)
            engine.Init(analyzer,planning,agents,obstacles);

        collision = colReact;
        if (collision != null && !collision.initialized)
            collision.Init(analyzer,planning,engine,agents,obstacles);

        if (debugText != null)
            debugText.gameObject.active = false;

        initialized = true;
    }
Exemple #12
0
        private void OnEntityBuilt(Planner planner, GameObject go)
        {
            BasePlayer basePlayer = planner?.GetOwnerPlayer();

            if (basePlayer == null)
            {
                return;
            }

            IPlayer player = basePlayer.IPlayer;

            if (player == null || player.HasPermission(permBypass))
            {
                return;
            }

            BaseEntity    entity        = go.ToBaseEntity();
            BuildingBlock buildingBlock = entity?.GetComponent <BuildingBlock>();

            if (buildingBlock == null)
            {
                return;
            }

#if DEBUG
            player.Message($"Water depth from base block: {buildingBlock.WaterFactor()}");
            player.Message($"Maximum water depth: {config.MaxWaterDepth}");
#endif
            if (config.RestrictWaterDepth && buildingBlock.WaterFactor() >= config.MaxWaterDepth)
            {
                if (config.RefundResources)
                {
                    RefundResources(basePlayer, buildingBlock);
                }

                buildingBlock.Kill(BaseNetworkable.DestroyMode.Gib);
                Message(player, "MaxWaterDepth", config.MaxWaterDepth);
                return;
            }

            string blockName  = buildingBlock.PrefabName;
            uint   buildingId = buildingBlock.buildingID;
            if (buildingIds.ContainsKey(buildingId))
            {
                List <BuildingBlock> connectingStructure = buildingIds[buildingBlock.buildingID];
                if (config.RestrictFoundations && blockName == foundation || blockName == triFoundation)
                {
                    int foundationCount    = GetCountOf(connectingStructure, foundation);
                    int triFoundationCount = GetCountOf(connectingStructure, triFoundation);
#if DEBUG
                    player.Message($"Foundation count: {foundationCount}");
                    player.Message($"Triangle foundation count: {triFoundationCount}");
#endif

                    if (blockName == foundation && foundationCount > config.MaxFoundations)
                    {
                        if (config.RefundResources)
                        {
                            RefundResources(basePlayer, buildingBlock);
                        }

                        buildingBlock.Kill(BaseNetworkable.DestroyMode.Gib);
                        Message(player, "MaxFoundations", config.MaxFoundations);
                    }
                    else if (blockName == triFoundation && triFoundationCount > config.MaxTriFoundations)
                    {
                        if (config.RefundResources)
                        {
                            RefundResources(basePlayer, buildingBlock);
                        }

                        buildingBlock.Kill(BaseNetworkable.DestroyMode.Gib);
                        Message(player, "MaxTriFoundations", config.MaxTriFoundations);
                    }
                    else
                    {
                        List <BuildingBlock> structure = new List <BuildingBlock>(connectingStructure)
                        {
                            buildingBlock
                        };
                        buildingIds[buildingId] = structure;
                    }
                }
                else
                {
                    if (config.RestrictBuildHeight && !allowedBuildingBlocks.Contains(blockName))
                    {
                        BuildingBlock firstFoundation = null;
                        foreach (BuildingBlock block in connectingStructure)
                        {
                            if (block.name.Contains(triFoundation) || block.name.Contains(foundation))
                            {
                                firstFoundation = block;
                                break;
                            }
                        }

                        if (firstFoundation != null)
                        {
                            float height    = (float)Math.Round(buildingBlock.transform.position.y - firstFoundation.transform.position.y, 0, MidpointRounding.AwayFromZero);
                            int   maxHeight = config.MaxBuildHeight * 3;
#if DEBUG
                            player.Message($"Maximum building height: {maxHeight}");
                            player.Message($"Attempted building height: {height}");
#endif

                            if (height > maxHeight)
                            {
                                if (config.RefundResources)
                                {
                                    RefundResources(basePlayer, buildingBlock);
                                }

                                buildingBlock.Kill(BaseNetworkable.DestroyMode.Gib);
                                Message(player, "MaxBuildHeight", config.MaxBuildHeight);
                            }
                        }
                    }
                }
            }
            else
            {
                List <BuildingBlock> structure = new List <BuildingBlock> {
                    buildingBlock
                };
                buildingIds[buildingId] = structure;
            }
        }
 public Player()
 {
     _planner = new Planner <AIContext>();
     _context = new AIContext(this);
     _context.Init();
 }
 public override void Init(Planner p)
 {
     base.Init(p);
     DoEffect();
 }
Exemple #15
0
    //
    // Public Methods
    //

    public PlanningGroup(int id, Planner planner)
    {
        this.id      = id;
        this.planner = planner;
    }
Exemple #16
0
        public void SecondPlannerRun()
        {
            Planner planner = new Planner(5, 2);

            Assert.AreEqual(12, planner.Run(new int[] { 1, 2 }));
        }
Exemple #17
0
    //  This is the standard DeltaBlue benchmark. A long chain of
    //  equality constraints is constructed with a stay constraint on
    //  one end. An edit constraint is then added to the opposite end
    //  and the time is measured for adding and removing this
    //  constraint, and extracting and executing a constraint
    //  satisfaction plan. There are two cases. In case 1, the added
    //  constraint is stronger than the stay constraint and values must
    //  propagate down the entire length of the chain. In case 2, the
    //  added constraint is weaker than the stay constraint so it cannot
    //  be accomodated. The cost in this case is, of course, very
    //  low. Typical situations lie somewhere between these two
    //  extremes.
    //
    private void chainTest(int n)
    {
        planner = new Planner();

        Variable prev = null, first = null, last = null;

        // Build chain of n equality constraints
        for (int i = 0; i <= n; i++)
        {
            String name = "v" + i;
            Variable v = new Variable(name);
            if (prev != null)
                new EqualityConstraint(prev, v, Strength.required);
            if (i == 0) first = v;
            if (i == n) last = v;
            prev = v;
        }

        new StayConstraint(last, Strength.strongDefault);
        Constraint editC = new EditConstraint(first, Strength.preferred);
        ArrayList editV = new ArrayList();
        editV.Add(editC);
        Plan plan = planner.extractPlanFromConstraints(editV);
        for (int i = 0; i < 100; i++)
        {
            first.value = i;
            plan.execute();
            if (last.value != i)
                error("Chain test failed!");
        }
        editC.destroyConstraint();
        deltablue.chains++;
    }
 /// <summary>
 /// 获取给定彩种/玩法/计划员的预测数据
 /// </summary>
 /// <param name="type">彩种</param>
 /// <param name="planer">计划员</param>
 /// <param name="rule">玩法(请使用具体玩法枚举,如"PK10Rule","CQSSCRule")</param>
 /// <returns>预测数据</returns>
 public override async Task <IForecastPlanModel> GetForecastData(LotteryType type, Planner planer, int rule)
 {
     return(await JinMaCollector.GetForecastData(type, planer, rule));
 }
Exemple #19
0
        // Creates a child node.
        private static StateSpaceNode CreateChild(Planner planner, Domain domain, Problem problem, Plan plan, State state, StateSpaceEdge edge)
        {
            // Create a new problem object.
            Problem newProblem = new Problem();

            // Create a new domain object.
            Domain newDomain = domain;

            // Create a new plan object.
            Plan newPlan = new Plan();

            // Store actions the system takes.
            List <IOperator> systemActions = new List <IOperator>();

            // If the outgoing action is an exceptional step...
            if (edge.ActionType == ActionType.Exceptional)
            {
                // Count the exceptional edge.
                Exceptional++;

                // Create a new problem object.
                newProblem = NewProblem(newDomain, problem, state, edge.Action);

                // Find a new plan.
                if (planner.Equals(Planner.FastDownward))
                {
                    newPlan = FastDownward.Plan(newDomain, newProblem);
                }
                else if (planner.Equals(Planner.Glaive))
                {
                    newPlan = Glaive.Plan(newDomain, newProblem);
                }

                // If the action was accommodated and the first step of the new plan isn't taken by the player...
                if (newPlan.Steps.Count > 0)
                {
                    // Add the action to the system action list.
                    systemActions = GetSystemActions(newPlan, new List <string> {
                        problem.Player
                    }, new List <IOperator>());

                    // Update the problem object with the system's next move.
                    newProblem = NewProblem(newDomain, newProblem, new State(newProblem.Initial, newPlan.InitialStep, (Operator)newPlan.Steps.First()), systemActions);

                    // Update the plan with the system's next move.
                    newPlan = newPlan.GetPlanUpdate(newProblem, systemActions);
                }
                else if (CEDeletion)
                {
                    // Try to find a domain revision alibi.
                    Tuple <Domain, Operator> alibi = ReviseDomain(planner, newDomain, problem, state, edge.Action as Operator);

                    // If domain revision worked.
                    if (alibi != null)
                    {
                        // Remember the new domain.
                        newDomain = alibi.First;

                        // Push the modified action to the edge object.
                        edge.Action = alibi.Second;

                        // Create a new problem object.
                        newProblem = NewProblem(newDomain, problem, state, edge.Action);

                        // Find a new plan.
                        if (planner.Equals(Planner.FastDownward))
                        {
                            newPlan = FastDownward.Plan(newDomain, newProblem);
                        }
                        else if (planner.Equals(Planner.Glaive))
                        {
                            newPlan = Glaive.Plan(newDomain, newProblem);
                        }

                        // Add the action to the system action list.
                        systemActions = GetSystemActions(newPlan, new List <string> {
                            problem.Player
                        }, new List <IOperator>());

                        // Update the problem object with the system's next move.
                        newProblem = NewProblem(newDomain, newProblem, new State(newProblem.Initial, newPlan.InitialStep, (Operator)newPlan.Steps.First()), systemActions);

                        // Update the plan with the system's next move.
                        newPlan = newPlan.GetPlanUpdate(newProblem, systemActions);
                    }
                }
            }
            // Otherwise, if the action is a consistent step...
            else if (edge.ActionType == ActionType.Consistent)
            {
                // Count the consistent edge.
                Consistent++;

                // Create a new problem object.
                newProblem = NewProblem(newDomain, problem, state, edge.Action);

                // Add the action to the system action list.
                systemActions = GetSystemActions(plan, new List <string> {
                    problem.Player
                }, new List <IOperator>());

                // Create a new state.
                State newState = new State(newProblem.Initial, state.nextStep, (Operator)plan.Steps.First());

                // Create a new problem object.
                newProblem = NewProblem(newDomain, newProblem, newState, systemActions);

                // Create a new plan.
                newPlan = plan.GetPlanUpdate(newProblem, systemActions);
            }
            // Otherwise, the action is a constituent step...
            else
            {
                // Count the constituent edge.
                Constituent++;

                // If there are effects of the constituent action...
                if (edge.Action.Effects.Count > 0)
                {
                    // Create a new problem object.
                    newProblem = NewProblem(newDomain, problem, state, edge.Action);

                    // Create a new plan.
                    newPlan = plan.GetPlanUpdate(newProblem, edge.Action as Operator);
                }
                // Otherwise, initialize to the old problem and plan...
                else
                {
                    newProblem = problem;
                    newPlan    = plan.Clone() as Plan;
                }

                // If there are still plan actions...
                if (newPlan.Steps.Count > 0)
                {
                    // Add the action to the system action list.
                    systemActions = GetSystemActions(newPlan, new List <string> {
                        problem.Player
                    }, new List <IOperator>());

                    // Update the problem object with the system's next move.
                    newProblem = NewProblem(newDomain, newProblem, new State(newProblem.Initial, newPlan.InitialStep, (Operator)newPlan.Steps.First()), systemActions);

                    // Update the plan with the system's next move.
                    newPlan = newPlan.GetPlanUpdate(newProblem, systemActions);
                }
            }

            // Add the system actions to the current edge.
            edge.SystemActions = systemActions;

            // Create an empty child node.
            StateSpaceNode child = null;

            // If there are remaining plan steps...
            if (newPlan.Steps.Count > 0)
            {
                // Build a new tree using the first step of the plan as the next step.
                child = StateSpaceSearchTools.CreateNode(planner, newDomain, newProblem, newPlan, new State(newProblem.Initial, newPlan.InitialStep, (Operator)newPlan.Steps.First()));
            }
            else
            {
                // Terminate the tree by adding a goal node.
                child = StateSpaceSearchTools.CreateNode(planner, newDomain, newProblem, newPlan, new State(newProblem.Initial, newPlan.InitialStep, newPlan.GoalStep));
            }

            // Store the system actions.
            child.systemActions = systemActions;

            // Record the action that triggered the node's generation.
            child.incoming = edge;

            return(child);
        }
Exemple #20
0
        // Rewrites history to remove harmful conditional effects.
        public static StateSpaceNode RemoveConditionalEffects(Planner planner, Domain domain, Problem problem, Plan plan, State state, StateSpaceEdge edge, int depth)
        {
            // Store the incoming action.
            Operator incoming = edge.Action as Operator;

            // Create a new plan object.
            Plan newPlan = new Plan();

            // Examine each exceptional effect.
            foreach (Predicate effect in incoming.ExceptionalEffects)
            {
                // Create a new domain object.
                Domain newDomain = new Domain();

                // Save the domain's name.
                newDomain.Name        = domain.Name;
                newDomain.staticStart = domain.staticStart;

                // If the current effect is conditional...
                if (incoming.IsConditional(effect))
                {
                    // If the conditional effect has not been observed by the player.

                    // Remove the conditional effect from the domain.

                    // Copy the current operator templates into a list.
                    List <IOperator> templates = new List <IOperator>();
                    foreach (IOperator templ in domain.Operators)
                    {
                        templates.Add(templ.Clone() as IOperator);
                    }

                    // Create a clone of the incoming action's unbound operator template.
                    IOperator temp = incoming.Template() as Operator;

                    // Find the incoming action template in the domain list.
                    Operator template = templates.Find(t => t.Equals(temp)) as Operator;

                    // Remove the incoming action template from the domain list.
                    templates.Remove(template);

                    // Create a clone of the incoming action.
                    Operator clone = incoming.Clone() as Operator;

                    // Create a list of conditional effects to remove from the template.
                    List <IAxiom> remove = new List <IAxiom>();
                    foreach (IAxiom conditional in clone.Conditionals)
                    {
                        if (conditional.Effects.Contains(effect))
                        {
                            remove.Add(conditional);
                        }
                    }

                    // Remove each conditional effect from the template.
                    foreach (IAxiom rem in remove)
                    {
                        template.Conditionals.Remove(rem.Template() as IAxiom);
                    }

                    // Add the modified template to the domain list.
                    templates.Add(template);

                    // Push the modified list to the new domain object.
                    newDomain.Operators = templates;

                    // Write new problem and domain files.
                    Writer.ProblemToPDDL(Parser.GetTopDirectory() + @"Benchmarks\" + domain.Name.ToLower() + @"\probrob.pddl", newDomain, problem, state.Predicates);
                    Writer.DomainToPDDL(Parser.GetTopDirectory() + @"Benchmarks\" + domain.Name.ToLower() + @"\domrob.pddl", newDomain);

                    // Find a new plan.
                    if (planner.Equals(Planner.FastDownward))
                    {
                        newPlan = FastDownward.Plan(newDomain, problem);
                    }
                    else if (planner.Equals(Planner.Glaive))
                    {
                        newPlan = Glaive.Plan(newDomain, problem);
                    }

                    // If the modified domain can accommodate the player's action...
                    if (newPlan.Steps.Count > 0)
                    {
                        // Clone the modified incoming action template.
                        Operator newAction = template.Clone() as Operator;

                        // Bind the cloned action with the incoming action's bindings.
                        newAction.Bindings = incoming.Bindings;

                        // Push the modified action to the edge object.
                        edge.Action = newAction;

                        // Expand the tree using the new domain.
                        return(ExpandTree(planner, newDomain, problem, plan, state, edge, depth));
                    }
                }
            }

            return(null);
        }
Exemple #21
0
 // Rewrites history using alibi generation.
 public static StateSpaceNode GenerateAlibi(Planner planner, Domain domain, Problem problem, Plan plan, State state, StateSpaceEdge edge, int depth)
 {
     return(RemoveConditionalEffects(planner, domain, problem, plan, state, edge, depth));
 }
Exemple #22
0
        // Expand an edge.
        public static StateSpaceNode ExpandTree(Planner planner, Domain domain, Problem problem, Plan plan, State state, StateSpaceEdge edge, int depth)
        {
            // Create a new problem object.
            Problem newProblem = new Problem();

            // Create a new plan object.
            Plan newPlan = new Plan();

            // Store actions the system takes.
            List <IOperator> systemActions = new List <IOperator>();

            // If the action is an exceptional step...
            if (edge.ActionType == ActionType.Exceptional)
            {
                // Count the exceptional edge.
                Exceptional++;

                // Create a new problem object.
                newProblem = NewProblem(domain, problem, state, edge.Action);

                // Find a new plan.
                newPlan = PlannerInterface.Plan(planner, domain, newProblem);

                // If the action was accommodated and the first step of the new plan isn't taken by the player...
                if (newPlan.Steps.Count > 0)
                {
                    // Add the action to the system action list.
                    systemActions = GetSystemActions(newPlan, new List <string> {
                        problem.Player
                    }, new List <IOperator>());

                    // Update the problem object with the system's next move.
                    newProblem = NewProblem(domain, newProblem, new State(newProblem.Initial, newPlan.InitialStep, (Operator)newPlan.Steps.First()), systemActions);

                    // Update the plan with the system's next move.
                    newPlan = newPlan.GetPlanUpdate(newProblem, systemActions);
                }
                else if (CEDeletion)
                {
                    StateSpaceNode alibi = GenerateAlibi(planner, domain, problem, plan, state, edge, depth);
                    if (alibi != null)
                    {
                        return(alibi);
                    }
                }
            }
            // Otherwise, if the action is a consistent step...
            else if (edge.ActionType == ActionType.Consistent)
            {
                // Count the consistent edge.
                Consistent++;

                // Create a new problem object.
                newProblem = NewProblem(domain, problem, state, edge.Action);

                // Add the action to the system action list.
                systemActions = GetSystemActions(plan, new List <string> {
                    problem.Player
                }, new List <IOperator>());

                // Create a new state.
                State newState = new State(newProblem.Initial, state.nextStep, (Operator)plan.Steps.First());

                // Create a new problem object.
                newProblem = NewProblem(domain, newProblem, newState, systemActions);

                // Create a new plan.
                newPlan = plan.GetPlanUpdate(newProblem, systemActions);
            }
            // Otherwise, the action is a constituent step...
            else
            {
                // Count the constituent edge.
                Constituent++;

                // If there are effects of the constituent action...
                if (edge.Action.Effects.Count > 0)
                {
                    // Create a new problem object.
                    newProblem = NewProblem(domain, problem, state, edge.Action);

                    // Create a new plan.
                    newPlan = plan.GetPlanUpdate(newProblem, edge.Action as Operator);
                }
                // Otherwise, initialize to the old problem and plan...
                else
                {
                    newProblem = problem;
                    newPlan    = plan.Clone() as Plan;
                }

                // If there are still plan actions...
                if (newPlan.Steps.Count > 0)
                {
                    // Add the action to the system action list.
                    systemActions = GetSystemActions(newPlan, new List <string> {
                        problem.Player
                    }, new List <IOperator>());

                    // Update the problem object with the system's next move.
                    newProblem = NewProblem(domain, newProblem, new State(newProblem.Initial, newPlan.InitialStep, (Operator)newPlan.Steps.First()), systemActions);

                    // Update the plan with the system's next move.
                    newPlan = newPlan.GetPlanUpdate(newProblem, systemActions);
                }
            }

            // Add the system actions to the current edge.
            edge.SystemActions = systemActions;

            // Create an empty child node.
            StateSpaceNode child = null;

            // If there are remaining plan steps...
            if (newPlan.Steps.Count > 0)
            {
                // Build a new tree using the first step of the plan as the next step.
                child = BuildTree(planner, domain, newProblem, newPlan, new State(newProblem.Initial, newPlan.InitialStep, (Operator)newPlan.Steps.First()), depth - 1);
            }
            else
            {
                // Terminate the tree by adding a goal node.
                child = BuildTree(planner, domain, newProblem, newPlan, new State(newProblem.Initial, newPlan.InitialStep, newPlan.GoalStep), depth - 1);
            }

            // Store the system actions.
            child.systemActions = systemActions;

            // Record the action that triggered the node's generation.
            child.incoming = edge;

            return(child);
        }
Exemple #23
0
        // Build the mediation tree using a depth-first strategy.
        public static StateSpaceNode BuildTree(Planner planner, Domain domain, Problem problem, Plan plan, State state, int depth)
        {
            // Create a node for the current state.
            StateSpaceNode root = new StateSpaceNode();

            // Record that a node was created.
            NodeCount++;

            // Return any empty plans.
            if (plan.Steps.Count == 0)
            {
                // If the goal is satisfied...
                if (state.Satisfies(plan.GoalStep.Preconditions))
                {
                    // Differentiate a satisfied goal.
                    root.satisfiesGoal = true;

                    // Record that a goal state was reached.
                    GoalStateCount++;
                }
                else
                {
                    // Record that a dead end state was reached.
                    DeadEndCount++;
                }

                // Return the leaf node.
                return(root);
            }

            // Set the node's domain.
            root.domain = domain;

            // Set the node's problem.
            root.problem = problem;

            // Set the node's plan.
            root.plan = plan;

            // Set the node's state.
            root.state = state;

            // Find out what the player knows.
            root.problem.Initial = KnowledgeAnnotator.Annotate(problem.Initial, problem.Player);

            // Find all outgoing user actions from this state.
            root.outgoing = StateSpaceTools.GetAllPossibleActions(domain, problem, plan, state);

            // Return the node if the depth limit has been reached.
            if (depth <= 0)
            {
                return(root);
            }

            // Loop through the possible actions.
            foreach (StateSpaceEdge edge in root.outgoing)
            {
                StateSpaceNode child = ExpandTree(planner, domain, problem, plan.Clone() as Plan, state.Clone() as State, edge, depth);

                // Set the child's parent to this node.
                child.parent = root;

                // Add the child to the parent's collection of children, by way of the current action.
                root.children[edge] = child;
            }

            // Return the current node.
            return(root);
        }
Exemple #24
0
 private void OnEntityBuilt(Planner plan, GameObject go)
 {
     CheckDeploy(go.ToBaseEntity());
 }
Exemple #25
0
 private void OnEntityBuilt(Planner plan, GameObject go)
 {
     CheckPlacement(plan, go);
 }
Exemple #26
0
 void Awake()
 {
     planner = FindObjectOfType(typeof(Planner)) as Planner;
 }
Exemple #27
0
        public async Task Get()
        {
            await Planner.StartScheduler();

            _logger.Info("udałosię i do ");
        }
Exemple #28
0
        /// <summary>
        /// An online text-based command line game that is a traversal of mediation space.
        /// </summary>
        /// <param name="domainName">The game domain.</param>
        /// <param name="debug">Whether or not debug mode is enabled.</param>
        public static void Play()
        {
            Console.Clear();
            string domainName = "";

            // Make sure the file exists.
            while
            (!File.Exists(Parser.GetTopDirectory() + @"Benchmarks\" + domainName + @"\domain.pddl") ||
             !File.Exists(Parser.GetTopDirectory() + @"Benchmarks\" + domainName + @"\prob01.pddl"))
            {
                // Prompt the user for game name.
                Console.WriteLine("What would you like to play?");
                Console.WriteLine("     Type 'exit' to end program.");
                Console.WriteLine("     Type 'path' to modify the directory.");
                Console.WriteLine("     Type 'planner' to choose the planner.");
                Console.WriteLine("     Type 'help' to print game titles.");
                Console.Write("     Type 'debug' to turn debug mode ");
                if (debug)
                {
                    Console.WriteLine("off.");
                }
                else
                {
                    Console.WriteLine("on.");
                }
                Console.Write("     Type 'turns' to switch turn-taking ");
                if (twoTurns)
                {
                    Console.WriteLine("off.");
                }
                else
                {
                    Console.WriteLine("on.");
                }
                Console.WriteLine();
                Console.Write(">");

                // Read in the game to load.
                domainName = Console.ReadLine().ToLower();

                // Print domains if prompted.
                if (domainName.Equals("help"))
                {
                    Console.WriteLine();
                    if (System.IO.Directory.Exists(Parser.GetTopDirectory() + @"Benchmarks\"))
                    {
                        foreach (string file in Directory.GetFileSystemEntries(Parser.GetTopDirectory() + @"Benchmarks\"))
                        {
                            Console.WriteLine(Path.GetFileName(file));
                        }

                        Console.WriteLine();
                        Console.Write(">");

                        // Read in the game to load.
                        domainName = Console.ReadLine().ToLower();
                    }
                    else
                    {
                        Console.WriteLine(Parser.GetTopDirectory() + @"Benchmarks\ does not exist!");
                        Console.ReadKey();
                        domainName = "482990adkdlllifkdlkfjlaoow";
                    }
                }

                // Rewrite directory if prompted.
                if (domainName.Equals("path"))
                {
                    Console.WriteLine();
                    Console.WriteLine("Your current game directory is: " + Parser.GetTopDirectory());
                    Console.WriteLine("Enter new path.");
                    Console.WriteLine();
                    Console.Write(">");
                    string newPath = Console.ReadLine();
                    Console.WriteLine();

                    if (Directory.Exists(newPath + @"Benchmarks\"))
                    {
                        Parser.path = newPath;
                    }
                    else
                    {
                        Console.WriteLine("Sorry, " + newPath + @"Benchmarks\" + " does not exist.");
                        Console.ReadKey();
                    }
                }

                // Change the planner if prompted.
                if (domainName.Equals("planner"))
                {
                    Console.WriteLine();
                    Console.WriteLine("Your current planner is: " + planner);
                    Console.WriteLine("Enter new planner.");
                    Console.WriteLine();
                    Console.Write(">");
                    string newPlanner = Console.ReadLine();
                    Console.WriteLine();

                    if (Enum.IsDefined(typeof(Planner), newPlanner))
                    {
                        planner = (Planner)Enum.Parse(typeof(Planner), newPlanner, true);
                        Console.WriteLine("Your planner is now " + planner);
                        Console.ReadKey();
                    }
                    else
                    {
                        Console.WriteLine("Sorry, " + newPlanner + " does not exist.");
                        Console.ReadKey();
                    }
                }

                // Exit if prompted.
                if (domainName.Equals("exit"))
                {
                    Environment.Exit(0);
                }

                // Toggle debug if prompted
                if (domainName.Equals("debug"))
                {
                    debug = !debug;
                }

                if (domainName.Equals("turns"))
                {
                    twoTurns = !twoTurns;
                }

                if
                ((!File.Exists(Parser.GetTopDirectory() + @"Benchmarks\" + domainName + @"\domain.pddl") ||
                  !File.Exists(Parser.GetTopDirectory() + @"Benchmarks\" + domainName + @"\prob01.pddl")) &&
                 !domainName.Equals("debug") && !domainName.Equals("path") && !domainName.Equals("planner") &&
                 !domainName.Equals("482990adkdlllifkdlkfjlaoow") && !domainName.Equals("turns"))
                {
                    // Prompt that the game doesn't exist.
                    Console.WriteLine();
                    Console.WriteLine("I'm sorry, but I can't find " + domainName.ToUpper());
                    Console.WriteLine();
                    Console.ReadKey();
                }

                // Clear the console screen.
                Console.Clear();
            }

            // Parse the domain file.
            Domain domain = Parser.GetDomain(Parser.GetTopDirectory() + @"Benchmarks\" + domainName + @"\domain.pddl", PlanType.StateSpace);

            // Parse the problem file.
            Problem problem = Parser.GetProblemWithTypes(Parser.GetTopDirectory() + @"Benchmarks\" + domainName + @"\prob01.pddl", domain);

            // Welcome the player to the game.
            Console.WriteLine("Welcome to " + domain.Name);

            // Create the initial node of mediation space.
            tree = new MediationTree(domain, problem, Parser.GetTopDirectory() + @"MediationTrees\Data\" + domain.Name + @"\");

            if (debug)
            {
                Console.WriteLine();
                Console.WriteLine("Nodes Expanded: " + tree.TotalNodes);
                Console.WriteLine("Dead Ends Expanded: " + tree.DeadEndCount);
                Console.WriteLine("Goal States Expanded: " + tree.GoalStateCount);
                Console.WriteLine("Lowest Depth Expanded: " + tree.LowestDepth);
            }

            current = tree.Root;

            computerActions = new List <IOperator>();

            if (!twoTurns)
            {
                while (!tree.GetTurnAtIndex(current.Depth).Equals(current.Problem.Player))
                {
                    TakeTurn();
                }
            }

            // Initialize a stopwatch for debugging.
            Stopwatch watch = new Stopwatch();

            Console.Out.WriteLine();

            // Present the initial state.
            command = "";
            Look();

            // Loop while this is false.
            bool exit = false;

            while (!exit)
            {
                exploreFrontier = true;

                // Initialize the frontier.
                frontier = new Hashtable();

                // Expand the frontier in a new thread.
                frontierThread = new Thread(ExpandFrontier);

                // Start the thread.
                frontierThread.Start();

                // Ask for input.
                Console.WriteLine();
                Console.Write(">");
                input = Console.ReadLine();

                // If in debug mode, start the stop watch.
                if (debug)
                {
                    watch.Reset();
                    watch.Start();
                }

                // Parse the command and its arguments.
                command   = ParseCommand(input).ToLower();
                arguments = ParseArguments(input);

                // Interpret the command.
                switch (command)
                {
                case "exit":
                    exit = true;
                    break;

                case "clear":
                    Console.Clear();
                    break;

                case "cls":
                    Console.Clear();
                    break;

                case "look":
                    Look();
                    break;

                case "help":
                    Help();
                    break;

                case "wait":
                    Console.Clear();
                    Wait();
                    break;

                default:
                    OneArg();
                    break;
                }

                // If debugging, write the current plan and the elapsed time.
                if (debug && current.Plan.Steps.Count > 0 && !command.Equals("clear") && !command.Equals("cls"))
                {
                    Console.Out.WriteLine();
                    Console.WriteLine("Narrative Trajectory:");
                    int longestName = 0;
                    foreach (Operator step in current.Plan.Steps)
                    {
                        if (step.TermAt(0).Length > longestName)
                        {
                            longestName = step.TermAt(0).Length;
                        }
                    }
                    string lastName = "";
                    foreach (Operator step in current.Plan.Steps)
                    {
                        if (!step.TermAt(0).Equals(lastName))
                        {
                            lastName = step.TermAt(0);
                            Console.Out.Write("".PadLeft(5) + UppercaseFirst(step.TermAt(0)) + "".PadLeft(longestName - step.TermAt(0).Length + 1));
                        }
                        else
                        {
                            Console.Out.Write("".PadLeft(5) + "".PadLeft(longestName + 1));
                        }

                        string[] splitName = step.Name.Split('-');
                        Console.Out.Write(splitName[0] + "s ");
                        for (int i = 1; i < step.Name.Count(x => x == '-') + 1; i++)
                        {
                            Console.Out.Write(UppercaseFirst(step.TermAt(i)) + " ");
                        }
                        Console.Out.WriteLine();
                    }
                    Console.Out.WriteLine();
                    Console.Write("Elapsed time: ");
                    Console.Out.Write(watch.ElapsedMilliseconds);
                    Console.WriteLine("ms");
                }

                // Check for goal state.
                if (current.IsGoal)
                {
                    Console.WriteLine("GOAL STATE");
                    Console.ReadKey();
                    exit = true;
                }
                // Check for incompatible state.
                else if (current.DeadEnd)
                {
                    Console.WriteLine("UNWINNABLE STATE");
                    Console.ReadKey();
                    exit = true;
                }

                if (exit)
                {
                    Console.Clear();
                }

                // Kill the frontier thread (this should be okay).
                exploreFrontier = false;
            }

            MTGame.Play();
        }
 public AsyncState CloseProgressBar()
 {
     return(Planner.Chain()
            .AddFunc(_progressBar.Close)
            );
 }
Exemple #30
0
 public override void Init(Planner p)
 {
     base.Init(p);
 }
Exemple #31
0
 public void Init(Planner p)
 {
     this.p = p;
 }
Exemple #32
0
 public virtual void Init(Planner p)
 {
     this.p = p;
 }
        void OnEntityBuilt(Planner planner, GameObject gameobject)
        {
            BasePlayer player        = planner.GetOwnerPlayer();
            var        hasperm       = HasPermission(player.UserIDString, PermBypass);
            BaseEntity entity        = UnityEngine.GameObjectEx.ToBaseEntity(gameobject);
            var        buildingBlock = entity?.GetComponent <BuildingBlock>() ?? null;

            if (buildingBlock != null || !buildingBlock.Equals(null))
            {
                var buildingId = buildingBlock.buildingID;
                if (buildingids.ContainsKey(buildingId))
                {
                    var ConnectingStructure = buildingids[buildingBlock.buildingID];
                    if (buildingBlock.name == Foundation || buildingBlock.name == TriangleFoundation)
                    {
                        var trifcount = GetCountOf(ConnectingStructure, TriangleFoundation);
                        var fcount    = GetCountOf(ConnectingStructure, Foundation);
                        if (buildingBlock.name == Foundation && fcount >= MaxFoundations)
                        {
                            if (!hasperm)
                            {
                                buildingBlock.Kill(BaseNetworkable.DestroyMode.Gib);
                                SendReply(player, Lang("Limit: Foundations", player.UserIDString, MaxFoundations.ToString()), player);
                            }
                        }
                        else if (buildingBlock.name == TriangleFoundation && trifcount >= MaxTFoundations)
                        {
                            if (!hasperm)
                            {
                                buildingBlock.Kill(BaseNetworkable.DestroyMode.Gib);
                                SendReply(player, Lang("Limit: Triangle Foundations", player.UserIDString, MaxTFoundations.ToString()), player);
                            }
                        }
                        else
                        {
                            var structure = new List <BuildingBlock>(ConnectingStructure);
                            structure.Add(buildingBlock);
                            buildingids[buildingId] = structure;
                        }
                    }
                    else
                    {
                        if (!AllowedBuildingBlocks.Contains(buildingBlock.name))
                        {
                            BuildingBlock firstfoundation = null;
                            foreach (BuildingBlock block in ConnectingStructure)
                            {
                                if (block.name.Contains(TriangleFoundation) || block.name.Contains(Foundation))
                                {
                                    firstfoundation = block;
                                    break;
                                }
                            }
                            if (firstfoundation != null)
                            {
                                float height = (float)Math.Round(buildingBlock.transform.position.y - firstfoundation.transform.position.y, 0, MidpointRounding.AwayFromZero);
                                if (MaxHeight <= height)
                                {
                                    if (!hasperm)
                                    {
                                        buildingBlock.Kill(BaseNetworkable.DestroyMode.Gib);
                                        SendReply(player, Lang("Limit: Height", player.UserIDString, (MaxHeight / 3).ToString()), player);
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    var structure = new List <BuildingBlock>();
                    structure.Add(buildingBlock);
                    buildingids[buildingId] = structure;
                }
            }
        }
Exemple #34
0
        public void ThirdPlannerRun()
        {
            Planner planner = new Planner(3, 3);

            Assert.AreEqual(39, planner.Run(new int[] { 4, 1, 3, 5 }));
        }
        public NewTermPage(Planner term)
        {
            InitializeComponent();

            BindingContext = this.viewModel = term;
        }
Exemple #36
0
        public void ThirdPlannerThreeDay()
        {
            Planner planner = new Planner(3, 3);

            Assert.AreEqual(3, planner.Decide(3, 4, 1));
            Assert.AreEqual(3, planner.Decide(3, 1, 3));
            Assert.AreEqual(3, planner.Decide(3, 3, 5));
        }
Exemple #37
0
 private object CanBuild(Planner planner, Construction prefab, Construction.Target target)
 {
     return(CheckBuild(planner, prefab, target));
 }
Exemple #38
0
        public void FirstPlannerFirstDay()
        {
            Planner planner = new Planner(5, 2);

            Assert.AreEqual(5, planner.Decide(5, 2, 1));
        }
Exemple #39
0
        public static async Task <IForecastPlanModel> GetForecastData(LotteryType type, Planner planer, int rule)
        {
            var response = await HttpUtil.GetAsync(GetForecastUrl(type, planer, rule));

            try
            {
                if (string.IsNullOrWhiteSpace(response))
                {
                    return(null);
                }

                var result = JsonConvert.DeserializeObject <JinMaForecastPlanModel>(response);
                result.Plan = planer.GetPlan();
                if (result.ForecastData != null && result.ForecastData.Any())
                {
                    var current = result.ForecastData.LastOrDefault();
                    var pn      = current.LastDrawnPeriod % 1000 >= current.LastPeriod
                        ? current.LastPeriod / 1000 * 1000 + current.LastPeriod - 1
                        : current.LastDrawnPeriod;

                    current.LastDrawnPeriod = pn;
                    result.LastDrawnPeriod  = pn;
                }

                return(result);
            }
            catch (Exception ex)
            {
                ExceptionlessUtil.Warn(ex, $"预测数据反序列化失败,内容:{response}");
                return(null);
            }
        }
Exemple #40
0
        public void FirstPlannerRun()
        {
            Planner planner = new Planner(5, 2);

            Assert.AreEqual(12, planner.Run(new int[] { 2, 1 }));
        }
Exemple #41
0
    //public void Init(AnimationAnalyzer animAnalyzer, FootstepPlanningTest planner, AnimationEngine animEngine,
    public void Init(AnimationAnalyzer animAnalyzer, Planner planner, AnimationEngine animEngine,
	                 NeighbourAgents agents, NeighbourObstacles obstacles)
    {
        analyzer = animAnalyzer;
        if (analyzer != null && !analyzer.initialized)
            analyzer.Init();

        planning = planner;
        if (planning != null && !planning.initialized)
            planning.Init(analyzer, agents, obstacles);

        engine = animEngine;
        if (engine != null && !engine.initialized)
            engine.Init(analyzer,planning,agents,obstacles);

        if (rightFoot.position[1] < leftFoot.position[1])
            auxHeight = rightFoot.position[1];
        else
            auxHeight = leftFoot.position[1];

        counter = 0;

        footSteps = new Object[numberOfFootSteps];

        initiated = true;
    }
Exemple #42
0
        private void OnEntityBuilt(Planner plan, GameObject gameObject)
        {
            var player        = plan?.GetOwnerPlayer();
            var buildingBlock = gameObject.GetComponent <BuildingBlock>();

            if (player == null || buildingBlock == null)
            {
                return;
            }

            if (!player.CanBuild() || !player.HasAnyPermission(RegisteredPerms))
            {
                return;
            }

            var bgradePlayer = player.GetComponent <BGradePlayer>();

            if (bgradePlayer == null)
            {
                return;
            }

            var playerGrade = bgradePlayer.GetGrade();

            if (playerGrade == 0)
            {
                return;
            }

            if (!player.HasPluginPerm("all") && !player.HasPluginPerm(playerGrade.ToString()))
            {
                return;
            }

            var hookCall = Interface.Call("CanBGrade", player, playerGrade, buildingBlock, plan);

            if (hookCall is int)
            {
                DealWithHookResult(player, buildingBlock, (int)hookCall, gameObject);
                return;
            }

            if (playerGrade < (int)buildingBlock.grade || buildingBlock.blockDefinition.grades[playerGrade] == null)
            {
                return;
            }

            if (CheckLastAttack && WasAttackedRecently(buildingBlock.transform.position))
            {
                return;
            }

            if (Interface.Call("OnStructureUpgrade", buildingBlock, player, (BuildingGrade.Enum)playerGrade) != null)
            {
                return;
            }

            if (!player.HasPluginPerm("nores"))
            {
                Dictionary <int, int> itemsToTake;
                var resourceResponse = TakeResources(player, playerGrade, buildingBlock, out itemsToTake);
                if (!string.IsNullOrEmpty(resourceResponse))
                {
                    player.ChatMessage(resourceResponse);
                    return;
                }

                foreach (var itemToTake in itemsToTake)
                {
                    player.TakeItem(itemToTake.Key, itemToTake.Value);
                }
            }

            if (AllowTimer)
            {
                bgradePlayer.UpdateTime();
            }

            buildingBlock.SetGrade((BuildingGrade.Enum)playerGrade);
            buildingBlock.SetHealthToMax();
            buildingBlock.StartBeingRotatable();
            buildingBlock.SendNetworkUpdate();
            buildingBlock.UpdateSkin();
            buildingBlock.ResetUpkeepTime();
            buildingBlock.GetBuilding()?.Dirty();
        }
Exemple #43
0
 private object CanBuild(Planner planner, Construction prefab, Construction.Target target) =>
 IsLimited(planner.GetOwnerPlayer()) ? false : (object)null;
Exemple #44
0
 public override void Init(Planner p)
 {
     base.Init(p);
     sticks = GameObject.FindGameObjectsWithTag("Stick");
     //Preconditions = new string[] { "" };
 }
Exemple #45
0
 /////////////////////////////////////////
 // OnEntityBuilt(Planner planner, GameObject gameobject)
 // Called when a buildingblock was created
 /////////////////////////////////////////
 private void OnEntityBuilt(Planner planner, GameObject gameobject)
 {
     if (planner.ownerPlayer == null) return;
     if (HasPlayerFlag(planner.ownerPlayer, ZoneFlags.NoBuild) && !hasPermission(planner.ownerPlayer, PermCanBuild))
     {
         gameobject.GetComponentInParent<BaseCombatEntity>().Kill(BaseNetworkable.DestroyMode.Gib);
         SendMessage(planner.ownerPlayer, "You are not allowed to build here");
     }
 }
Exemple #46
0
    //public void Init(AnimationAnalyzer animAnalyzer, FootstepPlanningTest planner, AnimationEngine animEngine, NeighbourAgents agents, NeighbourObstacles obstacles)
    public void Init(AnimationAnalyzer animAnalyzer, Planner planner, AnimationEngine animEngine,NeighbourAgents agents, NeighbourObstacles obstacles)
    {
        analyzer = animAnalyzer;
        if (analyzer != null && !analyzer.initialized)
            analyzer.Init();

        planning = planner;
        if (planning != null && !planning.initialized)
            planning.Init(analyzer, agents, obstacles);

        engine = animEngine;
        if (engine != null && !engine.initialized)
            engine.Init(analyzer,planning, agents, obstacles);

        reacting = false;

        initialized = true;
    }
Exemple #47
0
    void Start()
    {
        Buildskill = 0.0F;
        Collectskill = 0.0F;

        SetColor();

        totalSkillpoints = 100;
        float numberOfSkills = 2.0f;
        skillArray = new Dictionary<string, float>();
        skillArray.Add("buildSkillpoints", totalSkillpoints/numberOfSkills);
        skillArray.Add("collectSkillpoints", totalSkillpoints/numberOfSkills);

        planner = new Planner();
        plan = new List<string>();
        plan.Add("IdleAction");

        AddSensors();
        AddPathfinding();

        tick = 0;
        energy = 100;

        mood = "happy";
    }
Exemple #48
0
 private void OnEntityBuilt(Planner planner, UnityEngine.GameObject component)
 {
     if(DeletingAdmins.Contains(planner.ownerPlayer)){
         objectsToBlow.Add(component);
         PrintToChat(planner.ownerPlayer, "Event structure place.");
     }
 }
Exemple #49
0
    // This test constructs a two sets of variables related to each
    // other by a simple linear transformation (scale and offset). The
    // time is measured to change a variable on either side of the
    // mapping and to change the scale and offset factors.
    //
    private void projectionTest(int n)
    {
        planner = new Planner();

        Variable scale = new Variable("scale", 10);
        Variable offset = new Variable("offset", 1000);
        Variable src = null, dst = null;

        ArrayList dests = new ArrayList();

        for (int i = 0; i < n; ++i)
        {
            src = new Variable("src" + i, i);
            dst = new Variable("dst" + i, i);
            dests.Add(dst);
            new StayConstraint(src, Strength.normal);
            new ScaleConstraint(src, scale, offset, dst, Strength.required);
        }

        change(src, 17);
        if (dst.value != 1170) error("Projection test 1 failed!");

        change(dst, 1050);
        if (src.value != 5) error("Projection test 2 failed!");

        change(scale, 5);
        for (int i = 0; i < n - 1; ++i)
        {
            if (((Variable)dests[i]).value != i * 5 + 1000)
                error("Projection test 3 failed!");
        }

        change(offset, 2000);
        for (int i = 0; i < n - 1; ++i)
        {
            if (((Variable)dests[i]).value != i * 5 + 2000)
                error("Projection test 4 failed!");
        }
        deltablue.projections++;
    }
Exemple #50
0
    void LateUpdate() //using late update to ensure everthing has been assigned before execution to avoid issues
    {                 //many coniditonals here are used to protect against a crash or error and help reset the agent when finding a plan fails. Resetting should allow the planner to formulate a new plan for the agent
        //if the agent is in the middle of performing an action, then that action should not be interrupted
        if (currentAction != null && currentAction.running)
        {
            float distanceToTarget = Vector3.Distance(currentAction.target.transform.position, this.transform.position); //update distance the agent has to move to at the start of the loop in case it is not set later in LateUpdate
            if (currentAction.agent.hasPath && distanceToTarget < 2f)                                                    //if the agent has a goal and has reached that goal
            //(using a set distance 1f from goal to signify that the agent is in the goal location which luckily makes a cluster of agents attempting to reach a location wait for the agents closest to the destination point to move before they can perform the action)
            {
                //run the action performing process shown by making the agent wait at the goal location for the specified duration based on the action
                if (!invoked)                                         //boolean to determine if waiting process already invoked
                {
                    Invoke("CompleteAction", currentAction.duration); //make the agent wait at the goal position reached to convey the action is being done (waiting time based on action performed)
                    invoked = true;
                }
            }
            return;
        }

        if (planner == null || actionQueue == null) //if neither a planner or action queue exists then the agent has nothing to work on and a must be assinged a plan
        {
            planner = new Planner();                //create a planner

            //sort through subgoals from most important to least important to loop through them and find one for the agent to perfrom
            var sortedGoals = from entry in goals orderby entry.Value descending select entry; //use of Linq library to sort goals dictionary into sortedgoals

            foreach (KeyValuePair <SubGoal, int> sg in sortedGoals)                            //loop through the ordered subgoals (starting from highest priority) that need to be satisfied
            {
                actionQueue = planner.plan(actions, sg.Key.subgoals, beliefs);                 //call the planner to do planning process to give the agent the actions that it must perform (given null as the world state is being used at this point rather than the agent state)
                if (actionQueue != null)                                                       //if a plan has been found
                {
                    currentGoal = sg.Key;                                                      //set the goal the agent is working towards as the agent's subgoal
                    break;
                }
            }
        }

        //at this point the agent either runs out of actions to do (assuming it completed them) or it still has more actions it needs to perfrom
        if (actionQueue != null && actionQueue.Count == 0) //check queue exists to avoid errors and if the quque has no actions with it (empty queue)
        {
            if (currentGoal.remove)                        //if agent's current goal is removable,
            {
                goals.Remove(currentGoal);                 //remove the goal from the list of goals the agent still needs to perfrom to avoid repeating it after completion (some goals need to be repeated based on goal which
            }
            planner = null;                                //to trigger another planner being retrieved when done with current one for this iteration of the update
        }

        if (actionQueue != null && actionQueue.Count > 0) //ifthere are still actions in the queue that need to be performed (additional null check as safegaurd against crash)
        {
            currentAction = actionQueue.Dequeue();        //remove action at front of queue and store it in currentAction
            //perform checks required for the action
            if (currentAction.PrePerform())
            {
                //the targets for the navmesh agent to move to are set with tags referenced by strings (tags of objects are set from the inspector)
                if (currentAction.target == null && currentAction.targetTag != "") //check for the target object the agent has to move to. if thats not set, then set the one for the current action the agent is performing
                {
                    currentAction.target = GameObject.FindWithTag(currentAction.targetTag);
                }

                if (currentAction.target != null)                                                //error check in case no agent has no position to go for perform action
                {
                    currentAction.running = true;                                                //agent starts to perform action
                    currentAction.agent.SetDestination(currentAction.target.transform.position); //move agent to location needed to perform current action (Navmesh componenet will take care of navigating agents between its initial and goal positions)
                }
            }
            else //in case PrePreform method cannot be excecuted
            {
                actionQueue = null; //set the queueu to null to force the planner to get a new plan
            }
        }
    }
        protected virtual void Start()
        {
            States = new Dictionary <string, bool>();
            foreach (var item in preState)
            {
                States[item.Key] = item.Value;
            }

            IdleState idleState = new IdleState(FSM)
            {
                onStart = () => { },
                onExit  = () => { }
            };

            idleState.onUpdate = () =>
            {
                if (NextPlanTime > FSM.time)
                {
                    return;
                }

                NextPlanTime = FSM.time + interval;

                // 搜寻计划
                foreach (GOAPGoal goal in Goals)
                {
                    Planner.Plan(AvailableActions, States, goal, maxDepth, ref storedActionQueue);
                    if (StoredActionQueue.Count != 0)
                    {
                        CurrentGoal = goal;
                        break;
                    }
                }

                if (storedActionQueue.Count > 0)
                {
                    actionQueue.Clear();
                    foreach (var action in storedActionQueue)
                    {
                        actionQueue.Enqueue(action);
                    }

                    //通知计划找到
                    if (Provider != null)
                    {
                        Provider.PlanFound(CurrentGoal, actionQueue);
                    }
                    //转换状态
                    FSM.ChangeTo("PerformActionState");
                }
                else
                {
                    //通知计划没找到
                    if (Provider != null)
                    {
                        Provider.PlanFailed(Goals);
                    }
                    CurrentGoal = null;
                }
            };

            GOAPFSMState performActionState = new GOAPFSMState(FSM)
            {
                onStart = () => { },
                onExit  = () => { }
            };

            performActionState.onUpdate = () =>
            {
                if (HasPlan)
                {
                    // 如果当前有计划(目标尚未完成)
                    GOAPAction action = actionQueue.Peek();
                    if (CurrentAction != action)
                    {
                        CurrentAction = action;
                        action.OnPrePerform();
                    }
                    // 成功 or 失败
                    GOAPActionStatus status = action.OnPerform();

                    switch (status)
                    {
                    case GOAPActionStatus.Success:
                        foreach (var effect in action.Effects)
                        {
                            SetState(effect.Key, effect.Value);
                        }
                        action.OnPostPerform(true);
                        if (Provider != null)
                        {
                            Provider.ActionFinished(action.Effects);
                        }
                        actionQueue.Dequeue();
                        CurrentAction = null;
                        break;

                    case GOAPActionStatus.Failure:
                        if (replanOnFailed)
                        {
                            EnforceReplan();
                        }
                        else
                        {
                            AbortPlan();
                        }
                        return;

                    default:
                        break;
                    }
                }
                else
                {
                    // 如果没有计划(目标已完成)
                    // 如果目标为一次性,移除掉
                    if (CurrentGoal != null && CurrentGoal.Once)
                    {
                        Goals.Remove(CurrentGoal);
                    }

                    // 通知计划完成
                    if (Provider != null)
                    {
                        Provider.PlanFinished();
                    }

                    // 当前目标设置为空
                    CurrentGoal = null;
                    FSM.ChangeTo("IdleState");
                }
            };

            FSM.PushState("IdleState", idleState);
            FSM.PushState("PerformActionState", performActionState);
            FSM.ChangeTo("IdleState");
        }
Exemple #52
0
 public override void Init(Planner p)
 {
     base.Init(p);
     p.DataContainer.Add("isThirsty", false);
     p.DataContainer.Add("waterPosition", new Vector3(-10, 0, 10));
 }
Exemple #53
0
 private void OnEntityBuilt(Planner planner, GameObject gameObject)
 {
     HookCalled("OnEntityBuilt");
 }
Exemple #54
0
        public void SecondPlannerFirstDay()
        {
            Planner planner = new Planner(5, 2);

            Assert.AreEqual(2, planner.Decide(5, 1, 2));
        }
 void Awake()
 {
     goalIndex = 0;
     blackBoard = BlackBoard.Instance;
     planner = new Planner();
     goals = new List<WorldState>();
     buildingGroup = new GameObject();
 }
Exemple #56
0
        private void OnEntityBuilt(Planner plan, GameObject go)
        {
            var Player = plan.GetOwnerPlayer();

            if (Player == null)
            {
                return;
            }
            if (!permission.UserHasPermission(Player.UserIDString, permission_use))
            {
                return;
            }
            var Entity = go.ToBaseEntity() as DecayEntity;

            if (Entity == null)
            {
                return;
            }
            if (_config.Disabled.Contains(Entity.PrefabName))
            {
                return;
            }
            if (!_data.Codes.ContainsKey(Player.UserIDString))
            {
                _data.Codes.Add(Player.UserIDString, new PlayerData
                {
                    Code    = GetRandomCode(),
                    Enabled = true
                });
            }
            var pCode = _data.Codes[Player.UserIDString];

            if (!pCode.Enabled || !HasCodeLock(Player))
            {
                return;
            }
            var S = Entity as StorageContainer;

            if (S?.inventorySlots < 12)
            {
                return;
            }
            if (!S && !(Entity is AnimatedBuildingBlock))
            {
                return;
            }
            if (Entity.IsLocked())
            {
                return;
            }
            var Code = GameManager.server.CreateEntity("assets/prefabs/locks/keypad/lock.code.prefab") as CodeLock;

            Code.Spawn();
            Code.code = pCode.Code;
            Code.SetParent(Entity, Entity.GetSlotAnchorName(BaseEntity.Slot.Lock));
            Entity.SetSlot(BaseEntity.Slot.Lock, Code);
            Code.SetFlag(BaseEntity.Flags.Locked, true);
            Effect.server.Run("assets/prefabs/locks/keypad/effects/lock-code-deploy.prefab", Code.transform.position);
            Code.whitelistPlayers.Add(Player.userID);
            TakeCodeLock(Player);
            Player.ChatMessage(string.Format(lang.GetMessage("CodeAdded", this, Player.UserIDString),
                                             Player.net.connection.info.GetBool("global.streamermode") ? "****" : pCode.Code));
        }
Exemple #57
0
    void Start()
    {
        Buildskill = 0.0f;
        Collectskill = 0.0f;

        SetColor();

        totalSkillpoints = 100;
        float numberOfSkills = 2.0f;
        skillArray = new Dictionary<string, float>();
        skillArray.Add("buildSkillpoints", totalSkillpoints/numberOfSkills);
        skillArray.Add("collectSkillpoints", totalSkillpoints/numberOfSkills);

        planner = new Planner();
        plan = new List<string>();
        plan.Add("IdleAction"); //Set the agent to be Idle by default

        AddSensors();
        AddPathfinding();
    }
Exemple #58
0
        public void GooglePlannerFirstDay()
        {
            Planner planner = new Planner(5, 5);

            Assert.AreEqual(5, planner.Decide(5, 10, 10));
        }
Exemple #59
0
 /////////////////////////////////////////
 // OnEntityBuilt(Planner planner, GameObject gameobject)
 // Called when a buildingblock was created
 /////////////////////////////////////////
 void OnEntityBuilt(Planner planner, GameObject gameobject)
 {
     if (planner.ownerPlayer == null) return;
     if (hasTag(planner.ownerPlayer, "nobuild"))
     {
         if (!hasPermission(planner.ownerPlayer, "canbuild"))
         {
             gameobject.GetComponentInParent<BaseCombatEntity>().Kill(BaseNetworkable.DestroyMode.Gib);
             SendMessage(planner.ownerPlayer, "You are not allowed to build here");
         }
     }
 }
Exemple #60
0
        public void GooglePlannerRun()
        {
            Planner planner = new Planner(5, 5);

            Assert.AreEqual(500, planner.Run(new int[] { 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 }));
        }