Inheritance: MonoBehaviour
Example #1
0
    public static bool CheckForHighScores(Goal goal)
    {
        if (!SaveDataControl.GoalHighScores.ContainsKey(goal.MiniDescription)) {
            if((goal.HighScore != 0) | (goal.HighScore == 0 && !goal.HigherScoreIsGood))
            SaveDataControl.GoalHighScores[goal.MiniDescription] = goal.HighScore;

            SaveDataControl.Save();
            return true;
        }
        if (goal.HigherScoreIsGood) {
            if(SaveDataControl.GoalHighScores[goal.MiniDescription] < goal.HighScore) {
                Debug.Log("new high score is " + goal.HighScore);
                SaveDataControl.GoalHighScores[goal.MiniDescription] = goal.HighScore;

                SaveDataControl.Save();
                return true;
            }
        } else {
            if(SaveDataControl.GoalHighScores[goal.MiniDescription] > goal.HighScore) {
                Debug.Log("new high score is " + goal.HighScore);
                SaveDataControl.GoalHighScores[goal.MiniDescription] = goal.HighScore;

                SaveDataControl.Save();
                return true;
            }
        }
        return false;
    }
 /// <summary>Initializes a new Trigger</summary>
 /// <param name="parent">The <see cref="Goal"/> to which this object belongs.</param>
 /// <remarks>Trigger set to <b>10</b>, "never (FALSE)".</remarks>
 public Trigger(Goal parent)
 {
     _owner = parent;
     GoalTrigger = new Mission.Trigger();
     GoalTrigger.Condition = 10;
     for (int i = 0; i < 3; i++) _strings[i] = "";
 }
Example #3
0
    protected void Awake()
    {
        if(sInstance != null)
        {
            Destroy(gameObject);
            return;
        }

        sInstance = this;

        if (mDungeon == null)
        {
            mDungeon = FindObjectOfType<Dungeon>();
        }

        if (mFollowCamera == null)
        {
            mFollowCamera = FindObjectOfType<FollowCamera>();
        }

        if(mFader == null)
        {
            mFader = FindObjectOfType<Fader>();
        }

        GameObject goalObj = SpawnPrefab(mGoalPrefab);
        mGoal = goalObj.GetComponent<Goal>();
        GameObject playerObj = SpawnPrefab(GlobalData.sSelectedCharacter == SelectedCharacter.Rose ? mPlayerRosePrefab : mPlayerVuPrefab);
        mPlayer1 = playerObj.GetComponent<PlayerController>();
        mFollowCamera.Init(mPlayer1.transform);
    }
Example #4
0
    public Goal[] InitializeGoals(int numberOfGods)
    {
        unusedGoals = new List<Goal> ();

        GodChoiceMenu menu = gameObject.GetComponent<GodChoiceMenu> ();

        //If godchoicemenu is unlocked, pick from the selected gods' goals; otherwise, pick from all goals
        if(SaveDataControl.UnlockedGods.Count == 7) {
            for(int i = 0; i < allGoals.Count; i++) {
                for(int j = 0; j < menu.GodChoiceSelection.Length; j++) {
                    if(menu.GodChoiceSelection[j] && allGoals[i].God == ShopControl.AllGods[j]){
                        unusedGoals.Add(allGoals[i]);
                    }
                }
            }
        } else {
            for(int i = 0; i < allGoals.Count; i++) {
                unusedGoals.Add(allGoals[i]);
            }
        }

        Goal[] Goals = new Goal[numberOfGods];
        for(int i = 0; i < numberOfGods; i++){
            Goals[i] = new Goal();
            int randomNumber = Random.Range (0, unusedGoals.Count);
            Goals[i] = unusedGoals[randomNumber];
            unusedGoals.RemoveAt(randomNumber);
        }

        return Goals;
    }
 /// <summary>
 /// Begins the boid walk to the bar
 /// </summary>
 private void navigateToBar()
 {
     GoalSeekingBehaviour gsb = new GoalSeekingBehaviour(owner);
     currentGoal = gsb.ChooseClosestFromList(BootStrapper.EnvironmentManager.CurrentEnvironment.World.Bars);
     owner.Behaviour = gsb;
     NextStep();
 }
 /// <summary>
 /// Begins the boid walk to the stage
 /// </summary>
 private void navigateToStage()
 {
     GoalSeekingBehaviour behaviour = new LineOfSightGoalSeekingBehaviour(owner);
     this.currentGoal = behaviour.ChooseClosestFromList(BootStrapper.EnvironmentManager.CurrentEnvironment.World.Stages);
     owner.Behaviour = behaviour;
     NextStep();
 }
        protected override void EstablishContext()
        {
            //Prepare supplied data collections
            suppliedStudentMetricBenchmarkAssessmentData = GetSuppliedStudentMetricBenchmarkAssessment();
            suppliedSchoolGoal = GetSuppliedMetricGoal();
            suppliedMetricState = GetSuppliedMetricState();

            //Set up the mocks
            metricNodeResolver = mocks.StrictMock<IMetricNodeResolver>();
            studentMetricBenchmarkAssessmentRepository = mocks.StrictMock<IRepository<StudentMetricBenchmarkAssessment>>();
            metricGoalProvider = mocks.StrictMock<IMetricGoalProvider>();
            metricStateProvider = mocks.StrictMock<IMetricStateProvider>();
            metricInstanceSetKeyResolver = mocks.StrictMock<IMetricInstanceSetKeyResolver<StudentSchoolMetricInstanceSetRequest>>();

            //Set expectations
            Expect.Call(metricNodeResolver.GetMetricNodeForStudentFromMetricVariantId(suppliedSchoolId, suppliedMetricVariantId)).Return(GetMetricMetadataNode());
            Expect.Call(studentMetricBenchmarkAssessmentRepository.GetAll()).Return(suppliedStudentMetricBenchmarkAssessmentData);
            Expect.Call(
                metricInstanceSetKeyResolver.GetMetricInstanceSetKey(null))
                .Constraints(
                    new ActionConstraint<StudentSchoolMetricInstanceSetRequest>(x =>
                    {
                        Assert.That(x.SchoolId == suppliedSchoolId);
                        Assert.That(x.MetricVariantId == suppliedMetricVariantId);
                        Assert.That(x.StudentUSI == suppliedStudentUSI);
                    })
                ).Return(suppliedMetricInstanceSetKey);
            Expect.Call(metricGoalProvider.GetMetricGoal(suppliedMetricInstanceSetKey, suppliedMetricId)).Return(suppliedSchoolGoal);
            Expect.Call(metricStateProvider.GetState(suppliedMetricId, suppliedMetricValueStr, "System.Double")).Repeat.Any().Return(suppliedMetricState);
            Expect.Call(metricStateProvider.GetState(suppliedMetricId, "", "System.Double")).Return(suppliedMetricState);
        }
    public void EventGoalScored(Goal scoredOn)
    {
        if (scoredOn == Player1Goal)
        {
            Player2Score += 1;
            p1scorestreak = 0;

            int tmp = (int)Player2Goal.transform.localScale.y;
            if (tmp > 1)
            {
                tmp -= 1;
                Player2Goal.transform.localScale = new Vector3(1.5f, tmp, 1);
            }
        }
        if (scoredOn == Player2Goal)
        {
            Player1Score += 1;
            p2scorestreak = 0;
            int tmp = (int)Player1Goal.transform.localScale.y;
            if (tmp > 1)
            {
                tmp -= 1;
                Player1Goal.transform.localScale = new Vector3(1.5f, tmp, 1);
            }
        }
    }
        protected override void EstablishContext()
        {
            //Prepare supplied data collections
            _suppliedStudentMetricAssessmentHistorical = GetSuppliedStudentMetricAssessmentHistorical();
            _suppliedStudentMetricAssessmentHistoricalMetaData = GetSuppliedStudentMetricAssessmentHistoricalMetaData();
            _suppliedSchoolGoal = GetSuppliedMetricGoal();

            //Set up the mocks
            _metricNodeResolver = mocks.StrictMock<IMetricNodeResolver>();
            _studentMetricAssessmentHistorical = mocks.StrictMock<IRepository<StudentMetricAssessmentHistorical>>();
            _studentMetricAssessmentHistoricalMetaData = mocks.StrictMock<IRepository<StudentMetricAssessmentHistoricalMetaData>>();
            _metricGoalProvider = mocks.StrictMock<IMetricGoalProvider>();
            _metricInstanceSetKeyResolver = mocks.StrictMock<IMetricInstanceSetKeyResolver<StudentSchoolMetricInstanceSetRequest>>();

            //Set expectations
            Expect.Call(_metricNodeResolver.GetMetricNodeForStudentFromMetricVariantId(SuppliedSchoolId, SuppliedMetricVariantId)).Return(GetMetricMetadataNode());
            Expect.Call(_studentMetricAssessmentHistorical.GetAll()).Return(_suppliedStudentMetricAssessmentHistorical);
            Expect.Call(_studentMetricAssessmentHistoricalMetaData.GetAll()).Return(_suppliedStudentMetricAssessmentHistoricalMetaData);
            Expect.Call(
                _metricInstanceSetKeyResolver.GetMetricInstanceSetKey(null))
                .Constraints(
                    new ActionConstraint<StudentSchoolMetricInstanceSetRequest>(x =>
                    {
                        Assert.That(x.SchoolId == SuppliedSchoolId);
                        Assert.That(x.MetricVariantId == SuppliedMetricVariantId);
                        Assert.That(x.StudentUSI == SuppliedStudentUsi);
                    })
                ).Return(_suppliedMetricInstanceSetKey);
            Expect.Call(_metricGoalProvider.GetMetricGoal(_suppliedMetricInstanceSetKey, SuppliedMetricId)).Return(_suppliedSchoolGoal);
        }
