Example #1
0
    public void OnMouseEnter()
    {
        Unit       unit       = Unit.current;
        UnitAction unitAction = unit.Actions()[actionIndex].GetComponent <UnitAction>();

        StanceInformation.Show(unitAction.Name(), unitAction.MpCost().ToString(), unitAction.actionType().ToString() + " -- " + unitAction.Description());
    }
Example #2
0
    public void Ready(SpawnPointScript spawnPoint, PlayerScript player, Unit unit)
    {
        _targetingData    = new UnitTarget();
        _hoveredState     = HoveredState.NotHovered;
        _unitAction       = UnitAction.Idle;
        _unit             = unit;
        _playerScript     = player;
        _spawnPointScript = spawnPoint;

        transform.localPosition = Vector3.zero;
        _unitSprite.flipX       = !_playerScript.IsMe;
        _spawnPointScript.SetOccupied();

        _selectorArrows = new GameObject[_arrowInstanceCount];

        for (int i = 0; i < _arrowInstanceCount; i++)
        {
            _selectorArrows[i] = Instantiate(_selectorArrow, transform);
            _selectorArrows[i].GetComponentInChildren <SpriteRenderer>().enabled = false;
            if (i != _arrowInstanceCount - 1)
            {
                _selectorArrows[i].transform.localScale *= 0.7f;
            }
        }

        _sleepEffect.SetActive(true);
        UpdateTexts();
        ReadyEvents();
    }
Example #3
0
    public void Act(UnitAction action)
    {
        switch (action.ActionType)
        {
        case Constants.ActionType.MOVE:

            // If we successfully update our position on the grid, move to that tile
            if (GameComponents.GridController.MoveUnit(this, action.Target))
            {
                Movement.StartMoving(action.Target.GetPositionWithOffset());
                Debug.Log($"{Id} moved");
            }

            break;

        case Constants.ActionType.ATTACK:

            Unit target = GameComponents.UnitRegistry.GetUnit(action.Target.StoredId);
            if (target)
            {
                Attack(target);
                Debug.Log($"{Id} attacked");
            }

            break;

        default:
            break;
        }
    }
Example #4
0
        public bool UpdateAction(ref UnitAction action, bool current = false)
        {
            Vector3Int workCell;
            bool       success = false;

            if (World.instance.ClosestAvailableCell(m_controller.unit, action.target, m_action.interactionCell, out workCell))
            {
                /*if (current && m_action.interactionCell != workCell)
                 * {
                 *  World.instance.ReleaseCell(m_controller.unit, m_action.interactionCell);
                 *  World.instance.ReserveCell(m_controller.unit, workCell);
                 * }*/
                action.targetCell          = action.target.cell;
                action.targetPosition      = World.instance.CellToWorld(action.targetCell);
                action.interactionCell     = workCell;
                action.interactionPosition = World.instance.CellToWorld(workCell);
                action.distance            = World.Distance(m_controller.unit, action.target);
                //action.status = UnitAction.ActionStatus.Planned;
                success = true;
            }
            else
            {
                action.status = UnitAction.ActionStatus.Cancelled;
            }
            return(success);
        }
Example #5
0
    /**
     * 전투로 인한 데미지 출력 시 MakeMessage 함수
     * 인자로 UnitAction:Attack을 받지 않으면 에러 메세지 띄움. 추후 확장 가능성도 있음.
     */
    public void MakeAttackMessage(Unit subject, UnitAction action, Unit target, int damage)
    {
        //switch case by Subject and Action.
        string s = "Error: MakeAttackMessage가 call되었으나 string이 제대로 생성되지 않았습니다.";

        if (action != UnitAction.Attack) // 잘못된 호출
        {
            Debug.Log("정의되지 않은 방법으로 MakeAttackMessage를 호출하였습니다.");
            return;
        }

        if (subject.ToString() == "Player") //플레이어 공격
        {
            s  = "";
            s += SubjName(subject);
            s += " ";            // "당신은 "
            s += ObjName(target);
            s += " 공격하여 ";       // "당신은 대상을 "
            s += damage;
            s += "의 피해를 주었습니다."; // "당신은 대상을 공격하여 1의 피해를 주었습니다."
        }

        else // 플레이어 방어
        {
            s  = "";
            s += SubjName(subject);
            s += " ";            // "적이 "
            s += ObjName(target);
            s += " 공격하여 ";       // "적이 당신을 공격하여 "
            s += damage;
            s += "의 피해를 주었습니다."; // "적이 당신을 공격하여 1의 피해를 주었습니다."
        }
        logger.AddLog(s);
    }
