public override void Execute(AIAction action) { if (enemyDead) { EnemyDead(); return; } //Debug.Log("Doing " + action.Description); switch (action.ActionId) { case AIAgentManager.ActionId.Shoot: Shoot(action); break; case AIAgentManager.ActionId.Chase: Chase(action); break; case AIAgentManager.ActionId.Flee: Flee(action); break; case AIAgentManager.ActionId.Die: Die(action); break; default: Patrol(action); break; } }
private void Die(AIAction action) { anim.SetBool(hash.deadBool, true); enemyDead = true; Debug.Log("Enemy Dying."); }
private void Chase(AIAction action) { Vector3 sightingDeltaPos = enemySight.personalLastSighting - transform.position; // If the the last personal sighting of the player is not close... if (sightingDeltaPos.sqrMagnitude > 4f) { // ... set the destination for the NavMeshAgent to the last personal sighting of the player. nav.destination = enemySight.personalLastSighting; } // Set the appropriate speed for the NavMeshAgent. nav.speed = chaseSpeed; // If near the last personal sighting... if (nav.remainingDistance < nav.stoppingDistance) { // ... increment the timer. chaseTimer += Time.deltaTime; // If the timer exceeds the wait time... if (chaseTimer >= chaseWaitTime) { // ... reset last global sighting, the last personal sighting and the timer. lastPlayerSighting.position = lastPlayerSighting.resetPosition; enemySight.personalLastSighting = lastPlayerSighting.resetPosition; chaseTimer = 0f; } } else { // If not near the last sighting personal sighting of the player, reset the timer. chaseTimer = 0f; } }
private void SetFree() { _isOccupied = false; _actualAction = AIAction.Free; Status = AIMovementStatus.Walk; //CancelPreviousActions(); }
public override void SetAction(AIAction act) { base.SetAction(act); randomMoveAction = (RandomMoveAIAction)act; //Decide the number of displacements if (randomMoveAction.totalDisplacementsMin == randomMoveAction.totalDisplacementsMax) { totalDisplacements = randomMoveAction.totalDisplacementsMax; } else { totalDisplacements = Random.Range(randomMoveAction.totalDisplacementsMin, randomMoveAction.totalDisplacementsMax + 1); } if (Random.Range(0f, 1f) < 0.5f) { leftRight = -1; } else { leftRight = 1; } if (totalDisplacements > 0) { SetNewParameters(); } }
override protected void UpdateExecutor() { if (actionsList.Count > 0) { AIAction action = actionsList[currentActionIndex]; switch (action.actionType) { case AIAction.Type.SPIDER_BITE: currentExecutor = spiderBiteExecutor; currentExecutor.SetAction(action); break; case AIAction.Type.SPIDER_INFECT: currentExecutor = spiderInfectExecutor; currentExecutor.SetAction(action); break; default: base.UpdateExecutor(); break; } } else { base.UpdateExecutor(); } }
// Public Methods public void ScheduleAction(AIAction newAction) { if(active) actionQueue.Push(newAction); else SetActive(newAction); }
protected void ActionPlanning() { if (curAction == AIAction.IDEL) { curAction = AIAction.SEARCH; } }
IEnumerator CPUTUrn(BoardManager bm, Actor ai) { List <AIAction> aiaction = new List <AIAction>(); foreach (AIGoal goal in aigoals) { yield return(goal.CalculateActions(aiaction, bm, ai)); } //choose and action to perform //sort the action list //ai.Attack(); AIAction action = GetActionToUSe(aiaction); //AIAction action = new MoveToPlayerAction(ai, new MapCoords(0, 0)); Debug.Log("Choosen score: " + action.GetScore()); if (action.GetScore() != 0) { ai.StartCoroutine( action.ExecuteAction(ai, bm)); } //execute action }
private void RemoveCurrentAction(AIAction action) { action.RemoveEventListener(this.gameObject); actionSequence.RemoveAt(0); Destroy(this.transform.Find("CurrentAction").GetComponentInChildren <AIAction>().gameObject); }
private AIAction sOhFuckLetsGoRandom() // I GIVE UP, I'M RANDOM { if (randoWhatsie == 0) { y_row = 1; } int cy = c.getY(); if (cy == (myBoard.height - myBoard.topoffset)) { y_row = -1; } else if (cy == 0) { y_row = 1; } AIAction res = new AIAction(Random.value >= 0.75f ? 1: 0, Random.value >= 0.5f ? y_row : 0, Random.value >= 0.25f ? 1: 0, Random.value >= 0.5f); if (randoWhatsie++ > Random.Range(4, 20) && confused <= 0) { state = 10; return(s1()); } return(res); }
virtual protected void UpdateExecutor() { if (actionsList.Count > 0) { AIAction action = actionsList[currentActionIndex]; //Enemy specific executors should be managed in inherited classes switch (action.actionType) { case AIAction.Type.SELECT_PLAYER: currentExecutor = selectExecutor; break; case AIAction.Type.STANDING_IDLE: currentExecutor = standIdleExecutor; break; case AIAction.Type.LOOK_AT: currentExecutor = lookAtExecutor; break; case AIAction.Type.MOVE: currentExecutor = moveExecutor; break; case AIAction.Type.RANDOM_MOVE: currentExecutor = randomMoveExecutor; break; } currentExecutor.SetAction(action); } }
/// <summary> /// Evaluate the specified action. /// </summary> /// <param name="action">Action.</param> public Appraisal Evaluate(AIAction action) { if (action == null) { throw new ArgumentNullException("Action argument cannot be null."); } List <ICondition> conditions = TacticalMind.Input.FighterConditions; if (conditions == null) { throw new ArgumentNullException("ICondition variable cannot be null."); } if (conditions.Count < 1) { throw new ArgumentNullException("ICondition variable cannot be of length 0."); } // TODO: conditions should be stored per character and there should // probably be a more elegant way to access them. ICondition physicalCondition = conditions [3]; TechniqueProficiency proficiency = ((FightingTechniqueAction)action).Proficiency; if (proficiency == null) { throw new ArgumentNullException("FightingTechniqueAction variable cannot be null."); } float endurance = ((PhysicalCondition)physicalCondition).Condition; Appraisal appraisal = new Appraisal(); // If the current endurance is above the pre-defined // threshold then the basic score will be equal to the // initial score. Otherwise the score will be reduced or // increased by the result of dividing the endurance by // the maximum endurance, depending on whether it's a punch // or a kick. if (endurance >= _modificationThreshold * TacticalMind.MAX_PHYSICAL_CONDITION_VALUE) { appraisal.BasicScore = _initialScore; } else if (proficiency.TechniqueBodyPart.PartType == BodyPartType.LeftArm || proficiency.TechniqueBodyPart.PartType == BodyPartType.RightArm) { appraisal.BasicScore = _initialScore - endurance / TacticalMind.MAX_PHYSICAL_CONDITION_VALUE; } else if (proficiency.TechniqueBodyPart.PartType == BodyPartType.LeftLeg || proficiency.TechniqueBodyPart.PartType == BodyPartType.RightLeg) { appraisal.BasicScore = _initialScore + endurance / TacticalMind.MAX_PHYSICAL_CONDITION_VALUE; } else { appraisal.BasicScore = _initialScore; } return(appraisal); }
public static Type GetStrategyTypeForAction(AIAction action) { Type t; strategyTypesByActionType.TryGetValue(action.GetType(), out t); return(t); }
/// <summary> /// Gets the <see cref="AIAction" /> for the specified <see cref="GameState" />. /// </summary> /// <param name="gameState">The state of the game.</param> /// <returns> /// The <see cref="AIAction" /> for the specified <see cref="GameState" />. /// </returns> public AIAction GetAction(GameState gameState) { if (gameState.Step == 0 || MyTeam == null) { Ball = new Ball(gameState.Ball); MyTeam = new Team(GetParameters(), this); OpponentTeam = new Team(GetParameters(), this); // expect opponent to have the same parameters } // AI entities (wrappers of SimulationEntities) are set accordingly Ball.LoadState(gameState); OpponentTeam.LoadState(gameState, false); // must be loaded before my team! MyTeam.LoadState(gameState, true); SupportPositionsManager.Update(); // new action var currentAction = new AIAction { Step = gameState.Step, PlayerActions = MyTeam.GetActions() }; return(currentAction); }
void CalculateBuffScore(Combat testCombat, AIAction action) { int unitHits = 0; int score = 0; foreach (CombatNode node in testCombat.actorDamageMap) { if (node is BuffCombatNode) { BuffCombatNode n = node as BuffCombatNode; //lets figure out how to establish if the buff is positive or negative if ( (node.target.ActorsController().PlayerControlled() == true && n.buffToApply.IsBuff == false) || (node.target.ActorsController().PlayerControlled() == false && n.buffToApply.IsBuff == true) ) { //This means we're either buffing our allies or debuffing our enemies if (n.target.actorData.buffContainer.CanBuffBeApplied(n.buffToApply)) { action.SetScore(0.5f); } } } } }
public void PostDeserialise() { foreach (var link in m_linkSerialisationMap) { AIAction linkAction = Task.GetActionFromSerialisationID(link.Value); if (linkAction != null) { for (int index = 0; index < m_outputLinks.Count; index++) { if (m_outputLinks[index].linkName == link.Key) { var targetLink = m_outputLinks[index]; targetLink.linkAction = linkAction; m_outputLinks[index] = targetLink; } } } } #if UNITY_EDITOR for (int i = 0; i < m_inputData.Count; i++) { m_inputDataRects.Add(new Rect()); } for (int i = 0; i < m_inputData.Count; i++) { m_outputDataRects.Add(new Rect()); } #endif }
public void Execute(AIAction action) { if (m_actor != null) { m_actor.Execute(action); } }
internal void saveAction(AIAction action, Submarine sub) { sw.WriteLine("Action"); sw.WriteLine("Type"); if (action is PlaceMine) { sw.WriteLine("PlaceMine"); } if (action is LaunchTorpedo) { sw.WriteLine("LaunchTorpedo"); } if (action is Move) { sw.WriteLine("Move"); } sw.WriteLine("End type"); sw.WriteLine("Path"); foreach (Cell cell in action.path) { sw.WriteLine(cell.I + " " + cell.J); } sw.WriteLine("End path"); sw.WriteLine("Submarine"); sw.WriteLine(sub.Number); sw.WriteLine("End submarine"); sw.WriteLine("End action"); sw.Flush(); }
// ------------------------------------------------------------------------------------------------------------------- // Implementation // ------------------------------------------------------------------------------------------------------------------- private bool IsHigherScore(AIAction Action, AIAction BestAction) { // There is no spoon... if (null == BestAction) { return(true); } // The two scores are within the tolerance range if (Mathf.Abs(BestAction.GetPreviousScore() - Action.GetPreviousScore()) <= m_fScoreEqualityTolerance) { // Choose randomly which of these two "equal" scores to go with... if (m_bChooseRandomlyIfScoresEqual) { float r = Random.Range(0.0f, 1.0f); return(0.5f > r); } // An equal score is not enough to change Action! return(false); } if (Action.GetPreviousScore() > BestAction.GetPreviousScore()) { return(true); } return(false); }
/// <summary> /// 这里需要说明Node的key值是上一个节点的消耗+当前行为的消耗 /// </summary> /// <param name="_key">上一个节点的消耗+当前行为的消耗</param> /// <param name="_cost">当前节点的累计消耗</param> /// <param name="_parent">上一级节点</param> /// <param name="_upperAction">当前节点</param> public Node(string _key, float _cost, Node _parent, AIAction _upperAction) { Key = _key; cost = _cost; parent = _parent; upperAction = _upperAction; }
public Model UpdateModel(State currentState, AIAction action, State resultState, double reward) { if (currentState.IsEqual(resultState)) { return(this); } List <KeyValuePair <StateAction, StateReward> > result = new List <KeyValuePair <StateAction, StateReward> >(ModelWorld); StateAction stateAction; StateReward stateReward; stateAction.state = currentState; stateAction.action = action; stateReward = result.Find(x => x.Key.action.IsEqual(action) && x.Key.state.IsEqual(currentState) && x.Value.state.IsEqual(resultState)).Value; if (stateReward == null) { stateReward = new StateReward(); stateReward.reward = reward; stateReward.state = resultState; result.Add(new KeyValuePair <StateAction, StateReward>(stateAction, stateReward)); return(new Model(result)); } if (Math.Abs(stateReward.reward) <= reward) { stateReward.reward = reward; } return(new Model(result)); }
private AIAction s0_1(int xM, int xE, int typeM, int typeE, int xdir, int dshift) // MOVE TO A PREPARED ROW { int cx = c.getX(); if (cx == xM) { state = 2; return(s0_2(xM, xE, typeM, typeE, dshift)); } AIAction res = new AIAction(0, 0); if (cx != xM) { res.dx = xdir; } if (!StillHasTypeAtPos(enemyBoard, myBoard.width - 1 - xE, typeE)) { state = 0; } if (selfAwareness > Random.value && !StillHasTypeAtPos(myBoard, cx, typeM)) { int newx_e = GetNewTargetX(xM, typeM); if (repeats1++ > repeatTheshold || newx_e < 0) { repeats1 = 0; state = 0; } theirInvertedX = newx_e; } return(res); }
public void RemoveAction(AIAction action) { if (Actions.Contains(action)) { Actions.Remove(action); } }
public void Tick() { int count = agents.Count; //todo need to 'instantiate' decisions. Right now they are all the same references for (int i = 0; i < count; i++) { AIInfo agent = agents[i]; agent.decisionDuration = 1f; if (GameTimer.Instance.FrameTimeElapsed(agent.decisionDuration, agent.lastDecisionTime)) { if (agent.action != null) { actionsToSetup.Remove(agent.action); actionsToTeardown.Remove(agent.action); actionsToTick.Remove(agent.action); agent.action.Teardown(); } AIAction action = Decide(agent); Debug.Assert(action != null, "action != null"); actionsToSetup.Add(action); } } count = actionsToSetup.Count; for (int i = 0; i < count; i++) { actionsToSetup[i].OnSetup(); actionsToTick.Add(actionsToSetup[i]); } actionsToSetup.Clear(); count = actionsToTick.Count; for (int i = 0; i < count; i++) { AIAction action = actionsToTick[i]; if (action.Tick()) { // todo use double buffer instead of remove actionsToTick.RemoveAt(i); actionsToTeardown.Add(action); i--; } } count = actionsToTeardown.Count; for (int i = 0; i < count; i++) { actionsToTeardown[i].Teardown(); } actionsToTeardown.Clear(); }
private int ComputeScore(MapPoint point, out AIAction action) { int total = 0; action = AIAction.Walk; // deduct points for high distances from the pawn var distOverall = Mathf.Abs(point.x - m_pawn.GetMapX()) + Mathf.Abs(point.y - m_pawn.GetMapY()); total -= distOverall / 2; // accounting for other pawns... for (int i = 0; i < GameController.GetNumPawns(); i++) { if (i == m_pawn.GetPawnID()) { continue; } // deduct points for remaining far away from other pawns var otherPawn = GameController.GetPawn(i); var distPawn = m_pawn.GetMapPos().Manhattan(otherPawn.GetMapPos()); total -= distPawn / 2; // prefer tiles near other pawns and try to bomb them if (distPawn <= Mathf.Min(m_pawn.BombRange, 3)) { total += 12; action = AIAction.PlaceBomb; } } // heavily penalize tiles that are in immediate blast zones var danger = GameController.ComputeDangerLevel(point); if (danger > 0f) { total -= (int)(Mathf.Max(0.5f, danger) * 60f); } // look for nearby crates, and add points if we can blow up any for (var dir = Cardinal.North; dir <= Cardinal.West; dir++) { var neighbor = GameController.CardinalToDelta(dir) + point; if (Map.IsValid(neighbor) && Map.GetAt(neighbor) == MapTile.Crate) { action = AIAction.PlaceBomb; total += 5; } } // big boost for powerups in this spot, we really want to grab those if (GameController.Powerups.Any(pup => pup.GetMapPos() == point)) { total += 25; } return(total); }
public void StopCurrentAction() { if (_currentAction != null) { _currentAction.Stop(); } _currentAction = null; }
public void ClearActions(AIAction action) { if (action != null) { Actions.Clear(); AddAction(action); } }
public override bool CanDoBoth(AIAction other) { foreach(AIAction subAction in actions){ if(!subAction.CanDoBoth(other)) return false; } return true; }
internal void saveStep(EntityCollection collection, AIAction action, Submarine sub) { sw.WriteLine("Step {0}", LogicService.stepCount); saveCollection(collection); saveAction(action, sub); sw.WriteLine("End step {0}", LogicService.stepCount); sw.Flush(); }
public bool IsEqual(AIAction other) { if (other is WalkerAction) { return((other as WalkerAction).direction == direction); } return(false); }
public void AddAction(AIAction action) { if (!Actions.Contains(action)) { action.Initialize(this); Actions.Add(action); } }
public virtual void OnUpdate() { if(CurrentAction != null) { CurrentAction.Update(); if (CurrentAction.State == AIActionState.FINISH) CurrentAction = CurrentAction.NextAction; } }
private SpiderAIBehaviour spider; // TOREFACTOR - this action must be used for any enemy public override void SetAction(AIAction act) { base.SetAction(act); moveAction = (MoveAIAction)act; string tId = moveAction.targetId; spider = (SpiderAIBehaviour)state.parent; // TOREFACTOR - this action must be used for any enemy if (tId != "player") { state.target = GameObject.Find(tId); } else if(!state.target.activeSelf) { state.target = rsc.enemyMng.SelectTarget(); } switch(moveAction.offsetType) { case AIAction.OffsetType.POSITION_ZERO: direction = new Vector3(0, 0, 0); break; case AIAction.OffsetType.AROUND_WORLD_RELATIVE: direction = new Vector3(0, 0, 1); direction = Quaternion.Euler(0, moveAction.angle, 0) * direction; direction *= moveAction.distance; break; case AIAction.OffsetType.AROUND_ENEMY_RELATIVE: direction = (state.agent.transform.position - state.target.transform.position).normalized; direction = Quaternion.Euler(0, moveAction.angle, 0) * direction; direction *= moveAction.distance; break; } if (moveAction.inertia) state.agent.acceleration = 50; else state.agent.acceleration = 1000; state.agent.speed = moveAction.speed; spider.GetComponent<Animator>().speed = moveAction.speed / 4; state.agent.destination = state.target.transform.position + direction; state.agent.Resume(); elapsedTime = 0f; }
public override void SetAction(AIAction act) { //Debug.Log("Entering LookAt set action"); base.SetAction(act); lookAtAction = (LookAtAIAction)act; string tId = lookAtAction.targetId; if (tId != "player") { state.target = GameObject.Find(tId); } else if (!state.target.activeSelf) { state.target = rsc.enemyMng.SelectTarget(); } direction = state.target.transform.position - state.agent.transform.position; state.agent.Stop(); //Debug.Log("Exiting LookAt set action"); }
public override void SetAction(AIAction act) { base.SetAction(act); spiderBiteAction = (SpiderBiteAIAction)act; spider = (SpiderAIBehaviour)state.parent; state.agent.Stop(); if(spider.timeSinceLastAttack > spiderBiteAction.minimumTimeSinceLastAttack) { spider.GetComponent<Animator>().SetTrigger("bite"); spider.timeSinceLastAttack = 0f; spider.biting = true; discardedAttack = false; } else { discardedAttack = true; } }
private void SetActive(AIAction toActivate) { active = toActivate; activeEnumerator = active.GetEnumerator(); }
// Public Methods public virtual bool CanDoBoth(AIAction other) { return false; }
public void AddAction(AIAction action) { if(!Actions.Contains(action)) { action.Initialize(this); Actions.Add(action); } }
private IEnumerator DetermineAndTakeNextAction() { /*********************************************************************************** * AI is a combination of a miniature decision tree and weighted choices. * The decision tree portion determines goal and helps narrow down choices * * The weighted actions help the AI pick what appears to be the best action given * the known circumstances. **********************************************************************************/ Debug.Log("Determining Action"); //0. Check if ai has time units remaining if (HasMovesLeft()) { Debug.Log("Has Moves"); //1. Check Hostility. If hostile the goal is to kill opposing characters in facility if (tags.Contains("hostile") || tags.Contains("Predatory")) { Debug.Log("Hostile"); } else { //2. If not hostile find map exits and sort by distance. If not violent the goal is to escape //Create Distance sorted list of exits List<GameObject> exits = GameObject.FindGameObjectsWithTag("ExitTrigger").ToList(); exits.Sort(delegate(GameObject c1, GameObject c2) { return (this.transform.position - c1.transform.position).sqrMagnitude.CompareTo ((this.transform.position - c2.transform.position).sqrMagnitude); }); Debug.Log("Created Exit List: " + exits.Count); //3. Check if enemies are blocking viable exits Transform targetOfOpportunity = null; //foreach (Transform enemy in EnemiesInSight) { // Vector3 targetDir // if() //} //If so FIGHT //If not RUN after determining best movementAction float currentBestScore = MINIMAL_SCORE; Debug.Log(movementActions.Count + " actions available"); foreach (MovementAction action in movementActions) { action.Initialize(transform, exits[0].transform.position); if (action.CanExecute()) { float score = action.moveDistance; if (score > currentBestScore) { currentBestScore = score; nextAction = action; } } } if (nextAction != null) { Debug.Log("Picked Action"); timeUnitsUsedForActions = timeUnitsPerTurn; nextAction.PreComputation(); _State = AITurnStep.TakingAction; } else { //Might be a better way to look at this, but if we couldn't find a valid move, pass the turn. This should very rarely occur. FinishedTurn = true; } } } else { FinishedTurn = true; } yield return new WaitForEndOfFrame(); }
public void RemoveAction(AIAction action) { if (Actions.Contains (action)) Actions.Remove (action); }
public bool IsType(AIAction.UsageType type) { return (this.type & type) == type; }
public void Attack(AIObject attack_aiobj) { this.Status = AIMovementStatus.Run; _target = attack_aiobj; _holdFire = false; Follow(attack_aiobj); Shoot(attack_aiobj); _actualAction = AIAction.Attack; OccupyBy(AIAction.Attack); }
public AICombatAction(NPC owner, AIAction combatAction) : base(owner) { m_Strategy = combatAction; }
private void OccupyBy(AIAction action) { _isOccupied = true; _actualAction = action; }
bool IsSetForUsage(Type t, AIAction.UsageType usage) { object[] attributes = t.GetCustomAttributes(typeof(ActionUsageAttribute), false); if (attributes.Length == 0) { return false; } return (attributes[0] as ActionUsageAttribute).IsType(usage); }
public virtual void SetAction(AIAction act) { action = act; }
public void ClearActions(AIAction action) { if(action != null) { Actions.Clear(); AddAction(action); } }
public AIRoamAction(Unit owner, AIAction roamAction) : base(owner) { Strategy = roamAction; }
public AIRoamAction(Unit owner, AIAction roamAction) : base(owner) { Strategy = roamAction; MinimumRoamSpellCastDelay = DefaultRoamSpellCastDelay; }