Example #10
0
 public Quest(string n, string d, string o, int i, Goal[] newGoals )
 {
     name = n;
     description = d;
     objective = o;
     iden = i;
     goal = newGoals;
 }
Example #11
0
    public void NewLevelNewGoals(int numberOfGods, Goal[] goals)
    {
        Goals = goals;

        TurnOnExpoGUI ();

        S.ShopAndGoalParentCanvasInst.NewLevelNewGoals (goals);
    }
        void Awake()
        {
            Think = new Think(gameObject);

            Think.RemoveAllSubGoals();

            Think.OnActivate();
        }
Example #13
0
 public static Goal Disjunction(Goal goal1, Goal goal2)
 {
     return subst =>
     {
         var res = Disjunction(subst, goal1, goal2);
         return res.Any() ? res.Select(s => new InfiniteSubstitutions(s)) : null;
     };
 }
 public bool HasGoal(Goal _g)
 {
     if (this.subGoals.Count > 0)
     {
         return subGoals[0] != _g;
     }
     return true;
 }
Example #15
0
 void Awake()
 {
     playerGoal = (Goal)GameObject.Find("PGoal").GetComponent(typeof(Goal));
     shadowGoal = (Goal)GameObject.Find("SGoal").GetComponent(typeof(Goal));
     player = GameObject.Find("Player");
     shadow = GameObject.Find("Shadow");
     spawner = (Spawner)gameObject.GetComponent(typeof(Spawner));
 }
 public HttpResponseMessage Post(Goal model)
 {
     if (!ModelState.IsValid)
     {
         throw new HttpResponseException(HttpStatusCode.BadRequest);
     }
     _goalService.Add(model);
     return Request.CreateResponse<Goal>(HttpStatusCode.Created, model);
 }
Example #17
0
    /// <summary>
    /// Gets the usefulness of each subgoal that the Brain
    /// currently has and chooses the one with the greatest
    /// utility. The utility of a goal is calculated periodically
    /// by the Brains update in AI. 
    /// </summary>
    public void SelectGoal()
    {
        if (canThink == true)
        {
            best = 0f;
            topChoice = null;

            for (int i = 0; i <= this.subGoals.Count - 1; i++)
            {
                //print("GOALS " + i + " " + subGoals[i]);
                float utility = subGoals[i].CalculateUtility();

                if (utility >= best && utility > 0)
                {
                    best = utility;
                    topChoice = subGoals[i];
                    if (!topChoice.Equals(this.myGoal) && this.myGoal != null)
                    {
                        this.myGoal.myProperties.myStatus = GoalProps.goalStatus.FAILED;
                        //  this.myGoal.Terminate();
                    }
                }
            }
            this.myGoal = topChoice;
            this.AddSubGoal(this.myGoal);
        }
        //this.myGoal.Activate();
        /*
      if (this.myGoal != null)
      {


          if (this.myGoal != topChoice)
          {
              this.myGoal.Terminate();
              this.myGoal = topChoice;
              this.myGoal.Activate();
          }

      }
      else
      {
          if (subGoals.Count > 0)
          {
              this.myGoal = topChoice;
              this.myGoal.Activate();
          }
          else
          {
              this.subGoals.Add(this.GetComponent<Goal_Wander>());   
          }



      }
          */
    }
Example #18
0
        public void TestMethod1()
        {
            var eventRaised = false;
            var sut = new Goal();
            sut.PropertyChanged += (s, e) => { eventRaised = true; };
            sut.ManDays = 2;

            Assert.IsTrue(eventRaised);
        }
Example #19
0
        public void RequiresExplicitActiveGoalIfCommandNeedsIt()
        {
            commandEnumerator.Setup(c => c.NeedsExplicitTargetGoal(It.IsAny<string>())).Returns(true);

            var factory = new DefaultSuiteFactory(parameters.Object, suiteRoot, commandEnumerator.Object);

            var goal1 = new Goal("goal1");
            factory.CreateSuite(new HashSet<Goal>(new[] { goal1 }), Suite.DebugGoal);
        }
        public void SetUp()
        {
            var root = new TestFileSystemDirectory("root");
            var goalx86 = new Goal("debug-x86", new[] { Suite.DebugGoal, new Goal("x86") });
            var goalx64 = new Goal("debug-x64", new[] { Suite.DebugGoal, new Goal("x64") });

            x86Suite = new Suite(root, new[] {goalx86, goalx64}, goalx86);
            x64Suite = new Suite(root, new[] {goalx86, goalx64}, goalx64);
        }
Example #21
0
 public void TestClamping()
 {
     Goal g = new Goal(null, 0.5f);
     Assert.AreEqual<float>(g.Desirability, 0.5f);
     g.Desirability = 10;
     Assert.AreEqual<float>(g.Desirability, 1);
     g.Desirability = -1;
     Assert.AreEqual<float>(g.Desirability, 0);
 }
 public void NextGoal()
 {
     goalIterator++;
     if (goalIterator >= goals.Count) {
         UIManager.instance.UpdateGoalText("Good job!  You finished the game!");
         return;
     }
     currentGoal = goals [goalIterator];
     UIManager.instance.UpdateGoalText(currentGoal.goalText);
 }
Example #23
0
 public Quest(string n, string d, string o, int t, int i, Goal[] newGoals)
 {
     name = n;
     description = d;
     objective = o;
     duration = t;
     iden = i;
     goal = newGoals;
     timer = true;
 }
Example #24
0
        public void UsesFirstAvailableAsActiveGoalIfCommandDoesNotNeedIt()
        {
            commandEnumerator.Setup(c => c.NeedsExplicitTargetGoal(It.IsAny<string>())).Returns(false);

            var factory = new DefaultSuiteFactory(parameters.Object, suiteRoot, commandEnumerator.Object);

            var goal1 = new Goal("goal1");
            var suite = factory.CreateSuite(new HashSet<Goal>(new[] { goal1 }));

            suite.ActiveGoal.Should().Be(goal1);
        }
Example #25
0
        public void Compile(SuiteRelativePath scriptPath, TargetRelativePath targetPath, string version, Goal targetGoal)
        {
            var platform = targetGoal.Has("x64") ? "x64" : "x86";

            Run(suiteRoot,
                "/dVERSION="+version,
                "/dPLATFORM="+platform,
                "/dGOAL="+targetGoal.Name,
                "/o"+Path.GetDirectoryName(Path.Combine(suiteRoot.GetRelativePath(targetRoot), targetPath)),
                scriptPath);
        }
        public void SetUp()
        {
            var root = new TestFileSystemDirectory("root");
            debugSuite = new Suite(root, new[] {Suite.DebugGoal, Suite.ReleaseGoal}, Suite.DebugGoal);
            releaseSuite = new Suite(root, new[] { Suite.DebugGoal, Suite.ReleaseGoal }, Suite.ReleaseGoal);

            var customDebug = new Goal("test-debug", new[] {Suite.DebugGoal});
            var customRelease = new Goal("test-release", new[] { Suite.ReleaseGoal });

            customDebugSuite = new Suite(root, new[] { customDebug, customRelease }, customDebug);
            customReleaseSuite = new Suite(root, new[] { customDebug, customRelease }, customRelease);
        }