Example #6
0
 void enterAttack(UnitAction fromState, Unit u)
 {
     unit.anim.SetBool("Walk", false);
     //we're in range!
     unit.SwitchState(fromState, UnitAction.Attacking);
     target = u;
 }
Example #7
0
    private void lmousedown(float x, float y)
    {
        foreach (GameObject obj in list)
        {
            if (obj == null)
            {
                continue;
            }


            Unit info = obj.GetComponent <Unit>();
            if (info == null)
            {
                continue;
            }

            switch (info.unittype)
            {
            case "unit":
            case "Unit":
            {
                UnitAction action = obj.GetComponent <UnitAction>();
                if (action == null)
                {
                    continue;
                }

                int[]   i = { 0 };
                float[] f = { x, y };
                action.add("useweapon", 1, i, f);
            }
            break;
            }
        }
    }
Example #8
0
 public void resolveAction(UnitAction action)
 {
     if (action is DamagingAction)
     {
         Debug.Log("Applying damage");
         action.target.takeDamage(((DamagingAction)action).damage);
         if (action.target.isEnemy)
         {
             enemyNetDamageTaken += ((DamagingAction)action).damage;
         }
         else
         {
             playerNetDamageTaken += ((DamagingAction)action).damage;
         }
     }
     else if (action is HealingAction)
     {
         Debug.Log("Applying healing");
         action.target.takeHealing(((HealingAction)action).healing);
         if (action.target.isEnemy)
         {
             enemyNetDamageTaken -= ((HealingAction)action).healing;
         }
         else
         {
             playerNetDamageTaken -= ((HealingAction)action).healing;
         }
     }
     else
     {
     }
 }
Example #9
0
    public void EndTargetting(bool cancel = false)
    {
        Cursor.visible = true;

        _unitAction = UnitAction.Idle;

        for (int i = 0; i < _arrowInstanceCount; i++)
        {
            _selectorArrows[i].GetComponentInChildren <SpriteRenderer>().enabled = false;
        }

        if (!cancel && _targetingData.currentTarget != null && _targetingData.validator(_targetingData.currentTarget.Unit))
        {
            _targetingData.onComplete(_targetingData.currentTarget);
        }

        if (_targetingData.currentTarget != null)
        {
            _targetingData.currentTarget.HideTargetIndicator(_targetingData.onValidTargetMouseExit);
            SetDeathMarkerActive(false);
        }

        _targetingData.onComplete      = (a) => { };
        _targetingData.onInvalidTarget = (a) => { };
        _targetingData.currentTarget   = null;
    }
Example #10
0
    /// <summary>
    /// Tells the unit to follow the specified path, then attack the unit at the end of the path.
    /// </summary>
    /// <param name="path">The path to be followed by this unit</param>
    /// <param name="unit">The unit to be attacked at the end of the path</param>
    public void TravelPathAndAttack(List <BattleHex> path, BattleUnit unit)
    {
        HexDirection finalFacingDirection = TravelPath(path);
        BattleHex    unitTile;

        //this._actions.la
        if (path.Count > 1)
        {
            unitTile = path[path.Count - 1];
        }
        else
        {
            unitTile = _currentHex;
        }

        HexDirection requiredDirection = HexHelpers.GetTargetDirection(unitTile, unit.CurrentHexTile);

        if (requiredDirection != finalFacingDirection)
        {
            this._actions.Enqueue(new UnitRotation(this, HexHelpers.GetTargetDegrees(HexHelpers.ReverseDirection(finalFacingDirection)), HexHelpers.GetTargetDegrees(requiredDirection)));
        }

        this._actions.Enqueue(new UnitAttack(this, unit));

        if (this._currentAction == null)
        {
            this._currentAction = this._actions.Dequeue();
        }
    }
