private IEnumerator ThinkCoroutine() { thinkTime = thinkDelay * Random.Range(-randomness, randomness); while (currentState == BrainState.Thinking) { walker.Walk(0); yield return(new WaitForFixedUpdate()); thinkTime += Time.fixedDeltaTime; if (thinkTime >= thinkDelay) { if (followTransform != null) { currentState = BrainState.Chasing; } else { thinkTime = thinkDelay * Random.Range(-randomness, randomness); } } } StateCoroutineSwitch(); }
private void SelectNodeType(out BrainNode t_node, string t_nodeName, string t_nodeType) { switch (t_nodeType) { case "Task": t_node = new BrainTask(); MethodInfo method = typeof(Brain).GetMethod(t_nodeName, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy); ((BrainTask)t_node).taskAction = (BrainAction)Delegate.CreateDelegate(typeof(BrainAction), this, method); break; case "Sequence": t_node = new BrainSequence(); break; case "Selector": t_node = new BrainSelector(); method = typeof(Brain).GetMethod(t_nodeName, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy); ((BrainSelector)t_node).condition = (BrainSelectorCondition)Delegate.CreateDelegate(typeof(BrainSelectorCondition), this, method); break; case "State": t_node = new BrainState(); break; default: t_node = new BrainNode(); break; } t_node.nodeName = t_nodeName; }
private void LoadBeaviorTree(BrainState t_state) { // Read JSON... string jsonPath = Application.persistentDataPath + "/" + t_state.nodeName + ".json"; string jsonString = File.ReadAllText(jsonPath); JSONObject SMJson = (JSONObject)JSON.Parse(jsonString); BehaviorTree bt = new BehaviorTree { btName = t_state.nodeName }; bt.bt_initialNode = new BrainNode(); SelectNodeType(out bt.bt_initialNode, SMJson["entryNode"]["nodeName"], SMJson["entryNode"]["nodeType"]); if (!bt_nodes.ContainsKey(bt.bt_initialNode.nodeName)) { bt_nodes.Add(bt.bt_initialNode.nodeName, bt.bt_initialNode); } // Rest of the states foreach (JSONObject btNode in SMJson["nodes"]) { BrainNode newNode = new BrainNode(); SelectNodeType(out newNode, btNode["nodeName"], btNode["nodeType"]); if (!bt_nodes.ContainsKey(newNode.nodeName)) { bt_nodes.Add(newNode.nodeName, newNode); } } // Entry point transitions foreach (JSONArray jsonTransition in SMJson["entryNode"]["outputs"]) { BrainTransition transition = new BrainTransition { targetState = bt_nodes[jsonTransition[1]] }; bt.bt_initialNode.transitions.Add(jsonTransition[1], transition); } // Rest of the transitions foreach (JSONObject state in SMJson["nodes"]) { foreach (JSONArray jsonTransition in state["outputs"]) { BrainTransition transition = new BrainTransition { targetState = bt_nodes[jsonTransition[1]] }; bt_nodes[jsonTransition[0]].transitions.Add(jsonTransition[1], transition); } } t_state.behavior = bt; }
private IEnumerator ThinkCoroutine() { thinkTime = thinkDelay * Random.Range(-randomness, randomness); while (currentState == BrainState.Thinking) { walker.Walk(0); yield return(new WaitForFixedUpdate()); thinkTime += Time.fixedDeltaTime; if (thinkTime >= thinkDelay) { if (feet.IsOnGround == false) { currentState = BrainState.Floating; } else if (avoidTransform != null) { currentState = BrainState.Fleeing; } else if (followBody != null && followBody.Visible == true) { currentState = BrainState.Chasing; } else { thinkTime = thinkDelay * Random.Range(-randomness, randomness); } } } currentStateCoroutine = null; StateCoroutineSwitch(); }
protected void SetState(BrainState state) { if (data.avatar.animator != null) { data.avatar.animator.SetInteger(data.avatar.AnimParameter, (int)state); } }
protected void AddSpawnEntry(NpcCustomEntryId id, int timeToSpawnsecs, int amount, float amountMod, BrainState brainState = BrainState.DefenceTownEventMove) { int num1 = 0; int num2 = (int)((double)amount * (double)amountMod); for (int index1 = 1; index1 <= num2; ++index1) { int index2 = index1 % this.MovingPaths.Count; if (index2 == 0) { num1 += 2000; } NPCEntry entry = NPCMgr.GetEntry((uint)id); if (entry.Rank >= CreatureRank.Boss) { index2 = Utility.Random(0, this.MovingPaths.Count - 1); } this.NpcEntries.Add(new NpcSpawnEntry() { BrainState = brainState, TimeToSpawnMillis = timeToSpawnsecs * 1000 + num1, NpcEntry = entry, MovingPoints = (List <Vector3>) this.MovingPaths[index2] }); } }
public async Task OnTurn_Greeting_Async_Twice_Test(string request1, string expectedResponse1, string request2, string expectedResponse2) { // Arrange var brainState = new BrainState(); var turnContextMock1 = new Mock <ITurnContext>(); var activity1 = new Activity { Type = ActivityTypes.Message, Text = request1 }; turnContextMock1.Setup(p => p.Activity).Returns(activity1); _conversationStateProviderMock.Setup(p => p.GetConversationState <BrainState>(turnContextMock1.Object)) .Returns(brainState); var turnContextMock2 = new Mock <ITurnContext>(); var activity2 = new Activity { Type = ActivityTypes.Message, Text = request2 }; turnContextMock2.Setup(p => p.Activity).Returns(activity2); _conversationStateProviderMock.Setup(p => p.GetConversationState <BrainState>(turnContextMock2.Object)) .Returns(brainState); // Act await _echoBot.OnTurn(turnContextMock1.Object); await _echoBot.OnTurn(turnContextMock2.Object); // Assert turnContextMock1.Verify(p => p.Activity, Times.AtLeastOnce); turnContextMock1.Verify(p => p.SendActivity(expectedResponse1, null, null), Times.Never); turnContextMock2.Verify(p => p.Activity, Times.AtLeastOnce); turnContextMock2.Verify(p => p.SendActivity(expectedResponse2, null, null), Times.AtMostOnce); }
private BrainCommand CommandInReproductionState(BrainInput data) { int emptyCellDirection; if (data.Health < h1) { State = BrainState.LowHealth; return(new BrainCommand(CreatureAction.Go, FindMostSafeCell(data.Cells))); } else if (data.Energy <= e2) { State = BrainState.Normal; return(CommandInNormalState(data)); } else if ((emptyCellDirection = FindSafeCellForChild(data.Cells)) >= 0) { State = BrainState.Normal; return(new BrainCommand(CreatureAction.Reproduce, emptyCellDirection)); } else if (data.Cells[0].StandingCreatures.Count == 1) { return(new BrainCommand(CreatureAction.Go, FindMostSafeCell(data.Cells))); } else { return(new BrainCommand(CreatureAction.Hit, 0)); } }
private BrainCommand CommandInLowHealthState(BrainInput data) { if (data.Health >= h1) { if (data.Energy > e2) { State = BrainState.Reproduction; return(CommandInReproductionState(data)); } else if (data.Energy < e1) { State = BrainState.LowEnergy; return(CommandInLowEnergyState(data)); } else { State = BrainState.Normal; return(CommandInNormalState(data)); } } else { return(new BrainCommand(CreatureAction.Go, FindMostSafeCell(data.Cells))); } }
private void LoadBrain() { // Read JSON... string jsonPath = Application.persistentDataPath + "/StateMachine.json"; string jsonString = File.ReadAllText(jsonPath); JSONObject SMJson = (JSONObject)JSON.Parse(jsonString); // Entry point BrainState sm_entryState = new BrainState { nodeName = SMJson["entryNode"]["nodeName"] }; sm_states.Add(sm_entryState.nodeName, sm_entryState); sm_initialState = sm_entryState; LoadBeaviorTree(sm_entryState); // Rest of the states foreach (JSONObject state in SMJson["nodes"]) { BrainState newState = new BrainState { nodeName = state["nodeName"] }; sm_states.Add(newState.nodeName, newState); LoadBeaviorTree(newState); } // Entry point transitions foreach (JSONArray jsonTransition in SMJson["entryNode"]["outputs"]) { BrainTransition transition = new BrainTransition { targetState = sm_states[jsonTransition[1]] }; sm_entryState.transitions.Add(jsonTransition[1], transition); } // Rest of the transitions foreach (JSONObject state in SMJson["nodes"]) { foreach (JSONArray jsonTransition in state["outputs"]) { BrainTransition transition = new BrainTransition { targetState = sm_states[jsonTransition[1]] }; sm_states[jsonTransition[0]].transitions.Add(jsonTransition[1], transition); } } }
public BaseBrain(Unit owner, IAIActionCollection actions, BrainState defaultState) { this.m_owner = owner; this.m_defaultState = defaultState; this.m_state = this.m_defaultState; this.m_actions = actions; this.m_IsAggressive = true; }
private void ArrangeByDefault() { var brainState = new BrainState(); //_provider.Setup(p => p.GetConversationState<BrainState>(_context.Object)) // .Returns(brainState); //var retorts = Retorts.Instance(_context.Object, _provider.Object); //Retorts.ReadOnlyFile = true; }
private IEnumerator FleeCoroutine() { float randomizedAvoidDistance = avoidDistance * (1f + Random.Range(-randomness, randomness)); while (currentState == BrainState.Fleeing) { if (avoidTransform != null) { if (Vector2.Distance(transform.position, avoidTransform.position) < randomizedAvoidDistance) { float horizontalToTarget = Vector2.Dot(avoidTransform.position - transform.position, transform.right); float verticalToTarget = Vector2.Dot(avoidTransform.position - transform.position, transform.up); if (walker.currentWalkDirection == 0 && Mathf.Abs(verticalToTarget) < Mathf.Abs(horizontalToTarget) && CheckAbove() != DetectionResult.Avoid && Random.Range(0f, randomness) < jumpiness) { jumper.Jump(); } else if (horizontalToTarget > 0f) { if (CheckLeft() != DetectionResult.Avoid) { walker.Walk(-1); } else { walker.Walk(0); jumper.Jump(); } } else { if (CheckRight() != DetectionResult.Avoid) { walker.Walk(1); } else { walker.Walk(0); jumper.Jump(); } } } else { walker.Walk(0); } } else { currentState = BrainState.Thinking; } yield return(new WaitForFixedUpdate()); } currentStateCoroutine = null; StateCoroutineSwitch(); }
/// <summary> /// Creates new instance of greetings skill to process given phrase. /// </summary> /// <param name="context">current dialog context</param> /// <param name="conversationStateProvider">provider for passing the state from context</param>> private Greetings(ITurnContext context, IConversationStateProvider conversationStateProvider) { _state = conversationStateProvider.GetConversationState <BrainState>(context); // Create new DialogUtils to hide logic in sub-methods if (_dialogUtils == null) { _dialogUtils = new DialogUtils(context, conversationStateProvider); } }
/// <summary> /// Moves this Unit to the given position and then assumes arrivedState /// </summary> /// <param name="pos"></param> /// <param name="arrivedState">The BrainState to enter once arrived</param> /// <remarks>Requires Brain</remarks> public void MoveToThenEnter(IHasPosition pos, bool findPath, BrainState arrivedState) { if (CheckBrain()) { //m_brain.StopCurrentAction(); m_Movement.MoveTo(pos.Position, findPath); m_brain.CurrentAction = new AIMoveThenEnterAction(this, arrivedState); } }
public Brain(double alpha) { this.Alpha = alpha; h1 = CreatureParameters.h1(alpha); e1 = CreatureParameters.e1(alpha); e2 = CreatureParameters.e2(alpha); absorbAble = CreatureParameters.AbsorbAble(alpha); State = BrainState.Normal; }
public void ClearCombat(BrainState newState) { if ((m_owner is NPC)) { ((NPC)m_owner).ThreatCollection.Clear(); } m_owner.IsInCombat = false; m_owner.MarkUpdate(UnitFields.DYNAMIC_FLAGS); State = newState; }
public void ChangeState(Action newAction) { _currentState?.End(this); CurrentAction = newAction; _currentState = _states[newAction]; _currentState?.Begin(this); onChangeAction?.Invoke(this, EventArgs.Empty); }
public BaseBrain(Unit owner, IAIActionCollection actions, BrainState defaultState) { m_owner = owner; m_defaultState = defaultState; m_state = m_defaultState; m_actions = actions; m_IsAggressive = true; }
/// <summary> /// Changes the current state in the AI State Machine /// </summary> /// <param name="brainState"></param> public virtual void ChangeBrainState(BrainState brainState) { // perform any exit operations from the previous state if (currentBrainState != null) { currentBrainState.Exit(); } // save the new brain state and enter currentBrainState = brainState; currentBrainState.Enter(this); }
private AIAction _getActionFromState(BrainState state) { AIAction result; switch (state) { case BrainState.Combat: { result = new AI.Actions.States.AICombatAction(this.Owner); break; } case BrainState.Dead: { result = new AI.Actions.States.AIDeadAction(this.Owner); break; } case BrainState.Evade: { result = new AI.Actions.States.AIEvadeAction(this.Owner); break; } case BrainState.Follow: { result = new AI.Actions.States.AIFollowAction(this.Owner); break; } case BrainState.Guard: { result = new AI.Actions.States.AIGuardMasterAction(this.Owner); break; } case BrainState.Idle: { result = new AI.Actions.States.AIIdleAction(this.Owner); break; } case BrainState.Roam: { result = new AI.Actions.States.AIRoamAction(this.Owner); break; } default: throw new Exception("dont have that state to generate a new action"); } return(result); }
private void HealthDecay() { if (!DoHealthDecay) { return; } if (Health == 0) { State = BrainState.Dead; return; } Health--; }
public void ClearCombat(BrainState newState) { var npc = m_owner as NPC; if (npc != null) { npc.ThreatCollection.Clear(); npc.Damages.Clear(); } m_owner.IsInCombat = false; m_owner.MarkUpdate(UnitFields.DYNAMIC_FLAGS); State = newState; }
private IEnumerator ChaseCoroutine() { while (currentState == BrainState.Chasing) { if (followBody != null && followBody.Visible == true) { float horizontalToTarget = Vector2.Dot(followBody.transform.position - transform.position, transform.right); if (horizontalToTarget > detectionWidth / 2f && CheckRight() != DetectionResult.Avoid) { if (walker.currentWalkDirection == -1) { currentState = BrainState.Thinking; } else { walker.Walk(1); } } else if (horizontalToTarget < -detectionWidth / 2f && CheckLeft() != DetectionResult.Avoid) { if (walker.currentWalkDirection == 1) { currentState = BrainState.Thinking; } else { walker.Walk(-1); } } else { if (CheckAbove() != DetectionResult.Avoid) { jumper.Jump(); } currentState = BrainState.Thinking; } } else { currentState = BrainState.Thinking; } yield return(new WaitForFixedUpdate()); } currentStateCoroutine = null; StateCoroutineSwitch(); }
public void UserNameTest() { // Arrange var brainState = new BrainState(); _provider.Setup(p => p.GetConversationState <BrainState>(_context.Object)) .Returns(brainState); // Act var actual = _utils.UserName(); // Assert Assert.NotNull(actual); }
public void GetInstanceThroughFactoryTest() { // Arrange var brainState = new BrainState(); _provider.Setup(p => p.GetConversationState <BrainState>(_context.Object)) .Returns(brainState); var retorts = SkillFactory.GetInstance().GetSkill("retorts", _context.Object, _provider.Object); // Act // Assert Assert.NotNull(retorts); }
public void AuthorHasTextTest(string author) { // Arrange var brainState = new BrainState(); _provider.Setup(p => p.GetConversationState <BrainState>(_context.Object)) .Returns(brainState); // Act var actual = _utils.Author; // Assert Assert.Equal(author, actual.Text); }
public void ClearCombat(BrainState newState) { NPC owner = this.m_owner as NPC; if (owner != null) { owner.ThreatCollection.Clear(); owner.Damages.Clear(); } this.m_owner.IsInCombat = false; this.m_owner.MarkUpdate((UpdateFieldId)UnitFields.DYNAMIC_FLAGS); this.State = newState; }
public void AuthorHasRightTypeTest() { // Arrange var brainState = new BrainState(); _provider.Setup(p => p.GetConversationState <BrainState>(_context.Object)) .Returns(brainState); // Act var actual = _utils.Author; // Assert Assert.IsType <Activity>(actual); }
public void EnterState(BrainState state) { Logging.LogManager.DefaultLogger.Trace(this.Owner.DynamicID.ToString() + " " + state.ToString()); if (this._currentAction != null) { _currentAction.Stop(); } _state = state; _currentAction = _getActionFromState(_state); _currentAction.Start(); _currentAction.Target = null; //for roam for example. }
public void EnterState(BrainState state, Actor target) { Logging.LogManager.DefaultLogger.Trace(this.Owner.DynamicID.ToString() + " " + state.ToString()); if (this._currentAction != null) { //dejar de hacer lo que esta haciendo actualmente _currentAction.Stop(); } _state = state; _currentAction = _getActionFromState(_state); _currentAction.Start(); _currentAction.Target = target; }
public AIAction this[BrainState state] { get { return Actions[(int)state]; } set { var oldAction = Actions[(int)state]; if (oldAction == value) return; Actions[(int)state] = value; var brain = m_owner.Brain; if (brain != null && brain.State == state && brain.CurrentAction == oldAction) { // we can quite safely assume that the Brain is using this collection // owner already selected the action -> override it brain.CurrentAction = value; } } }
/// <summary> /// Moves this Unit to the given position and then assumes arrivedState /// </summary> /// <param name="pos"></param> /// <param name="arrivedState">The BrainState to enter once arrived</param> /// <remarks>Requires Brain</remarks> public void MoveToThenEnter(IHasPosition pos, BrainState arrivedState) { MoveToThenEnter(pos, true, arrivedState); }
public void HandleChangeState(GameMsg msg) { // swap states ChangeStateMsg statemsg = msg as ChangeStateMsg; if (statemsg != null) { #if BRAIN_DEBUG Debug.Log("Got ChangeStateMsg = " + statemsg.state); #endif // convert string to classname Type type = brainStates.GetType(); if (type == null) return; PropertyInfo state = type.GetProperty(statemsg.state); if (state == null) { Debug.Log("Brain : HandleChangeState(" + statemsg.state + ") Can't find state!"); return; } BrainState next = state.GetValue(brainStates, null) as BrainState; if (next != null) { // save name next.Name = statemsg.state; next.Args = statemsg.args; // cleanup old state if (current != null) current.Cleanup(); // set current = next; // init new state if (current != null) current.Init(); } else { Debug.LogWarning("ChangeStateMsg: unknown state - " + statemsg.state); } } }
/// <summary> /// Moves this Unit to the given position and then assumes arrivedState /// </summary> /// <param name="pos"></param> /// <param name="arrivedState">The BrainState to enter once arrived</param> /// <remarks>Requires Brain</remarks> public void MoveToThenEnter(ref Vector3 pos, BrainState arrivedState) { MoveToThenEnter(ref pos, true, arrivedState); }
public AIMoveThenEnterAction(Unit owner, BrainState arrivedState) : base(owner) { ArrivedState = arrivedState; }
public TraumaStates( TraumaBrain brain ) { _beginscenario = new BeginScenario(); _endscenario = new EndScenario(); _assessment = new Assessment(); }
public MobBrain(NPC owner, BrainState defaultState) : base(owner, defaultState) { }
public MobBrain(NPC owner, IAIActionCollection actions, BrainState defaultState) : base(owner, actions, defaultState) { }
public BaseBrain(Unit owner, BrainState defaultState) : this(owner, new DefaultAIActionCollection(), defaultState) { }
public virtual AIAction this[BrainState state] { get { return Actions[(int)state]; } set { Actions[(int)state] = value; } }
public void SetAction(BrainState state, AIAction action) { Actions[(int)state] = action; }
public bool Contains(BrainState state) { return Actions[(int)state] != null; }