Example #27
0
 private static IEnumerable<IEnumerable<Substitution>> Conjunction(ISubstitutions subst, Goal goal1, Goal goal2)
 {
     foreach (var firstSubst in goal1(subst))
     {
         foreach (var secondSubst in goal2(subst))
         {
             var resSubst = Conjunction(firstSubst, secondSubst);
             if (resSubst != null)
                 yield return resSubst;
         }
     }
 }
Example #28
0
        public ActionResult Create(Goal goal)
        {
            if (ModelState.IsValid)
            {
                db.Goals.Add(goal);
                db.SaveChanges();
                return RedirectToAction("Edit", "Match", new { id = goal.MatchID });
            }

            ViewBag.PlayerID = new SelectList(db.Players, "PlayerID", "Name", goal.PlayerID);
            return View(goal);
        }
    public void NewLevelNewGoals(Goal[] goals)
    {
        TurnOnAppropriateGoals(goals);

        for (int i = 0; i < 3; i++) {
            if(GOALCANVASES[i] != null && GOALCANVASES[i].gameObject.activeSelf) {
                GOALCANVASES[i].SetInitialGoalInfo(goals[i]);
            }
        }

        UpdateGoalInfos (goals);
    }
 /// <summary>
 /// Adds a new goal at the head of the list
 /// </summary>
 /// <param name="_g">The goal to add.</param>
 public override void AddSubGoal(Goal _g)
 {
     if (HasGoal(_g) == true)
     {
         ClearSubGoals();
         subGoals.Insert(0, _g);
     }
     else
     {
     //add component
     }
 }
Example #31
0
 public void Update(Goal entity)
 {
     //TODO: sprawdziæ jakieœ waruneczki
     _repository.Update(entity);
 }
Example #32
0
        public MemoryStream WriteKnowledgeProblem(HashSet <Predicate> lObserved, HashSet <Predicate> lAllValues)
        {
            MemoryStream msProblem = new MemoryStream();
            StreamWriter sw        = new StreamWriter(msProblem);

            sw.WriteLine("(define (problem K" + Name + ")");
            sw.WriteLine("(:domain K" + Domain.Name + ")");
            sw.WriteLine(";;" + SDRPlanner.Translation);
            sw.WriteLine("(:init"); //ff doesn't like the and (and");


            foreach (GroundedPredicate gp in lObserved)
            {
                if (gp.Name == "Choice")
                {
                    continue;
                }
                sw.WriteLine(gp);
                if (!Domain.AlwaysKnown(gp))
                {
                    Predicate kp = new KnowPredicate(gp);
                    sw.WriteLine(kp);
                }
            }
            HashSet <Predicate> lHidden = new HashSet <Predicate>(lAllValues.Except(lObserved));



            foreach (GroundedPredicate gp in lHidden)
            {
                sw.WriteLine(gp);
            }



            sw.WriteLine(")");

            HashSet <Predicate> lGoalPredicates = Goal.GetAllPredicates();


            CompoundFormula cfGoal = new CompoundFormula("and");

            foreach (Predicate p in lGoalPredicates)
            {
                if (Domain.AlwaysKnown(p))
                {
                    cfGoal.AddOperand(p);
                }
                else
                {
                    cfGoal.AddOperand(new KnowPredicate(p));
                }
            }

            CompoundFormula cfAnd = new CompoundFormula(cfGoal);

            sw.WriteLine("(:goal " + cfAnd.Simplify() + ")");
            //sw.WriteLine("))");

            sw.WriteLine(")");
            sw.Flush();


            return(msProblem);
        }
Example #33
0
 /// <summary>
 /// The disj goal constructor takes two goals as arguments and returns
 /// a goal that succeeds if either of the two subgoals succeed.
 /// </summary>
 public static Goal Disj(Goal g1, Goal g2)
 {
     return(sc => MPlus(g1(sc), g2(sc)));
 }
Example #34
0
 private Plan GetPlanFor(Goal goal)
 {
     return(env.Planner.FormulatePlan(env.KnowledgeProvider, env.SupportedPlanningActions, goal));
 }
Example #35
0
 private Role(string name, Goal mainGoal) : base(name)
 {
     Main = mainGoal;
 }
Example #36
0
 private void Start()
 {
     Instance = this;
 }