Example #11
0
    private void Start()
    {
        unitAction = UnitAction.Idle;
        unitState  = UnitState.Inactive;

        highlight.SetActive(false);
    }
Example #12
0
    private void rmousedown(float x, float y)
    {
        foreach (GameObject obj in list)
        {
            if (obj == null)
            {
                continue;
            }

            Unit info = obj.GetComponent <Unit>();
            if (info == null)
            {
                continue;
            }
            switch (info.unittype)
            {
            case "unit":
            case "Unit":
            {
                UnitAction action = obj.GetComponent <UnitAction>();
                if (action == null)
                {
                    continue;
                }

                action.add("movedest", 1, null, new float[] { x, y, 2 });
            }
            break;
            }
        }
    }
        public async UniTask <UnitActionPlanResult> PlanBatchedAction(IUnit[] units, UnitAction action)
        {
            // Action Plan Event
            _logger.Log(LoggedFeature.Units, $"Action: {action} planned on {units.Length} units.");
            _batchedActionHandlers.Where(x => x.ActionType == action).ToList()
            .ForEach(x => x.HandleActionPlanned(units));

            // Subscribe to confirm / cancel. They will fire before Tick if possible.
            UnitActionPlanResult result = null;
            var confirmObservables      =
                _batchedActionHandlers.Where(x => x.ActionType == action).Select(x => x.ConfirmActionObservable);

            confirmObservables.Merge().Subscribe(coords => {
                HandleActionConfirmed(units, action);
                result = UnitActionPlanResult.MakeConfirmed();
            }).AddTo(_disposables);

            var cancelObservables =
                _batchedActionHandlers.Where(x => x.ActionType == action).Select(x => x.CancelActionObservable);

            cancelObservables.Merge().Subscribe(coords => {
                HandleActionCanceled(units, action);
                result = UnitActionPlanResult.MakeCanceled();
            }).AddTo(_disposables);

            // Wait until result is received
            await UniTask.WaitUntil(() => result != null);

            return(result);
        }
        public async UniTask <UnitActionPlanResult> PlanAction(IUnit unit, UnitAction action)
        {
            // Action Plan Event
            HandleActionPlanned(unit, action);

            // Subscribe to confirm / cancel. They will fire before Tick if possible.
            UnitActionPlanResult result = null;
            var confirmObservables      =
                _actionHandlers.Where(x => x.ActionType == action).Select(x => x.ConfirmActionObservable);

            confirmObservables.Merge().Subscribe(coords => {
                HandleActionConfirmed(unit, action);
                result = UnitActionPlanResult.MakeConfirmed();
            }).AddTo(_disposables);

            var cancelObservables =
                _actionHandlers.Where(x => x.ActionType == action).Select(x => x.CancelActionObservable);

            cancelObservables.Merge().Subscribe(coords => {
                HandleActionCanceled(unit, action);
                result = UnitActionPlanResult.MakeCanceled();
            }).AddTo(_disposables);

            // Wait until result is received
            await UniTask.WaitUntil(() => result != null);

            return(result);
        }
Example #15
0
    IEnumerator walkTo(Vector3 pos)
    {
        anim.SetBool("Walk", true);
        Vector3 startPos = t.position;

        SetFacing(pos.x > startPos.x);
        float length = Vector3.Distance(t.position, pos);
        float start  = Time.time;
        float time   = 0.0f;

        if (pos == startPos)
        {
            // Debug.Log("[DamageEvent] already there");
            yield break;
        }
        actionState |= UnitAction.Walking;
        while (time < 1.0f)
        {
            float dist = (Time.time - start) * speed;
            time = dist / length;
            transform.position = Vector3.Lerp(startPos, pos, time);
            yield return(null);
        }
        transform.position = pos;
        anim.SetBool("Walk", false);
        actionState &= ~UnitAction.Walking;
    }
        private bool CanExecute(UnitAction action, World.Maps.HexPoint focus)
        {
            switch (action)
            {
                case UnitAction.Found:
                    if (Game.GetCityAt(focus) != null)
                        return false;

                    foreach( HexPoint pt in focus.Neighbors )
                        if (Game.GetCityAt(pt) != null)
                            return false;

                    return true;
                case UnitAction.BuildRoad:

                    if (road == null)
                        road = Provider.GetImprovement("Road");

                    return !Game.Map[focus].Improvements.Contains(road);
                case UnitAction.BuildFarm:

                    if (road == null)
                        road = Provider.GetImprovement("Farm");

                    return !Game.Map[focus].Improvements.Contains(farm);
            }

            return false;
        }
Example #17
0
        //



        //Aqui vc coloca sua lógica
        public override void Step(Squad squad)
        {
            if (squad.TargetInfo == null || !squad.TargetInfo.IsValid)
            {
                foreach (var squaddie in squad.Units)
                {
                    squaddie.CurrentAction = UnitAction.IdleAction();
                }
                return;
            }

            if (squad.TargetInfo.Target == null)
            {
                foreach (var squaddie in squad.Units)
                {
                    squaddie.CurrentAction = UnitAction.MoveAction(squad.TargetInfo.Position);
                }
            }
            else
            {
                foreach (var squaddie in squad.Units)
                {
                    squaddie.CurrentAction = UnitAction.AttackAction(squad.TargetInfo.Target, squad.TargetInfo.Target.position);
                }
            }
        }
Example #18
0
 public IEnumerator Execute()
 {
     while (true)
     {
         UnitAction.activeSource = GetComponent <UnitController>();
         UpdatePlan();
         UnitAction action = plan.Pop();
         Debug.Log(action.GetType());
         if (action != null)
         {
             if (typeof(ToggleAction).IsAssignableFrom(action.GetType()))
             {
                 ((ToggleAction)action).RunToggleAction();
                 yield return(null);
             }
             else
             {
                 UnitAction.activeSource = GetComponent <UnitController>();
                 yield return(StartCoroutine(action.RunAction()));
             }
         }
         else
         {
             yield return(null);
         }
     }
 }
Example #19
0
    public void AddAction(UnitAction action)
    {
        if (remainingActions <= 0)
        {
            return;
        }
        remainingActions--;

        // SET UI
        switch (action.GetActionType())
        {
        case UnitAction.ActionType.FIX:
            FindObjectOfType <GameUI>()?.AddHeroHUDRepair(unitNumber);
            SoundSystem.Instance.PlayHeroConfirmSound(unitNumber);
            break;

        case UnitAction.ActionType.MOVE:
            FindObjectOfType <GameUI>()?.AddHeroHUDMove(unitNumber);
            SoundSystem.Instance.PlayHeroMoveSound(unitNumber);
            TileManager.Instance.OnUnitMovedToTile(action.GetActionTarget(), unitNumber);
            break;
        }

        actions.Add(action);
    }
Example #20
0
    public virtual void DealDamage(Damage dmg)
    {
        if (state == UnitState.Dead || state == UnitState.Zombie)
        {
            return;
        }
        // Debug.Log("[Unit] " + this.gameObject + " taking " + dmg.amount + " from " + dmg.source, gameObject);

        hp -= dmg.amount;
        hp  = Math.Max(hp, 0);
        OnDamageTaken.Invoke(dmg);
        if (hp == 0)
        {
            // Debug.Log("[Unit] DEAD!");
            state = UnitState.Dead;
            m.units.Remove(this);
            actionState = (UnitAction)0;
            fx.Spawn(Keys.Death);
            Destroy(gameObject);
        }
        else
        {
            displayDamageFX(dmg);
        }
    }
Example #21
0
    /**
     * 아이템과 관련된 메세지를 출력하는 함수
     * 상황에 따라 3가지 오버로딩
     */

    // 보통 아이템 관련 메세지 출력하는 오버로딩 함수
    public void MakeItemMessage(UnitAction action, ItemManager.Label item)
    {
        string s = "";

        if (action == UnitAction.EatCapsule)
        {
            Debug.Log("정의되지 않은 방법으로 MakeItemMessage를 호출하였습니다." +
                      " EatCapsule로 call시 물 섭취 여부를 true/false로 입력하세요.");
            return;
        }

        if (action == UnitAction.PickItem || action == UnitAction.TakeCapsule)  //아이템 습득
        {
            if (itemmanager.GetItemIdentificationInfo(item) == false)
            {
                s = "미식별 알약을 얻었습니다.";
            }
            else
            {
                s = ObjName(item) + " 얻었습니다.";
            }
        }

        else if (action == UnitAction.UseItem || action == UnitAction.InjectItem) // 아이템(소모품) 사용
        {
            s = ObjName(item) + " 사용했습니다.";
        }
        else
        {
            Debug.Log("정의되지 않은 방법으로 MakeItemMessage를 호출하였습니다.");
            return;
        }

        logger.AddLog(s);
    }