Example #37
0
 /// <summary>
 /// This method attempt  to compute a path from the given state information
 /// to the given goal. This function will throw a PathNotFoundException if
 /// no valid path can be found.
 /// </summary>
 /// <param name="StaticState">Some static state information that will not
 /// change with actions performed upon the state space.</param>
 /// <param name="DynamicState">A starting dynamic state to be transformed
 /// by actions to reach the goal state.</param>
 /// <param name="Goal">A goal object to evaluate if a given goal has been
 /// reached.</param>
 /// <returns>A path from the starting state to the goal state. Whether this
 /// is optiminal will depend upon the concrete implementation.</returns>
 public abstract IEnumerable <Path <SS, DS> > Compute(SS StaticState,
                                                      DS DynamicState, Goal <SS, DS> Goal, Operator <SS, DS>[] Actions);
        public void update(MapData map)
        {
            Player p;

            if (timer < Time.time && !destroyed)
            {
                AgentSI(map);

                foreach (var pl in map.players)
                {
                    p = pl.Value;
                    if (p.controledBySI == true && this.ownerPlayer.controledBySI == false)
                    {
                        var obcy_ = p.agents.Where(f => (
                                                       (f.Value.x == x && f.Value.y == y) ||
                                                       (f.Value.x == x + 1 && f.Value.y == y) ||
                                                       (f.Value.x == x - 1 && f.Value.y == y) ||
                                                       (f.Value.x == x && f.Value.y == y + 1) ||
                                                       (f.Value.x == x && f.Value.y == y - 1) ||
                                                       (f.Value.x == x + 1 && f.Value.y == y + 1) ||
                                                       (f.Value.x == x - 1 && f.Value.y == y - 1) ||
                                                       (f.Value.x == x - 1 && f.Value.y == y + 1) ||
                                                       (f.Value.x == x + 1 && f.Value.y == y - 1)
                                                       ) && f.Value.destroyed == false).ToList();

                        if (obcy_.Count > 0)
                        {
                            Agent obcy = obcy_.FirstOrDefault().Value;

                            finishedWay();
                            obcy.finishedWay();
                            obcy.DestroyMe();
                            DestroyMe();
                            if (ownerPlayer.agents.Count == 0)
                            {
                                obcy.ownerPlayer.won = true;
                            }
                            else if (obcy.ownerPlayer.agents.Count == 0)
                            {
                                ownerPlayer.won = true;
                            }
                        }
                    }
                    p = null;
                }
                timer = Time.time + 0.5f;
                if (destinationWay == null || destinationWay.Count == 0)
                {
                    finishedWay();
                    var mygo = map.Table[x + 800][y + 800];
                    if (mygo != null)
                    {
                        if (mygo.objectType == ObjectType.Building)
                        {
                            Building b = (Building)mygo;
                            if (b.owner == owner)
                            {
                                map.players.TryGetValue((int)this.owner, out p);
                                if (p != null)
                                {
                                    p.food += food;
                                    food    = 0;
                                    p.gold += gold;
                                    gold    = 0;
                                    p.wood += wood;
                                    wood    = 0;

                                    currentGoal = Goal.None;

                                    if (destinationRemember.HasValue)
                                    {
                                        agentService.setDestination(destinationRemember.Value, this);
                                        if (map.Table[(int)destinationRemember.Value.x + 800][(int)destinationRemember.Value.y + 800] != null)
                                        {
                                            ObjectType t = map.Table[(int)destinationRemember.Value.x + 800][(int)destinationRemember.Value.y + 800].objectType;
                                            if (t == ObjectType.Food)
                                            {
                                                currentGoal = Goal.CollectFood;
                                            }
                                            if (t == ObjectType.Gold)
                                            {
                                                currentGoal = Goal.CollectGold;
                                            }
                                            if (t == ObjectType.Wood)
                                            {
                                                currentGoal = Goal.CollectWood;
                                            }
                                        }
                                    }
                                    destinationRemember = null;
                                }
                            }
                            else
                            {
                                b.zniszczony++;
                                finishedWay();
                                DestroyMe();
                                if (b.zniszczony >= 10)
                                {
                                    ownerPlayer.won = true;
                                }
                            }
                        }
                        else if (currentGoal == Goal.CollectFood)
                        {
                            if (mygo.objectType == ObjectType.Food)
                            {
                                Food f = (Food)mygo;
                                map.players.TryGetValue((int)this.owner, out p);
                                if (p != null && f != null)
                                {
                                    if (food + collectSpeed <= collectMax)
                                    {
                                        food    += collectSpeed;
                                        f.value -= collectSpeed;
                                        if (f.value < 0)
                                        {
                                            food += f.value;
                                        }
                                        if (f.value < 1)
                                        {
                                            GameObject.Destroy(f.objectUnity);
                                            map.Table[x + 800][y + 800] = null;
                                            SetStore();
                                        }
                                    }
                                    else
                                    {
                                        destinationRemember = new Vector2(x, y);
                                        SetStore();
                                    }
                                }
                            }
                            else
                            {
                                currentGoal = Goal.None;
                            }
                        }
                        else if (currentGoal == Goal.CollectGold)
                        {
                            if (mygo.objectType == ObjectType.Gold)
                            {
                                Gold f = (Gold)mygo;
                                map.players.TryGetValue((int)this.owner, out p);
                                if (p != null && f != null)
                                {
                                    if (gold + collectSpeed <= collectMax)
                                    {
                                        gold    += collectSpeed;
                                        f.value -= collectSpeed;
                                        if (f.value < 0)
                                        {
                                            gold += f.value;
                                        }
                                        if (f.value < 1)
                                        {
                                            GameObject.Destroy(f.objectUnity);
                                            map.Table[x + 800][y + 800] = null;
                                            SetStore();
                                        }
                                    }
                                    else
                                    {
                                        destinationRemember = new Vector2(x, y);
                                        SetStore();
                                    }
                                }
                            }
                            else
                            {
                                currentGoal = Goal.None;
                            }
                        }
                        else if (currentGoal == Goal.CollectWood)
                        {
                            if (mygo.objectType == ObjectType.Wood)
                            {
                                Wood f = (Wood)mygo;
                                map.players.TryGetValue((int)this.owner, out p);
                                if (p != null && f != null)
                                {
                                    if (gold + collectSpeed <= collectMax)
                                    {
                                        wood    += collectSpeed;
                                        f.value -= collectSpeed;
                                        if (f.value < 0)
                                        {
                                            wood += f.value;
                                        }
                                        if (f.value < 1)
                                        {
                                            GameObject.Destroy(f.objectUnity);
                                            map.Table[x + 800][y + 800] = null;
                                            SetStore();
                                        }
                                    }
                                    else
                                    {
                                        destinationRemember = new Vector2(x, y);
                                        SetStore();
                                    }
                                }
                            }
                            else
                            {
                                currentGoal = Goal.None;
                            }
                        }
                    }
                    else
                    {
                        currentGoal = Goal.None;
                    }
                }
                if (destinationWay != null)
                {
                    Vector2 first = destinationWay.FirstOrDefault();
                    if (first != null)
                    {
                        SetVelocity();
                    }
                    else
                    {
                        finishedWay();
                    }
                }
            }
        }
 public void SetStore()
 {
     this.currentGoal = Goal.Store;
     agentService.setDestination(new Vector2(ownerPlayer.startXB, ownerPlayer.startYB), this);
 }
 public LevelScenarioData(string mapFileName, string name, string description, int index, Goal goal)
 {
     this.mapFileName = mapFileName;
     this.name        = name;
     this.description = description;
     this.index       = index;
     this.goal        = goal;
 }
Example #41
0
 void Replace(Goal goal, Formula f1, Formula f2)
 {
     goal.FormalSpec = Replace(goal.FormalSpec, f1, f2);
 }
Example #42
0
        public Goal GetGoal()
        {
            Goal goal = (Goal)MapThings.Find(x => x.Tag == "Goal");

            return(goal);
        }
Example #43
0
        public MemoryStream WriteKnowledgeProblem(HashSet <Predicate> lObserved, HashSet <Predicate> lHidden, int cMinMishaps, int cMishaps, bool bRemoveNegativePreconditions)
        {
            MemoryStream msProblem = new MemoryStream();
            StreamWriter sw        = new StreamWriter(msProblem);

            sw.WriteLine("(define (problem K" + Name + ")");
            sw.WriteLine("(:domain K" + Domain.Name + ")");
            sw.WriteLine(";;" + SDRPlanner.Translation);
            sw.WriteLine("(:init"); //ff doesn't like the and (and");

            string sKP = "", sP = "";

            HashSet <string> lNegativePreconditons = new HashSet <string>();

            if (bRemoveNegativePreconditions)
            {
                foreach (Predicate p in Domain.IdentifyNegativePreconditions())
                {
                    lNegativePreconditons.Add(p.Name);
                }
            }

            foreach (GroundedPredicate gp in lObserved)
            {
                if (gp.Name == "Choice")
                {
                    continue;
                }
                if (Domain.AlwaysKnown(gp))
                {
                    sw.WriteLine(gp);
                }
                if (!Domain.AlwaysKnown(gp))
                {
                    Predicate kp = new KnowPredicate(gp);
                    sw.WriteLine(kp);
                }
                if (gp.Negation && bRemoveNegativePreconditions && lNegativePreconditons.Contains(gp.Name))
                {
                    Predicate np = gp.Negate().Clone();
                    np.Name = "Not" + gp.Name;
                    sw.WriteLine(np);
                }
            }
            if (bRemoveNegativePreconditions)
            {
                foreach (GroundedPredicate gp in lHidden)
                {
                    Predicate nkp = gp.Clone();
                    nkp.Name = "NotK" + gp.Name;
                    sw.WriteLine(nkp);
                    Predicate nknp = gp.Clone();
                    nknp.Name = "NotKN" + gp.Name;
                    sw.WriteLine(nknp);
                }
            }

            if (cMinMishaps > cMishaps)
            {
                sw.WriteLine("(MishapCount m" + cMishaps + ")");
            }

            if (SDRPlanner.AddActionCosts)
            {
                sw.WriteLine("(= (total-cost) 0)");
            }

            sw.WriteLine(")");

            HashSet <Predicate> lGoalPredicates    = Goal.GetAllPredicates();


            CompoundFormula cfGoal = new CompoundFormula("and");

            foreach (Predicate p in lGoalPredicates)
            {
                if (Domain.AlwaysKnown(p))
                {
                    cfGoal.AddOperand(p);
                }
                else
                {
                    cfGoal.AddOperand(new KnowPredicate(p));
                }
            }

            CompoundFormula cfAnd = new CompoundFormula(cfGoal);

            if (cMinMishaps > cMishaps && SDRPlanner.Translation != SDRPlanner.Translations.Conformant)
            {
                GroundedPredicate gp = new GroundedPredicate("MishapCount");
                gp.AddConstant(new Constant("mishaps", "m" + cMinMishaps));
                cfAnd.AddOperand(gp);
            }

            sw.WriteLine("(:goal " + cfAnd.Simplify() + ")");
            if (MetricStatement != null)
            {
                sw.WriteLine(MetricStatement);
            }

            sw.WriteLine(")");
            sw.Flush();


            return(msProblem);
        }