Example #22
0
        public void Run(UnitAction action)
        {
            if (action.target != null && action.target == m_action.target)
            {
                // continue action;
                m_action.status = UnitAction.ActionStatus.Planned;
                return;
            }
            else
            {
                // reserve a new cell for the interaction

                /*if (m_action.interactionCell != action.interactionCell)
                 * {
                 *  World.instance.ReleaseCell(m_controller.unit, m_action.interactionCell);
                 *  World.instance.ReserveCell(m_controller.unit, action.interactionCell);
                 * }*/
                m_action = action;
                m_navigation.isStopped = false;
                m_action.status        = UnitAction.ActionStatus.Planned;

                m_time = 0;
                if (action.target)
                {
                    building = action.target as BuildingBase;
                    unit     = action.target as Unit;
                    resource = action.target as ResourceSource;
                }
            }
        }
Example #23
0
    //If We're not moving we assume we're attacking
    public void ShowActionTiles(UnitAction unitAction)
    {
        m_unitView = unitAction.unit;

        HideActionTiles(m_unitView);

        Vector3 unitPosition = unitAction.unit.transform.position;

        m_activatedTiles.Clear();

        int unitX = Mathf.RoundToInt(unitPosition.x);
        int unitY = Mathf.RoundToInt(unitPosition.z);

        int actionRange = unitAction.isMoving ? m_unitView.UnitData.movementRange : m_unitView.UnitData.weapon.weaponRange;

        for (int x = -actionRange; x <= actionRange; x++)
        {
            for (int y = -actionRange; y <= actionRange; y++)
            {
                if (x == 0 && y == 0)
                {
                    continue;
                }

                if (Mathf.Abs(x) + Mathf.Abs(y) > actionRange)
                {
                    continue;
                }

                int xPos = unitX + x;
                int yPos = unitY + y;

                Vector3 worldPoint = new Vector3(xPos, 0, yPos);

                if (IsPositionWithinBoard(xPos, yPos))
                {
                    bool actionable = !(Physics.CheckSphere(worldPoint, 0.4f, unitAction.collisionMask));

                    if (unitAction.isMoving)
                    {
                        if (actionable)
                        {
                            PathRequestManager.RequestPath(unitPosition, new Vector3(xPos, 0, yPos), OnPathFound);
                        }
                    }
                    else if (!unitAction.isMoving)
                    {
                        actionable = !actionable; //Reverse collision bool as we're looking for tiles with animals

                        if (actionable)
                        {
                            m_tileGrid[xPos, yPos].SetActive(true);
                            m_activatedTiles.Add(m_tileGrid[xPos, yPos]);
                        }
                    }
                }
            }
        }
    }
Example #24
0
    public void Set(UnitAction action)
    {
        StopCurrent();

        queue.Clear();

        Add(action);
    }
Example #25
0
 // Add an action to the list and start it if is the only action
 public void AddAction(UnitAction action)
 {
     actions.Add(action);
     if (actions.Count == 1)
     {
         action.StartAction();
     }
 }
        private void HandleActionCanceled(IUnit unit, UnitAction action)
        {
            _logger.Log(LoggedFeature.Units, $"Action: {action} canceled on unit: {unit}");
            _actionHandlers.Where(x => x.ActionType == action).ToList().ForEach(x => x.HandleActionCanceled(unit));

            _disposables.ForEach(x => x.Dispose());
            _disposables.Clear();
        }
Example #27
0
    private GameObject buildSpriteOption(Sprite sprite, UnitAction choice)
    {
        GameObject go = Instantiate(MenuSpritePrefab) as GameObject;

        go.GetComponent <SpriteRenderer>().sprite = sprite;
        go.GetComponent <MenuOption>().Setup(this, choice);
        return(go);
    }
Example #28
0
    public BuildAction(GameObject owner, GameObject gameObject, Vector3 position, UnitAction postBuildAction) : base(owner)
    {
        GameObject = gameObject;

        Position = position;

        PostBuildAction = postBuildAction;
    }
 public UnitActionTransition(UnitAI ai, UnitAction from, UnitAction to, UnitFunction precondition, double propability = 1.0)
 {
     _ai = ai;
     _from = from;
     _to = to;
     _precondition = precondition;
     _propability = propability;
 }
Example #30
0
 public void AttackInit()
 {
     if (!m_hasPerformedOperation)
     {
         UnitAction unitAction = new UnitAction(m_unitView, false, m_unitView.UnitData.weapon.weaponTargetMask);
         GameManager.Instance.ActionTiles.ShowActionTiles(unitAction);
     }
 }
 public void IndicateUnitAction(UnitCell unit, UnitAction unitAction)
 {
     if (!IsCurrentPlayer)
     {
         return;
     }
     actions.SetUnitAction(unit, unitAction);
 }
Example #32
0
 private void TileRightClickEvent(Tile tile)
 {
     if (IsActivePlayerUnit(selectedUnit) && IsValidTarget(selectedUnit, tile))
     {
         UnitAction action = new UnitAction(tile, Constants.ActionType.ATTACK);
         selectedUnit.Act(action);
         GameComponents.TurnHandler.EndTurn();
     }
 }
Example #33
0
    // run away to the node that's farthest away from all enemies.
    private KeyValuePair<Result, UnitAction> RunAway()
    {
        MinPriorityQueue<UnitAction> farthestActions = new MinPriorityQueue<UnitAction>();
        foreach (Node n in pathManager.getAccessibleNodes(subjectRef))
        {
            int curCount = 0;
            foreach (Unit en in subjectsEnemiesRef)
                curCount += Node.range(n, en.getNode());

            // min priority queue: negate results.
            UnitAction runAwayTo = new UnitAction(subjectRef, null, n);
            farthestActions.Enqueue(runAwayTo, -curCount);
        }

        if (farthestActions.Count == 0)
            return new KeyValuePair<Result, UnitAction>(Result.NothingFound, UnitAction.DoNothing(subjectRef));
        else
            return new KeyValuePair<Result, UnitAction>(Result.Success, farthestActions.Dequeue());
    }
Example #34
0
		protected virtual void EveryPeriod () {
			if (action != null) {
				if (!action.isactive) {
					action = null;
				} else if (action.IsEndAction()) {
					action = null;
				}
			}
		}