Example #44
0
        /*public ActionResult ActivityTypeChart()
         * {
         *  IList<Activity> activities = new List<Activity>
         *  {
         *      new Activity { Id = 1, Name="Walking", Duration = 800, UserId = "2a7f80bb-5e84-4468-88ad-804f848d8f20", StartTime = new DateTime(2014, 2, 15), Type = ActivityType.Walking, Distance = 1200, Steps = 430 },
         *      new Activity { Id = 2, Name="Walking", Duration = 500, UserId = "2a7f80bb-5e84-4468-88ad-804f848d8f20", StartTime = new DateTime(2015, 3, 15), Type = ActivityType.Walking, Distance = 900, Steps = 370 },
         *      new Activity { Id = 3, Name="Jogging", Duration = 1000, UserId = "2a7f80bb-5b36-4468-88ad-804f848d8f20", StartTime = new DateTime(2015, 3, 18), Type = ActivityType.Jogging, Distance = 1500, Steps = 480 },
         *      new Activity { Id = 4, Name="Biking", Duration = 1500, UserId = "2a7f80bb-5b36-4468-88ad-804f848d8f20", StartTime = new DateTime(2015, 4, 2), Type = ActivityType.Biking, Distance = 2000, Steps = 600 },
         *      new Activity { Id = 5, Name="Running", Duration = 400, UserId = "2a7f80bb-3r56-4468-88ad-804f848d8f20", StartTime = new DateTime(2015, 4, 8), Type = ActivityType.Running, Distance = 600, Steps = 300 },
         *  };
         *  ViewBag.Message = "Pie chart of activities";
         *  Highcharts chart = ChartHelper.ActivityTypePie(activities);
         *  return PartialView();
         * }*/

        public ActionResult GoalChart(Goal goal)
        {
            #region setup

            string timeFrame = "";
            switch (goal.TimeFrame)
            {
            case TimeFrame.Daily:
                timeFrame = "day";
                break;

            case TimeFrame.Weekly:
                timeFrame = "week";
                break;

            case TimeFrame.Monthly:
                timeFrame = "month";
                break;

            case TimeFrame.Yearly:
                timeFrame = "year";
                break;
            }
            string type = "";
            switch (goal.Type)
            {
            case GoalType.Steps:
                type = "steps";
                break;

            case GoalType.Duration:
                type = "minutes";
                break;

            case GoalType.Distance:
                type = "miles";
                break;
            }

            #endregion setup

            Highcharts chart = new Highcharts("chart")
                               .InitChart(new Chart {
                PlotBorderWidth = 0, PlotShadow = false
            })
                               .SetTitle(new Title
            {
                Text          = string.Format("{0} {1} each {2}", goal.Target, type, timeFrame),
                Align         = HorizontalAligns.Center,
                VerticalAlign = VerticalAligns.Middle,
                Y             = 50
            })
                               .SetTooltip(new Tooltip {
                PointFormat = "{series.name}: <b>{point.percentage:.1f}%</b>"
            })
                               .SetPlotOptions(new PlotOptions
            {
                Pie = new PlotOptionsPie
                {
                    StartAngle = -90,
                    EndAngle   = 90,
                    Center     = new[] { new PercentageOrPixel(50, true), new PercentageOrPixel(75, true) },
                    DataLabels = new PlotOptionsPieDataLabels
                    {
                        Enabled  = true,
                        Distance = -50,
                        Style    = "fontWeight: 'bold', color: 'white', textShadow: '0px 1px 2px black'"
                    }
                }
            })
                               .SetSeries(new Series
            {
                Type           = ChartTypes.Pie,
                Name           = type,
                PlotOptionsPie = new PlotOptionsPie {
                    InnerSize = new PercentageOrPixel(50, true)
                },
                Data = new Data(new object[]
                {
                    new object[] { "Current Activity", goal.Progress * goal.Target },
                    new object[] { "Remaining Activity", 1 - (goal.Progress * goal.Target) }
                })
            });
            return(PartialView(chart));
        }
Example #45
0
 /// <summary>
 /// The conj goal constructor takes two goals as arguments and returns a goal
 /// that succeeds if both goals succeed for that state.
 /// </summary>
 public static Goal Conj(Goal g1, Goal g2)
 {
     return(sc => Bind(g1(sc), g2));
 }
        [STAThread] // Added to support UX
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    #region Sample Code
                    //////////////////////////////////////////////
                    #region Set up
                    SetUpSample(service);
                    #endregion Set up
                    #region Demonstrate

                    // Create the revenue metric, setting the Amount Data Type to 'Money'
                    // and the Metric Type to 'Amount'.
                    Metric sampleMetric = new Metric()
                    {
                        Name           = "Sample Revenue Metric",
                        AmountDataType = new OptionSetValue(0),
                        IsAmount       = true,
                    };
                    _metricId       = service.Create(sampleMetric);
                    sampleMetric.Id = _metricId;

                    Console.Write("Created revenue metric, ");

                    #region Create RollupFields

                    // Create RollupField which targets the actual totals.
                    RollupField actual = new RollupField()
                    {
                        SourceEntity           = SalesOrder.EntityLogicalName,
                        SourceAttribute        = "totalamount",
                        GoalAttribute          = "actualmoney",
                        SourceState            = 1,
                        EntityForDateAttribute = SalesOrder.EntityLogicalName,
                        DateAttribute          = "datefulfilled",
                        MetricId = sampleMetric.ToEntityReference()
                    };
                    _actualId = service.Create(actual);

                    Console.Write("created actual revenue RollupField, ");

                    #endregion

                    #region Create the goal rollup query

                    // The query locates sales orders in the first sales
                    // representative's area (zip code: 60661) and with a value
                    // greater than $1,000.
                    GoalRollupQuery goalRollupQuery = new GoalRollupQuery()
                    {
                        Name            = "First Example Goal Rollup Query",
                        QueryEntityType = SalesOrder.EntityLogicalName,
                        FetchXml        = @"<fetch mapping=""logical"" version=""1.0""><entity name=""salesorder""><attribute name=""customerid"" /><attribute name=""name"" /><attribute name=""salesorderid"" /><attribute name=""statuscode"" /><attribute name=""totalamount"" /><order attribute=""name"" /><filter><condition attribute=""totalamount"" operator=""gt"" value=""1000"" /><condition attribute=""billto_postalcode"" operator=""eq"" value=""60661"" /></filter></entity></fetch>"
                    };
                    _rollupQueryId     = service.Create(goalRollupQuery);
                    goalRollupQuery.Id = _rollupQueryId;

                    Console.Write("created rollup query.");
                    Console.WriteLine();

                    #endregion

                    #region Create two goals: one parent and one child goal

                    // Create the parent goal.
                    Goal parentGoal = new Goal()
                    {
                        Title = "Parent Goal Example",
                        RollupOnlyFromChildGoals = true,
                        TargetMoney        = new Money(1000.0M),
                        IsFiscalPeriodGoal = false,
                        MetricId           = sampleMetric.ToEntityReference(),
                        GoalOwnerId        = new EntityReference
                        {
                            Id          = _salesManagerId,
                            LogicalName = SystemUser.EntityLogicalName
                        },
                        OwnerId = new EntityReference
                        {
                            Id          = _salesManagerId,
                            LogicalName = SystemUser.EntityLogicalName
                        },
                        GoalStartDate = DateTime.Today.AddDays(-1),
                        GoalEndDate   = DateTime.Today.AddDays(30)
                    };
                    _parentGoalId = service.Create(parentGoal);
                    parentGoal.Id = _parentGoalId;

                    Console.WriteLine("Created parent goal");
                    Console.WriteLine("-------------------");
                    Console.WriteLine("Target: {0}", parentGoal.TargetMoney.Value);
                    Console.WriteLine("Goal owner: {0}", parentGoal.GoalOwnerId.Id);
                    Console.WriteLine("Goal Start Date: {0}", parentGoal.GoalStartDate);
                    Console.WriteLine("Goal End Date: {0}", parentGoal.GoalEndDate);
                    Console.WriteLine("<End of Listing>");
                    Console.WriteLine();

                    // Create the child goal.
                    Goal firstChildGoal = new Goal()
                    {
                        Title = "First Child Goal Example",
                        ConsiderOnlyGoalOwnersRecords = true,
                        TargetMoney        = new Money(1000.0M),
                        IsFiscalPeriodGoal = false,
                        MetricId           = sampleMetric.ToEntityReference(),
                        ParentGoalId       = parentGoal.ToEntityReference(),
                        GoalOwnerId        = new EntityReference
                        {
                            Id          = _salesRepresentativeId,
                            LogicalName = SystemUser.EntityLogicalName
                        },
                        OwnerId = new EntityReference
                        {
                            Id          = _salesManagerId,
                            LogicalName = SystemUser.EntityLogicalName
                        },
                        RollUpQueryActualMoneyId = goalRollupQuery.ToEntityReference(),
                        GoalStartDate            = DateTime.Today.AddDays(-1),
                        GoalEndDate = DateTime.Today.AddDays(30)
                    };
                    _firstChildGoalId = service.Create(firstChildGoal);

                    Console.WriteLine("First child goal");
                    Console.WriteLine("----------------");
                    Console.WriteLine("Target: {0}", firstChildGoal.TargetMoney.Value);
                    Console.WriteLine("Goal owner: {0}", firstChildGoal.GoalOwnerId.Id);
                    Console.WriteLine("Goal Start Date: {0}", firstChildGoal.GoalStartDate);
                    Console.WriteLine("Goal End Date: {0}", firstChildGoal.GoalEndDate);
                    Console.WriteLine("<End of Listing>");
                    Console.WriteLine();

                    #endregion

                    // Calculate roll-up of goals.
                    // Note: Recalculate can be run against any goal in the tree to cause
                    // a rollup of the whole tree.
                    RecalculateRequest recalculateRequest = new RecalculateRequest()
                    {
                        Target = parentGoal.ToEntityReference()
                    };
                    service.Execute(recalculateRequest);

                    Console.WriteLine("Calculated roll-up of goals.");
                    Console.WriteLine();

                    // Retrieve and report 3 different computed values for the goals
                    // - Percentage
                    // - ComputedTargetAsOfTodayPercentageAchieved
                    // - ComputedTargetAsOfTodayMoney
                    QueryExpression retrieveValues = new QueryExpression()
                    {
                        EntityName = Goal.EntityLogicalName,
                        ColumnSet  = new ColumnSet(
                            "title",
                            "computedtargetasoftodaypercentageachieved",
                            "computedtargetasoftodaymoney")
                    };
                    EntityCollection ec = service.RetrieveMultiple(retrieveValues);

                    // Compute and display the results
                    for (int i = 0; i < ec.Entities.Count; i++)
                    {
                        Goal temp = (Goal)ec.Entities[i];
                        Console.WriteLine("Roll-up details for goal: {0}", temp.Title);
                        Console.WriteLine("---------------");
                        Console.WriteLine("ComputedTargetAsOfTodayPercentageAchieved: {0}",
                                          temp.ComputedTargetAsOfTodayPercentageAchieved);
                        Console.WriteLine("ComputedTargetAsOfTodayMoney: {0}",
                                          temp.ComputedTargetAsOfTodayMoney.Value);
                        Console.WriteLine("<End of Listing>");
                    }


                    #region Clean up
                    CleanUpSample(service);
                    #endregion Clean up
                }
                #endregion Demonstrate
                #endregion Sample Code

                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Microsoft Dataverse";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }

            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