Example #35
0
		public virtual bool StartAction (UnitAction _action)
		{
			if (action != null) {
				if (!action.isactive) {
					action = _action;
					action.StartAction();
					return true;
				} else if (_action.priory > action.priory) {
					if (InterruptAction()) {
						action = _action;
						action.StartAction();
						return true;
					}
				}
			} else {
				action = _action;
				action.StartAction();
				return true;
			}
			return false;
		}
    public void Update()
    {
        if (delayTime <= 0 && !moving)
        {
            if (aiTurn && toActAI.Count == 0)
            {
                selectionState = State.EnemyTurn;

                foreach (Unit unit in aiUnits)
                    toActAI.Enqueue(unit);

                if (toActAI.Count == 0)
                {
                    moving = true;
                    UIManager.getUIManager().clearDisplay();
                    pathFinder.clearRangeDisplay();
                    return;
                }
            }

            if (aiTurn)
            {
                currentAIUnit = toActAI.Dequeue();
                UIManager.getUIManager().setDisplayedUnit(currentAIUnit);
                pathFinder.displayRangeOfUnit(currentAIUnit, currentAIUnit.getNode().getPos());

                currentAction = ai.RunAI(currentAIUnit, playerUnits);
                UIManager.getUIManager().setDisplayedUnit(currentAIUnit);

                lockMovement();
                currentAction.Move(finishedMoveCallbackAI);
            }

            if (!aiTurn && toActAI.Count == 0)
            {
                selectionState = State.EnemyTurn;

                foreach (Unit unit in playerUnits)
                    toActAI.Enqueue(unit);

                if (toActAI.Count == 0)
                {
                    moving = true;
                    UIManager.getUIManager().clearDisplay();
                    pathFinder.clearRangeDisplay();
                    return;
                }
            }

            if (!aiTurn)
            {
                currentAIUnit = toActAI.Dequeue();
                UIManager.getUIManager().setDisplayedUnit(currentAIUnit);
                pathFinder.displayRangeOfUnit(currentAIUnit, currentAIUnit.getNode().getPos());

                currentAction = ai.RunAI(currentAIUnit, aiUnits);
                UIManager.getUIManager().setDisplayedUnit(currentAIUnit);

                lockMovement();
                currentAction.Move(finishedMoveCallbackAI);
            }
            else
            {
                selectionState = State.OurTurnNoSelection;

                if (Input.GetMouseButtonDown((int)MouseButton.left))
                {
                    Vector2 position = getMousePos();

                    if (positionInGraph(position))
                    {
                        Node clickedNode = pathFinder.closestMostValidNode(position);

                        if (unitSelected)
                        {
                            currentlySelectedUnit.deselect();
                            unitSelected = false;
                            selectionState = State.OurTurnNoSelection;
                        }

                        if (clickedNode.Occupied)
                        {
                            currentlySelectedUnit = clickedNode.Occupier;
                            currentlySelectedUnit.select();
                            unitSelected = true;
                            pathFinder.displayRangeOfUnit(currentlySelectedUnit, position);
                            if (currentlySelectedUnit.isEnemy())
                                selectionState = State.UnitActed;
                            else
                                selectionState = State.UnitFresh;
                        }
                        else
                        {
                            pathFinder.clearRangeDisplay();
                            selectionState = State.OurTurnNoSelection;
                        }
                    }
                }
                if (Input.GetMouseButtonDown((int)MouseButton.right))
                {
                    pathFinder.clearRangeDisplay();
                    selectionState = State.OurTurnNoSelection;
                }
            }

        }
        else
        {
            // disables all buttons while locked
            selectionState = State.EnemyTurn;

            if (delayTime > 0)
                delayTime--;
        }

        UIManager.getUIManager().ChangeButtonState(selectionState);
    }
Example #37
0
 public void ProcessUnitAction(Unit unit, UnitAction action)
 {
     if (action is MoveAction) Move(unit, (MoveAction)action);
     else if (action is ScanAction) Scan(unit, (ScanAction)action);
     else if (action is ShootAction) Shoot(unit, (ShootAction)action);
 }
Example #38
0
		public virtual bool InterruptAction () {
			if (action != null) {
				if (!action.isactive) {
					action = null;
					return true;
				}
				if (!action.uninterrupt) {
					action.StopAction();
					action = null;
					return true;
				}
			} else {
				return true;
			}
			return false;
		}
Example #39
0
        public void Execute(UnitAction _action)
        {
            switch (_action)
            {
                case UnitAction.Idle:
                    break;
                case UnitAction.Found:
                    Found();
                    break;
                case UnitAction.Move:
                    SelectTarget();
                    break;
                case UnitAction.BuildRoad:
                    if (road == null)
                        road = Provider.GetImprovement("Road");

                    Build(road);
                    break;
                case UnitAction.BuildFarm:
                    if (farm == null)
                        farm = Provider.GetImprovement("Farm");

                    Build(farm);
                    break;
                default:
                    throw new Exception("No handle for " + _action); 
            }

            UpdateUnitAction();
        }