Example #47
0
 public void RemoveUniversalQuantifiers()
 {
     Goal = Goal.RemoveUniversalQuantifiers(Domain.Constants, null, null);
 }
 /// <summary>
 /// Add an Goal row view model to the list of <see cref="Goal"/>
 /// </summary>
 /// <param name="goal">
 /// The <see cref="Goal"/> that is to be added
 /// </param>
 private GoalRowViewModel AddGoalRowViewModel(Goal goal)
 {
     return(new GoalRowViewModel(goal, this.Session, this));
 }
Example #49
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            using (ForecastService forecastService =
                       (ForecastService)user.GetService(DfpService.v201802.ForecastService))
            {
                // Set the placement that the prospective line item will target.
                long[] targetPlacementIds = new long[]
                {
                    long.Parse(_T("INSERT_PLACEMENT_ID_HERE"))
                };

                // Set the ID of the advertiser (company) to forecast for. Setting an advertiser
                // will cause the forecast to apply the appropriate unified blocking rules.
                long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE"));

                // Create prospective line item.
                LineItem lineItem = new LineItem();

                lineItem.targeting = new Targeting();
                lineItem.targeting.inventoryTargeting = new InventoryTargeting();
                lineItem.targeting.inventoryTargeting.targetedPlacementIds = targetPlacementIds;

                Size size = new Size();
                size.width  = 300;
                size.height = 250;

                // Create the creative placeholder.
                CreativePlaceholder creativePlaceholder = new CreativePlaceholder();
                creativePlaceholder.size = size;

                lineItem.creativePlaceholders = new CreativePlaceholder[]
                {
                    creativePlaceholder
                };

                lineItem.lineItemType      = LineItemType.SPONSORSHIP;
                lineItem.startDateTimeType = StartDateTimeType.IMMEDIATELY;

                // Set the line item to run for one month.
                lineItem.endDateTime =
                    DateTimeUtilities.FromDateTime(System.DateTime.Now.AddMonths(1),
                                                   "America/New_York");

                // Set the cost type to match the unit type.
                lineItem.costType = CostType.CPM;
                Goal goal = new Goal();
                goal.goalType        = GoalType.DAILY;
                goal.unitType        = UnitType.IMPRESSIONS;
                goal.units           = 50L;
                lineItem.primaryGoal = goal;

                try
                {
                    // Get availability forecast.
                    AvailabilityForecastOptions options = new AvailabilityForecastOptions();
                    options.includeContendingLineItems        = true;
                    options.includeTargetingCriteriaBreakdown = true;
                    ProspectiveLineItem prospectiveLineItem = new ProspectiveLineItem();
                    prospectiveLineItem.advertiserId = advertiserId;
                    prospectiveLineItem.lineItem     = lineItem;
                    AvailabilityForecast forecast =
                        forecastService.getAvailabilityForecast(prospectiveLineItem, options);

                    // Display results.
                    long   matched          = forecast.matchedUnits;
                    double availablePercent =
                        (double)(forecast.availableUnits / (matched * 1.0)) * 100;
                    String unitType = forecast.unitType.ToString().ToLower();
                    Console.WriteLine("{0} {1} matched.\n{2}% {3} available.", matched, unitType,
                                      availablePercent, unitType);

                    if (forecast.possibleUnitsSpecified)
                    {
                        double possiblePercent =
                            (double)(forecast.possibleUnits / (matched * 1.0)) * 100;
                        Console.WriteLine("{0}% {1} possible.\n", possiblePercent, unitType);
                    }

                    Console.WriteLine("{0} contending line items.",
                                      (forecast.contendingLineItems != null)
                            ? forecast.contendingLineItems.Length
                            : 0);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to get forecast. Exception says \"{0}\"", e.Message);
                }
            }
        }
Example #50
0
 public Agent(AgentEnvironment environment)
 {
     this.env         = PreconditionUtils.EnsureNotNull(environment, nameof(environment));
     this.currentGoal = environment.GoalSelector.DefaultGoal;
 }
Example #51
0
 public bool Update(Goal goal)
 {
     return(GoalDb.Update(goal));
 }
Example #52
0
        public MemoryStream WriteTaggedProblemNoState(Dictionary <string, List <Predicate> > dTags, IEnumerable <Predicate> lObserved,
                                                      Dictionary <string, double> dFunctionValues)
        {
            MemoryStream ms = new MemoryStream(1000);
            StreamWriter sw = new StreamWriter(ms);

            sw.WriteLine("(define (problem K" + Name + ")");
            sw.WriteLine("(:domain K" + Domain.Name + ")");
            sw.WriteLine("(:init"); //ff doesn't like the and (and");

            string sKP = "";

            if (Domain.TIME_STEPS > 0)
            {
                sw.WriteLine("(time0)");
            }
            foreach (KeyValuePair <string, double> f in dFunctionValues)
            {
                sw.WriteLine("(= " + f.Key + " " + f.Value + ")");
            }
            foreach (GroundedPredicate gp in lObserved)
            {
                //if (gp.Negation)
                //    continue;
                if (gp.Name == "Choice" || gp.Name == Domain.OPTION_PREDICATE)
                {
                    continue;
                }
                if (Domain.AlwaysKnown(gp) && Domain.AlwaysConstant(gp))
                {
                    sKP = "(" + gp.Name;
                    foreach (Constant c in gp.Constants)
                    {
                        sKP += " " + c.Name;
                    }
                    sw.WriteLine(sKP + ")");
                }
                else
                {
                    foreach (string sTag in dTags.Keys)
                    {
                        if (!gp.Negation)
                        {
                            Predicate pGiven = gp.GenerateGiven(sTag);
                            sw.WriteLine(pGiven);
                        }
                    }
                }
            }
            foreach (KeyValuePair <string, List <Predicate> > p in dTags)
            {
                foreach (GroundedPredicate gp in p.Value)
                {
                    if (gp.Negation)
                    {
                        continue;
                    }
                    if (gp.Name == "Choice")
                    {
                        continue;
                    }
                    if (!gp.Negation)
                    {
                        sw.WriteLine(gp.GenerateGiven(p.Key));
                    }
                    //sKP = GenerateKnowGivenLine(gp, p.Key, true);
                    //sw.WriteLine(sKP);
                }
            }

            //if (Problem.Domain.HasNonDeterministicActions())
            //    sw.WriteLine("(option opt0)");

            //if (SDRPlanner.SplitConditionalEffects)
            sw.WriteLine("(NotInAction)");

            sw.WriteLine(")");

            CompoundFormula cfGoal = new CompoundFormula("and");

            HashSet <Predicate> lGoalPredicates = new HashSet <Predicate>();

            Goal.GetAllPredicates(lGoalPredicates);


            for (int iTag = 0; iTag < dTags.Count; iTag++)
            {
                if (SDRPlanner.ConsiderStateNegations && iTag == dTags.Count - 1)
                {
                    break;//What is that?
                }
                string sTag = dTags.Keys.ElementAt(iTag);
                foreach (Predicate p in lGoalPredicates)
                {
                    if (!Domain.AlwaysKnown(p) || !Domain.AlwaysConstant(p))
                    {
                        cfGoal.AddOperand(p.GenerateGiven(sTag));
                    }
                }
            }

            if (SDRPlanner.ForceTagObservations)
            {
                foreach (string sTag1 in dTags.Keys)
                {
                    foreach (string sTag2 in dTags.Keys)
                    {
                        if (sTag1 != sTag2)
                        {
                            Predicate gpNot = Predicate.GenerateKNot(new Constant(Domain.TAG, sTag1), new Constant(Domain.TAG, sTag2));
                            cfGoal.AddOperand(gpNot);
                        }
                    }
                }
            }

            sw.WriteLine("(:goal " + cfGoal + ")");
            //sw.WriteLine("))");
            if (MetricStatement != null)
            {
                sw.WriteLine(MetricStatement);
            }
            sw.WriteLine(")");
            sw.Flush();

            return(ms);
        }
Example #53
0
 public GoalCreatedDomainEvent(Goal goal)
 {
     Goal = goal;
 }
Example #54
0
        /// <summary>
        /// Run the code examples.
        /// </summary>
        /// <param name="user">The DFP user object running the code examples.</param>
        public void Run(DfpUser user)
        {
            // Get the LineItemService.
            LineItemService lineItemService =
                (LineItemService)user.GetService(DfpService.v201605.LineItemService);

            // Set the order that all created line items will belong to and the
            // placement ID to target.
            long orderId = long.Parse(_T("INSERT_ORDER_ID_HERE"));

            long[] targetPlacementIds = new long[] { long.Parse(_T("INSERT_PLACEMENT_ID_HERE")) };

            // Create inventory targeting.
            InventoryTargeting inventoryTargeting = new InventoryTargeting();

            inventoryTargeting.targetedPlacementIds = targetPlacementIds;

            // Create geographical targeting.
            GeoTargeting geoTargeting = new GeoTargeting();

            // Include the US and Quebec, Canada.
            Location countryLocation = new Location();

            countryLocation.id = 2840L;

            Location regionLocation = new Location();

            regionLocation.id = 20123L;
            geoTargeting.targetedLocations = new Location[] { countryLocation, regionLocation };

            Location postalCodeLocation = new Location();

            postalCodeLocation.id = 9000093;

            // Exclude Chicago and the New York metro area.
            Location cityLocation = new Location();

            cityLocation.id = 1016367L;

            Location metroLocation = new Location();

            metroLocation.id = 200501L;
            geoTargeting.excludedLocations = new Location[] { cityLocation, metroLocation };

            // Exclude domains that are not under the network's control.
            UserDomainTargeting userDomainTargeting = new UserDomainTargeting();

            userDomainTargeting.domains  = new String[] { "usa.gov" };
            userDomainTargeting.targeted = false;

            // Create day-part targeting.
            DayPartTargeting dayPartTargeting = new DayPartTargeting();

            dayPartTargeting.timeZone = DeliveryTimeZone.BROWSER;

            // Target only the weekend in the browser's timezone.
            DayPart saturdayDayPart = new DayPart();

            saturdayDayPart.dayOfWeek = Google.Api.Ads.Dfp.v201605.DayOfWeek.SATURDAY;

            saturdayDayPart.startTime        = new TimeOfDay();
            saturdayDayPart.startTime.hour   = 0;
            saturdayDayPart.startTime.minute = MinuteOfHour.ZERO;

            saturdayDayPart.endTime        = new TimeOfDay();
            saturdayDayPart.endTime.hour   = 24;
            saturdayDayPart.endTime.minute = MinuteOfHour.ZERO;

            DayPart sundayDayPart = new DayPart();

            sundayDayPart.dayOfWeek = Google.Api.Ads.Dfp.v201605.DayOfWeek.SUNDAY;

            sundayDayPart.startTime        = new TimeOfDay();
            sundayDayPart.startTime.hour   = 0;
            sundayDayPart.startTime.minute = MinuteOfHour.ZERO;

            sundayDayPart.endTime        = new TimeOfDay();
            sundayDayPart.endTime.hour   = 24;
            sundayDayPart.endTime.minute = MinuteOfHour.ZERO;

            dayPartTargeting.dayParts = new DayPart[] { saturdayDayPart, sundayDayPart };


            // Create technology targeting.
            TechnologyTargeting technologyTargeting = new TechnologyTargeting();

            // Create browser targeting.
            BrowserTargeting browserTargeting = new BrowserTargeting();

            browserTargeting.isTargeted = true;

            // Target just the Chrome browser.
            Technology browserTechnology = new Technology();

            browserTechnology.id                 = 500072L;
            browserTargeting.browsers            = new Technology[] { browserTechnology };
            technologyTargeting.browserTargeting = browserTargeting;

            // Create an array to store local line item objects.
            LineItem[] lineItems = new LineItem[5];

            for (int i = 0; i < 5; i++)
            {
                LineItem lineItem = new LineItem();
                lineItem.name      = "Line item #" + i;
                lineItem.orderId   = orderId;
                lineItem.targeting = new Targeting();

                lineItem.targeting.inventoryTargeting  = inventoryTargeting;
                lineItem.targeting.geoTargeting        = geoTargeting;
                lineItem.targeting.userDomainTargeting = userDomainTargeting;
                lineItem.targeting.dayPartTargeting    = dayPartTargeting;
                lineItem.targeting.technologyTargeting = technologyTargeting;

                lineItem.lineItemType  = LineItemType.STANDARD;
                lineItem.allowOverbook = true;

                // Set the creative rotation type to even.
                lineItem.creativeRotationType = CreativeRotationType.EVEN;

                // Set the size of creatives that can be associated with this line item.
                Size size = new Size();
                size.width         = 300;
                size.height        = 250;
                size.isAspectRatio = false;

                // Create the creative placeholder.
                CreativePlaceholder creativePlaceholder = new CreativePlaceholder();
                creativePlaceholder.size = size;

                lineItem.creativePlaceholders = new CreativePlaceholder[] { creativePlaceholder };

                // Set the line item to run for one month.
                lineItem.startDateTimeType = StartDateTimeType.IMMEDIATELY;
                lineItem.endDateTime       =
                    DateTimeUtilities.FromDateTime(System.DateTime.Today.AddMonths(1), "America/New_York");

                // Set the cost per unit to $2.
                lineItem.costType    = CostType.CPM;
                lineItem.costPerUnit = new Money();
                lineItem.costPerUnit.currencyCode = "USD";
                lineItem.costPerUnit.microAmount  = 2000000L;

                // Set the number of units bought to 500,000 so that the budget is
                // $1,000.
                Goal goal = new Goal();
                goal.goalType        = GoalType.LIFETIME;
                goal.unitType        = UnitType.IMPRESSIONS;
                goal.units           = 500000L;
                lineItem.primaryGoal = goal;

                lineItems[i] = lineItem;
            }

            try {
                // Create the line items on the server.
                lineItems = lineItemService.createLineItems(lineItems);

                if (lineItems != null)
                {
                    foreach (LineItem lineItem in lineItems)
                    {
                        Console.WriteLine("A line item with ID \"{0}\", belonging to order ID \"{1}\", and" +
                                          " named \"{2}\" was created.", lineItem.id, lineItem.orderId, lineItem.name);
                    }
                }
                else
                {
                    Console.WriteLine("No line items created.");
                }
            } catch (Exception e) {
                Console.WriteLine("Failed to create line items. Exception says \"{0}\"",
                                  e.Message);
            }
        }