Example #40
0
    /// <summary>
    /// Runs MinMax on a unit.
    /// </summary>
    /// <returns>A result-UnitAction pair.</returns>
    private KeyValuePair<Result, UnitAction> MinMax()
    {
        List<Node.NodePointer> targets = pathManager.getCurrentTargets(subjectRef);
        MinPriorityQueue<UnitAction> bestMoves = new MinPriorityQueue<UnitAction>();
        int realclay = subjectRef.getClay();

        // The "max-y" part: maximize (damage/counter-damage)
        foreach (Node.NodePointer candidateAttackTarget in targets)
        {
            int moveCost = candidateAttackTarget.getDist();

            Unit curEnemy = candidateAttackTarget.getTarget().Occupier;

            AttackRound util = new AttackRound(subjectRef, moveCost, curEnemy);


            UnitAction roundMove = new UnitAction(subjectRef, curEnemy, candidateAttackTarget.getStart());

            int totDmg = 0;

            // Will very likely die, enqueue this move as bad, and don't move to next step.
            //TODO: utility = 0
            if (util.attackerDies() || util.getUtility() == 0)
            {
                bestMoves.Enqueue(roundMove, double.PositiveInfinity);
                util.resetBack();
                subjectRef.setClay(realclay);
                continue;
            }

            totDmg += util.getExpectedDamage();

            // Loop through all things that could attack this position, and continue testing attacks.
            // The "min-y" part. Enemy tries to maximize their (damage/counter-damage)
            // Technically could just do damage maximization, since counter-damage is fixed.
            foreach (Unit enemy in subjectsEnemiesRef)
            {
                if (enemy.getClay() > 0 && pathManager.canAttack(enemy, candidateAttackTarget.getStart()))
                {
                    //gets the closest move. This will be the move that maxes damage.
                    int enemyMoveCost = pathManager.maxDamageMoveCost(enemy, candidateAttackTarget.getStart());
                    AttackRound subRound = new AttackRound(enemy, enemyMoveCost, subjectRef);
                    int roundClay = subjectRef.getClay();

                    subRound.resetBack();
                    subjectRef.setClay(roundClay);

                    // If we die, break early, as usual.
                    if (util.defenderDies())
                    {
                        break;
                    }

                    totDmg += subRound.getExpectedCounterDamage();
                }
            }

            // Died. Enqueue with +inf again.
            if (subjectRef.getClay() == 0)
                bestMoves.Enqueue(roundMove, double.PositiveInfinity);
            // enqueue move! min pri queue, so invert answer.
            else
                bestMoves.Enqueue(roundMove, -((double)totDmg / subjectRef.getClay()));
            
            util.resetBack();
            subjectRef.setClay(realclay);
        }

        subjectRef.setClay(realclay);

        // no local targets...
        if (bestMoves.Count == 0)
            return new KeyValuePair<Result, UnitAction>(Result.NothingFound, null);
        // all moves die. only move is not to play.
        else if (bestMoves.currentInversePriority(bestMoves.Peek()) == double.PositiveInfinity)
            return new KeyValuePair<Result, UnitAction>(Result.WillDie, bestMoves.Peek());
        // found good target.
        return new KeyValuePair<Result, UnitAction>(Result.Success, bestMoves.Peek());
    }
Example #41
0
 public Unit(UnitType t, Sector s, Player p, DateTime d)
 {
     this.type = t;
     this.sector = s;
     this.owner = p;
     this.date = d;
     this.action = UnitAction.None;
     this.hitpoints = Info.Hitpoints;
     this.number = 1;
     Sector.Units.Add(this);
     if (Owner != null)
         Owner.Units.Add(this);
 }
Example #42
0
    private KeyValuePair<Result, UnitAction> FindUnit()
    {
        Predicate<Node> findEn = (Node q) =>
        {
            bool isOccupied = q.Occupied;
            if (!isOccupied)
                return false;
            if (q.Occupier.isEnemy() != subjectRef.isEnemy())
                return true;
            return false;
        };

        Node closestEnemyNode = pathManager.getClosestNode(subjectRef, findEn);
        if (closestEnemyNode == null)
            return new KeyValuePair<Result, UnitAction>(Result.NothingFound, null);

        Queue<Node> path = new Queue<Node>();
        pathFinderRef.AStar(path, subjectRef.getNode(), closestEnemyNode, closestEnemyNode);
        
        Node goTo = subjectRef.getNode();

        // go to farthest path.
        while (path.Count > 0 && pathManager.canWalkTo(subjectRef, path.Peek()))
            goTo = path.Dequeue();

        UnitAction moveCloserToClosestEnemy = new UnitAction(subjectRef, null, goTo);

        return new KeyValuePair<Result, UnitAction>(Result.Success, moveCloserToClosestEnemy);
    }