Example #55
0
 private static void Plan(List <Action> actions, Goal goal, List <Context> environment)
 {
 }
Example #56
0
 public Goal Post(int userId, [FromBody] Goal goal)
 {
     return(goalService.CreateGoal(userId, goal));
 }
Example #57
0
 public Goal Put(int userId, int id, [FromBody] Goal goal)
 {
     return(goalService.UpdateGoal(userId, id, goal));
 }
Example #58
0
        public static void GradeStudentGoal(User grader)
        {
            var courseStore = new CourseStore();
            var gradeStore  = new GradeStore();
            var goalStore   = new GoalStore();

            List <Course> courses = GetCourses(grader, courseStore).ToList();


            Course course = CoursePresenter.AskForCourseById();

            if (course == null)
            {
                return;
            }
            if (grader.HasLevel(UserLevel.Teacher) && course.CourseTeacher != grader.UserName)
            {
                Console.WriteLine("Du är ej lärare för den kursen");
                UserInput.WaitForContinue();
                return;
            }

            User           student = UserManagerPresenter.SearchForUser(UserLevel.Student);
            EducationClass klass   = student.GetClass();

            if (klass == null)
            {
                Console.WriteLine("Användaren är inte en student");
                UserInput.WaitForContinue();
                return;
            }
            if (!klass.HasCourse(course.CourseId))
            {
                Console.WriteLine("Klassen läser ej den kursen");
                UserInput.WaitForContinue();
                return;
            }

            List <Goal> goals = goalStore.FindByCourseId(course.CourseId).ToList();

            foreach (Goal g in goals)
            {
                Console.WriteLine($"  {g.GoalId}: {g.Description.Truncate(95)}");
            }

            Console.WriteLine();
            string goalToGrade = UserInput.GetInput <string>("Välj mål att betygsätta:");

            Goal goal = goals.SingleOrDefault(g => g.GoalId == goalToGrade);

            if (goal == null)
            {
                Console.WriteLine($"Finns inget mål med id {goalToGrade}");
                UserInput.WaitForContinue();
                return;
            }

            GradeLevel gradeLevel = AskForGrade();

            var grade = new Grade
            {
                StudentId  = student.UserName,
                CourseId   = course.CourseId,
                CourseGoal = goal.GoalId,
                Result     = gradeLevel
            };

            Console.WriteLine();
            Console.WriteLine($"Student: {student.FullName()}");
            Console.WriteLine($"Kursmål: {goal.Description.Truncate(95)}");
            Console.WriteLine($"Betyg:   {grade.Result}");

            bool confirm = UserInput.AskConfirmation("Spara betyg?");

            if (confirm)
            {
                Grade existingGrade = gradeStore.FindById(grade.GradeId);
                if (existingGrade == null)
                {
                    gradeStore.AddItem(grade);
                    gradeStore.Save();
                }
                else
                {
                    gradeStore.GradeStudent(student, grade);
                    gradeStore.Save();
                }
            }

            Console.WriteLine();
            UserInput.WaitForContinue();
        }
Example #59
0
    public override void Process()
    {
        Goal child = GetActiveGoal();

        if (child.IsInactive)
        {
            child.Activate();
        }

        IReadOnlyCollection <DataCreature> creatures = owner.Memory.Creatures.Read();
        Agent friend           = null;
        float distanceToFriend = Mathf.Infinity;

        foreach (DataCreature data in creatures)
        {
            if (!data.creature)
            {
                continue;
            }
            Agent agent = data.creature.agentCreature;
            if (agent == owner)
            {
                continue;
            }

            if (data.RegistrationDate < Time.time - 0.5f || !agent.gameObject.activeSelf)
            {
                continue;
            }

            if (!agent.IsThinking || agent.IsThrow)
            {
                continue;
            }

            float distanceToAgent = Vector3.Distance(owner.transform.position, agent.transform.position);
            if (distanceToAgent >= distanceToFriend)
            {
                continue;
            }

            /*bool recentTalk = false;
             * IReadOnlyCollection<DataCommunication> communications = owner.Memory.Communications.Read();
             * foreach(DataCommunication com in communications){
             *  if(com.creature == agent.Creature && com.subject == memoryType){
             *      recentTalk = true;
             *      break;
             *  }
             * }*/

            if (GetCreatureFilter()(agent.Creature))
            {
                friend           = agent;
                distanceToFriend = distanceToAgent;
            }
        }

        switch (communicateState)
        {
        case CommunicateState.Search:
            if (child.HasFailed)
            {
                AddSubgoal(new GoalSeekNest(owner));
                communicateState = CommunicateState.SeekNest;
            }

            if (!friend)
            {
                break;
            }

            child.Abort();
            asked.Add(friend.Creature);

            if (friend.Thinking.RequestGoal(GoalCommunication_Evaluator.Instance))
            {
                Squad squad = new Squad(owner, friend);
                AddSubgoal(new GoalShare(owner, friend, memoryType, squad));
                friend.Thinking.ActiveGoal = new GoalShare(friend, owner, memoryType, squad);
                communicateState           = CommunicateState.Share;
            }
            else
            {
                AddSubgoal(new GoalSearchCreature(owner, GetCreatureFilter()));
            }
            break;

        case CommunicateState.SeekNest:
            if (child.HasFailed)
            {
                AddSubgoal(new GoalWander(owner));
                communicateState = CommunicateState.Wander;
            }

            if (!friend)
            {
                break;
            }

            child.Abort();
            asked.Add(friend.Creature);

            if (friend.Thinking.RequestGoal(GoalCommunication_Evaluator.Instance))
            {
                Squad squad = new Squad(owner, friend);
                AddSubgoal(new GoalShare(owner, friend, memoryType, squad));
                friend.Thinking.ActiveGoal = new GoalShare(friend, owner, memoryType, squad);
                communicateState           = CommunicateState.Share;
            }
            else
            {
                AddSubgoal(new GoalSearchCreature(owner, GetCreatureFilter()));
            }
            break;

        case CommunicateState.Wander:
            if (!friend)
            {
                break;
            }

            child.Abort();
            asked.Add(friend.Creature);

            if (friend.Thinking.RequestGoal(GoalCommunication_Evaluator.Instance))
            {
                Squad squad = new Squad(owner, friend);
                AddSubgoal(new GoalShare(owner, friend, memoryType, squad));
                friend.Thinking.ActiveGoal = new GoalShare(friend, owner, memoryType, squad);
                communicateState           = CommunicateState.Share;
            }
            else
            {
                AddSubgoal(new GoalSearchCreature(owner, GetCreatureFilter()));
            }
            break;

        case CommunicateState.Share:
            if (child.HasFailed)
            {
                AddSubgoal(new GoalSearchCreature(owner, GetCreatureFilter()));
                communicateState = CommunicateState.Search;
            }
            break;
        }

        base.ProcessSubgoals();
    }
Example #60
0
 public bool Create(Goal goal)
 {
     return(GoalDb.Create(goal));
 }