Ejemplo n.º 1
0
        public void Next()
        {
            RoundMark++;

            FlowWordQueue.Next();
            EffectQueue.Next();
            MissileQueue.Next();

            if (RoundMark % 4 == 0) //200ms
            {
                float pastRound = (float)200 / GameConstants.RoundTime;

                MonsterQueue.NextAction(pastRound); //1回合

                PlayerManager.Update(false, pastRound, StatisticData.Round);

                Round += pastRound;
                if (Round >= 1)
                {
                    Round = 0;
                    PlayerManager.CheckRoundCard(); //1回合
                }
            }
            StatisticData.Round = RoundMark * 50 / GameConstants.RoundTime + 1;//50ms
            if (RoundMark % 10 == 0)
            {
                AIStrategy.AIProc(PlayerManager.RightPlayer);
            }
        }
Ejemplo n.º 2
0
    void Start()
    {
        _isServing            = false;
        _AIStrategy           = new AIStrategy(otherPlayer);
        _characterController  = GetComponent <CharacterController>();
        _playerAnimation      = new PlayerAnimation(GetComponent <Animator>());
        _basePositionFromBall = new Vector3(7.705f, 0f, 0.633f);
        _newPosition          = true;
        _scoreManager         = ScoreManager.GetInstance();
        _timeToServe          = 0;
        difficulty            = difficulty > 4 ? 4 : difficulty;
        difficulty            = difficulty < 1 ? 1 : difficulty;


        if (transform.position.x < 0)
        {
            _id = 1;
        }
        else
        {
            _id = 2;
        }
        Setinitialposition();
        SetDifficulty(ScoreManager.GetInstance().GetGameDifficulty());
        SetSpeed();
        SetTimeToBounce();
    }
Ejemplo n.º 3
0
 public AIPlayer(AIStrategy strategy, long id, GameManager gameManager)
 {
     this.id = id;
     this.strategy = strategy;
     this.gameManager = gameManager;
     this.gameState = gameManager.getGameState();
 }
Ejemplo n.º 4
0
    public Governor(string leaderName, City city, AIStrategy strategy)
    {
        this.allegiance = Allegiance.INDEPENDENT;
        this.leaderName = leaderName;
        this.strategy   = strategy;
        this.city       = city;
        this.gold       = 0;

        this.brain = new GovernorBrain(this);
    }
Ejemplo n.º 5
0
    public override IPlayedCard Play(int memberId, BattleState battleState, AIStrategy strategy)
    {
        var me            = battleState.Members[memberId];
        var playableCards = battleState.GetPlayableCards(memberId);
        var allies        = battleState.GetConsciousAllies(me);
        var enemies       = battleState.GetConsciousEnemies(me);

        var maybeCard = new Maybe <CardTypeData>();
        IEnumerable <CardTypeData> cardOptions = playableCards;

        // Go Ham if Alone
        if (allies.Count() == 1 && cardOptions.Any(c => c.Tags.Contains(CardTag.Attack)))
        {
            maybeCard = new Maybe <CardTypeData>(cardOptions.Where(c => c.Tags.Contains(CardTag.Attack)).MostExpensive());
        }
        // Play Ultimate
        else if (cardOptions.Any(c => c.Tags.Contains(CardTag.Ultimate)))
        {
            maybeCard = new Maybe <CardTypeData>(cardOptions.Where(c => c.Tags.Contains(CardTag.Ultimate)).MostExpensive());
        }

        // Don't Hit Enemy Shields if the play isn't very effective
        if (enemies.Sum(e => e.CurrentShield()) < 15)
        {
            cardOptions = cardOptions.Where(c => !c.Tags.Contains(CardTag.Shield));
        }

        // Pick any other highest-cost card
        var card = maybeCard.IsPresent
            ? maybeCard.Value
            : cardOptions
                   .ToArray()
                   .Shuffled()
                   .OrderByDescending(c => c.Cost.Amount)
                   .First();

        var targets = card.ActionSequences.Select(action =>
        {
            var possibleTargets = battleState.GetPossibleConsciousTargets(me, action.Group, action.Scope);
            if (card.Tags.Contains(CardTag.Stun))
            {
                return(possibleTargets.MostPowerful());
            }
            if (card.Tags.Contains(CardTag.Attack))
            {
                return(strategy.AttackTargetFor(action));
            }
            return(possibleTargets.Random());
        });

        var cardInstance = card.CreateInstance(battleState.GetNextCardId(), me);

        return(new PlayedCardV2(me, targets.ToArray(), cardInstance));
    }
Ejemplo n.º 6
0
    protected virtual void StartStrategy(AIAction action)
    {
        var strategy = GetOrCreateStrategyForAction(action);

        if (currentStrategy != null && currentStrategy != strategy)
        {
            currentStrategy.StopStrategy();
        }
        CurrentStrategy = strategy;
        strategy.StartStrategy(action);
    }
Ejemplo n.º 7
0
    public override IPlayedCard Play(int memberId, BattleState battleState, AIStrategy strategy)
    {
        var me            = battleState.Members[memberId];
        var playableCards = battleState.GetPlayableCards(memberId);
        var allies        = me.TeamType == TeamType.Enemies
            ? battleState.Enemies.Where(m => m.IsConscious()).ToArray()
            : battleState.Heroes.Where(m => m.IsConscious()).ToArray();

        if (playableCards.MostExpensive().Cost.Amount > 1 && allies.Any(x => x.CurrentHp() + x.CurrentShield() > x.MaxHp() * 0.5f))
        {
            var viableAllies = allies.Where(x => x.CurrentHp() + x.CurrentShield() > x.MaxHp() * 0.5f).ToArray();
            var ultimate     = playableCards.MostExpensive().CreateInstance(battleState.GetNextCardId(), me);
            if (viableAllies.Any(x => x.BattleRole == BattleRole.Striker))
            {
                return(new PlayedCardV2(me, new Target[] { new Single(viableAllies.Where(x => x.BattleRole == BattleRole.Striker).Random()) }, ultimate));
            }
            if (viableAllies.Any(x => x.BattleRole == BattleRole.Tank))
            {
                return(new PlayedCardV2(me, new Target[] { new Single(viableAllies.Where(x => x.BattleRole == BattleRole.Tank).Random()) }, ultimate));
            }
            return(new PlayedCardV2(me, new Target[] { new Single(viableAllies.Random()) }, ultimate));
        }

        if (allies.Length == 1)
        {
            var attackCard = playableCards.Where(c => c.Is(CardTag.Attack)).Random()
                             .CreateInstance(battleState.GetNextCardId(), me);
            return(new PlayedCardV2(me, attackCard.ActionSequences.Select(strategy.AttackTargetFor).ToArray(), attackCard));
        }
        else
        {
            playableCards = playableCards.Where(x => !x.Is(CardTag.Attack)).ToArray();
        }
        if (allies.Length == 2)
        {
            playableCards = playableCards.Where(cardType => cardType.ActionSequences.Any(sequence => sequence.Group != Group.Ally || sequence.Scope != Scope.All)).ToArray();
        }
        var card = playableCards.Random();

        return(new PlayedCardV2(me, card.ActionSequences.Select(action =>
        {
            if (action.Group == Group.Ally && action.Scope == Scope.One)
            {
                var weightedList = new List <Member>();
                foreach (var ally in allies.Where(x => x != me))
                {
                    Enumerable.Range(0, Mathf.RoundToInt(Mathf.Pow(((ally.CurrentHp() + ally.CurrentShield()) / (float)ally.MaxHp()) * 10, 1.6f) * (ally.BattleRole == BattleRole.Striker ? 3 : 1))).ForEach(x => weightedList.Add(ally));
                }
                return new Single(weightedList.Random());
            }
            return strategy.GetRandomApplicableTarget(me, battleState.Members.Values.Where(x => x.IsConscious()).ToArray(), action);
        }).ToArray(), card.CreateInstance(battleState.GetNextCardId(), me)));
    }
Ejemplo n.º 8
0
    void Start()
    {
        if (HumanPlayer == false)
        {
            Debug.Log("A non-human just started playing!!!");

            ai = new HouseDemonAIStrategy(this);
            //ai = new BeardedShavingDemonAIStrategy(this);
            //ai = new BeardedDemonAIStrategy(this);
        }

        //tag = "Player";
    }
Ejemplo n.º 9
0
    void Start()
    {
        if (HumanPlayer == false) {

            Debug.Log ("A non-human just started playing!!!");

            ai = new HouseDemonAIStrategy(this);
            //ai = new BeardedShavingDemonAIStrategy(this);
            //ai = new BeardedDemonAIStrategy(this);
        }

        //tag = "Player";
    }
Ejemplo n.º 10
0
 private void DiscoverCard(IMonster mon, int[] cardId, int lv, DiscoverCardActionType type)
 {
     if (isPlayerControl)
     {
         CardSelectMethodDiscover discover = new CardSelectMethodDiscover(cardId, lv, type);
         if (OnShowCardSelector != null)
         {
             OnShowCardSelector(this, discover);
         }
     }
     else
     {
         AIStrategy.Discover(this, mon, cardId, lv, type);
     }
 }
Ejemplo n.º 11
0
    public override IPlayedCard Play(int memberId, BattleState battleState, AIStrategy strategy)
    {
        var me            = battleState.Members[memberId];
        var playableCards = battleState.GetPlayableCards(memberId);

        var card    = playableCards.Random();
        var targets = card.ActionSequences.Select(action =>
        {
            var possibleTargets = battleState.GetPossibleConsciousTargets(me, action.Group, action.Scope);
            var target          = possibleTargets.Random();
            return(target);
        });

        var cardInstance = card.CreateInstance(battleState.GetNextCardId(), me);

        return(new PlayedCardV2(me, targets.ToArray(), cardInstance));
    }
Ejemplo n.º 12
0
        public bool checkHouseLocation(House house, Vector2 tryPosition, Vector2 target)
        {
            GameObject go = AIStrategy.findClosestGameObject(tryPosition, target);

            //Debug.Log ("Trying from " + tryPosition + " to hit " + target);
            if (go.tag == "House")
            {
                //Debug.Log ("Found a house with vectors in checkHouseLocation");
                House checkhouse = go.GetComponent <House> ();
                if (checkhouse.transform.position == house.transform.position && Global.boardHeight / 2 > absoluteDistance(_startPosition, house.transform.position))
                {
                    //Debug.Log ("Found house owned by AI in checkHouseLocation");
                    return(true);
                }
            }
            return(false);
        }
Ejemplo n.º 13
0
    public override IPlayedCard Play(int memberId, BattleState battleState, AIStrategy strategy)
    {
        var me            = battleState.Members[memberId];
        var playableCards = battleState.GetPlayableCards(memberId);

        IEnumerable <CardTypeData> cardOptions = playableCards;
        var maybeCard = Maybe <CardTypeData> .Missing();

        // Always play a Super Card if charged
        if (me.HasMaxPrimaryResource())
        {
            maybeCard = new Maybe <CardTypeData>(playableCards.MostExpensive());
        }

        // Don't buff self if already buffed
        if (me.HasAttackBuff())
        {
            cardOptions = cardOptions.Where(c => !c.Tags.Contains(CardTag.BuffAttack));
        }

        var card = maybeCard.IsPresent
            ? maybeCard.Value
            : cardOptions.MostExpensive();

        var targets = new List <Target>();

        card.ActionSequences.ForEach(
            action =>
        {
            if (action.Group == Group.Opponent)
            {
                targets.Add(strategy.AttackTargetFor(action));
            }
            else
            {
                var possibleTargets = battleState.GetPossibleConsciousTargets(me, action.Group, action.Scope);
                targets.Add(possibleTargets.MostVulnerable());
            }
        }
            );

        var cardInstance = card.CreateInstance(battleState.GetNextCardId(), me);

        return(new PlayedCardV2(me, targets.ToArray(), cardInstance));
    }
Ejemplo n.º 14
0
    private IEnumerator ChangeEnemyAI(AIStrategy strategy, int count)
    {
        yield return(new WaitForEndOfFrame());

        for (int i = 0; i < count; i++)
        {
            GameObject enemy = enemies.GetChild(i).gameObject;
            EnemyTank  tank  = enemy.GetComponent <EnemyTank>();
            enemy.SetActive(true);
            if (strategy is EasyAIStrategy)
            {
                tank.Strategy = new EasyAIStrategy(enemy, tank.TankMotor, enemy.transform.GetChild(0).GetComponent <Weapon>());
            }
            else
            {
                tank.Strategy = new MediumAiStrategy(enemy, tank.TankMotor, enemy.transform.GetChild(0).GetComponent <Weapon>());
            }
        }
    }
Ejemplo n.º 15
0
        private AIShip CreateAIShip(string shipId, Point2D pos, BoundaryStrategy boundaryStrat, Difficulty diff, IHandlesEntities entHandler)
        {
            AIStrategyFactory strategyFac = new AIStrategyFactory(diff.DifficultyLevel, diff.ShootCooldown);

            JObject obj = Util.Deserialize(FileRegistry[shipId]);

            //int health = obj.Value<int>("health");
            List <Color> shipColors = new List <Color> {
                Color.Crimson, Color.Yellow, Color.White, Color.Red
            };
            float   scale       = obj.Value <float>("scale");
            JArray  enginesObj  = obj.Value <JArray>("engines");
            JArray  toolsObj    = obj.Value <JArray>("tools");
            JArray  emittersObj = obj.Value <JArray>("emitters");
            JObject shapeObj    = obj.Value <JObject>("shape");

            Team    team   = Team.Computer;
            Point2D offset = SwinGame.PointAt(0, 0);

            //shape
            Shape shape  = new ShapeFactory().Create(shapeObj, scale, SwinGame.PointAt(0, 0));
            int   health = shape.Mass / 2;

            shape.TeleportTo(pos);

            //components
            List <Component> components = BuildComponents(enginesObj, toolsObj, emittersObj, entHandler, boundaryStrat, team, offset, diff.AIMod);

            //build and return ship
            AIShip result = new AIShip(shipId, FileRegistry[shipId], pos, SwinGame.PointAt(0, 0), shape, shipColors,
                                       health, SwinGame.VectorTo(0, 0), SwinGame.VectorTo(0, -1), boundaryStrat, team, components);

            //create strategy
            AIStrategy aiStrat = strategyFac.Create((IAIEntity)result, entHandler);

            result.AIStrategy = aiStrat;

            result.TeleportTo(pos);
            return(result);
        }
Ejemplo n.º 16
0
        public void Test_BuildCommandList()
        {
            var unit1    = new Mock <Unit>();
            var command1 = new AICommand()
            {
                Command = AICommand.Move, Unit = 1, Dir = AICommand.North
            };

            unit1.Setup(u => u.BuildCommand()).Returns(command1);

            var unit2    = new Mock <Unit>();
            var command2 = new AICommand()
            {
                Command = AICommand.Move, Unit = 2, Dir = AICommand.South
            };

            unit2.Setup(u => u.BuildCommand()).Returns(command2);

            var unit3 = new Mock <Unit>();

            unit3.Setup(u => u.BuildCommand()).Returns((AICommand)null);

            var unitManager = new Mock <IUnitManager>();
            var units       = new Dictionary <int, Unit>()
            {
                { 1, unit1.Object },
                { 2, unit2.Object },
                { 3, unit3.Object }
            };

            unitManager.Setup(g => g.Units).Returns(units);

            var map      = new Map();
            var commands = new AIStrategy(unitManager.Object, map).BuildCommandList();

            commands.Count.Should().Be(2);
            commands[0].Should().Be(command1);
            commands[1].Should().Be(command2);
        }
Ejemplo n.º 17
0
 public Player(Color color, int type, string name)
 {
     switch (type)
     {
         case 0:
             break;
         case 1:
             ai = new AI.Rule.RuleStrategy();
             this.name = "Rule AI";
             break;
         case 2:
             ai = new AI.State.StateStrategy();
             this.name = "State AI";
             break;
         case 3:
             this.name = name;
             break;
     }
     type = 0;
     finished = false;
     this.color = color;
 }
Ejemplo n.º 18
0
        public Game(AIStrategy aiStrategy, bool serialize)
        {
            _serialize = serialize;

            if (_serialize)
            {
                _gameHistories = _jsonPersistence.Read();
            }

            switch (aiStrategy)
            {
            case AIStrategy.Random:
                _ai = new RandomAI();
                break;

            case AIStrategy.AlwaysWins:
                _ai = new AlwaysWinsAI();
                break;

            case AIStrategy.AlwaysLoses:
                _ai = new AlwaysLosesAI();
                break;
            }
        }
Ejemplo n.º 19
0
 public void setAI(AIStrategy ai)
 {
     this.ai = ai;
 }
Ejemplo n.º 20
0
 public abstract IPlayedCard Play(int memberId, BattleState battleState, AIStrategy strategy);
Ejemplo n.º 21
0
    public override IPlayedCard Play(int memberId, BattleState battleState, AIStrategy strategy)
    {
        var me            = battleState.Members[memberId];
        var playableCards = battleState.GetPlayableCards(memberId);
        var allies        = me.TeamType == TeamType.Enemies
            ? battleState.Enemies.Where(m => m.IsConscious())
            : battleState.Heroes.Where(m => m.IsConscious());

        var maybeCard = new Maybe <CardTypeData>();
        IEnumerable <CardTypeData> cardOptions = playableCards;
        // TODO: Dealing killing blow if possible with an attack card

        var attackCards = cardOptions.Where(c => c.Is(CardTag.Attack)).ToList();

        if (allies.Count() == 1 && attackCards.Any())
        {
            maybeCard = new Maybe <CardTypeData>(attackCards.MostExpensive());
        }

        // Don't play a heal if all allies are very healthy
        if (allies.All(a => a.CurrentHp() >= a.MaxHp() * 0.9))
        {
            cardOptions = cardOptions.Where(c => !c.Is(CardTag.Healing));
        }

        // Don't play a shield if all allies are already shielded
        if (allies.All(a => a.RemainingShieldCapacity() > a.MaxShield() * 0.7))
        {
            cardOptions = cardOptions.Where(x => !x.Is(CardTag.Defense, CardTag.Shield));
        }

        var card = maybeCard.IsPresent
            ? maybeCard.Value
            : cardOptions
                   .ToArray()
                   .Shuffled()
                   .OrderByDescending(c => c.Cost.Amount)
                   .ThenBy(c => CardTypePriority[c.Tags.First()]) // Maybe needs a better way to prioritze
                   .First();

        var targets = card.ActionSequences.Select(action =>
        {
            var possibleTargets = battleState.GetPossibleConsciousTargets(me, action.Group, action.Scope);
            if (card.Is(CardTag.Healing))
            {
                return(possibleTargets.MostDamaged());
            }
            if (card.Is(CardTag.Defense, CardTag.Shield))
            {
                if (possibleTargets.Any(x => !x.HasShield()))
                {
                    return(possibleTargets.Where(x => !x.HasShield())
                           .MostVulnerable());
                }
                // Or, use shield to whomever could use the most
                return(possibleTargets.OrderByDescending(x => x.TotalRemainingShieldCapacity()).First());
            }

            if (card.Is(CardTag.Attack))
            {
                return(strategy.AttackTargetFor(action));
            }
            return(possibleTargets.Random());
        });

        var cardInstance = card.CreateInstance(battleState.GetNextCardId(), me);

        return(new PlayedCardV2(me, targets.ToArray(), cardInstance));
    }
Ejemplo n.º 22
0
    //moves up to an ally unit
    void MoveToSupportAlly()
    {
        myUnit.currentPath.Remove (target);

        // the unit is next to its target
        if (myUnit.currentPath.Count == 0) {
            //pass go
            myUnit.ShowCombatText("Passed", myUnit.statusCombatText);
        }
        //the unit is in normal move range
        else if (myUnit.currentPath.Last().cost <= myUnit.movespeed) {
            myUnit.moving = true;
            myUnit.remainingMove -= (int)myUnit.currentPath.Last().cost;  // there may not be a
            hasAttacked = true;
            inCloseCombat = true;
        }
        // if the unit is really far away, dash
        else{
            //check to see if it is now in melee
            if (myUnit.currentPath.Last().cost <= myUnit.movespeed*2) {
                inCloseCombat = true;
            } else {
                inCloseCombat = false;
            }

            myStrat = AIStrategy.Dash;
            myUnit.moving = true;
            myUnit.remainingMove += myUnit.movespeed - (int)myUnit.currentPath.Last().cost;
            --myUnit.actionPoints;
            hasAttacked = true;
        }

        if (myUnit.moving) {
            myMap.GetNode (myUnit.tileX, myUnit.tileY).myUnit = null;
            myUnit.currentPath.Last ().myUnit = myUnit;
        }
    }
Ejemplo n.º 23
0
 protected virtual void OnStrategyFinished(AIStrategy strategy)
 {
     CurrentStrategy = DefaultStrategy;
 }
Ejemplo n.º 24
0
 public void SetDefaultStrategy <A>() where A : AIStrategy
 {
     DefaultStrategy = GetComponent <A> ();
 }
Ejemplo n.º 25
0
    //Basic turn - attack if in range or move and attack, or dash
    void BasicTurn()
    {
        // is it already in melee?
        if (myUnit.currentPath.Count == 0) {
            myStrat = AIStrategy.Attack;
            myUnit.attacking = true;
            hasAttacked = false;
            inCloseCombat = true;
        }
        // if target is in first move range, move and attack
        else if (myUnit.remainingMove > 0 || myUnit.movespeed > 0) {
            if (myUnit.currentPath.Last().cost <= myUnit.movespeed) {
                myStrat = AIStrategy.MoveAttack;
                myUnit.moving = true;
                myUnit.attacking = true;
                myUnit.remainingMove -= (int)myUnit.currentPath.Last().cost;
                hasAttacked = false;
                inCloseCombat = true;
            }
            // if the unit is really far away, dash
            else{
                //check to see if it is now in melee
                if (myUnit.currentPath.Last().cost <= myUnit.movespeed*2) {
                    inCloseCombat = true;
                } else {
                    inCloseCombat = false;
                }
                myStrat = AIStrategy.Dash;
                myUnit.moving = true;
                myUnit.remainingMove += myUnit.movespeed - (int)myUnit.currentPath.Last().cost;
                --myUnit.actionPoints;
                hasAttacked = true;
            }
        }

        if (myUnit.moving) {
            //myMap.GetNode (myUnit.tileX, myUnit.tileY).myUnit = null;
            //myUnit.currentPath.Last ().myUnit = myUnit;
        }
    }
Ejemplo n.º 26
0
 public AIPlayer(int botNumber, AIDifficulty type, GameManager game) : base(new User {
     ID = botNumber + 1, UserName = $"AI{botNumber + 1}"
 }, game)
 {
     this.strategy = AIStrategyFactory.CreateAIStrategy(type);
 }
Ejemplo n.º 27
0
        public void rotateTower()
        {
            if (Locked)
            {
                return;
            }

            if (baseTower == null)
            {
                baseTower = _player.tokenManager.createNewTokenAI(new Vector3(_playerPosition.x, _playerPosition.y, 0), 270f);
            }

            List <House> unclaimedHouses = new List <House>();


            if (!_foundFurthestLocation)
            {
                furthestLocationFound  = _playerPosition - Vector2.down;
                _foundFurthestLocation = true;
            }

            //Determine direction base tower should face
            for (int counter = 1; counter <= 20; counter++)
            {
                Vector2    randomPos = new Vector2(Random.Range(Global.left * 8, Global.right * 8), -15);
                GameObject go        = AIStrategy.findClosestGameObject(_playerPosition, randomPos);
                if (go.tag == "House")
                {
                    House house = go.GetComponent <House> ();
                    if (house.owner == null || house.owner != _player)
                    {
                        unclaimedHouses.Add(house);
                    }
                }
//				else if (go.tag == "Spawner") {
//					if (_playerPosition.y < -5) {
//						Spawner sp = go.GetComponent<Spawner>();
//						if (sp.owner != _player) {
//							_enemySpawnerLocation = sp.transform.position;
//							_foundEnemySpawnerLocation = true;
//						}
//					}
//				}
                if ((_playerPosition.y - go.gameObject.transform.position.y) > (_playerPosition.y - furthestLocationFound.y))
                {
                    furthestLocationFound = go.gameObject.transform.position;
                }
            }
            float angle = 270f;

            Debug.Log("Unclaimed houses");
            Debug.Log(unclaimedHouses.Count);
            if (unclaimedHouses.Count > 0)
            {
                House   randomHouse     = unclaimedHouses [Random.Range(0, unclaimedHouses.Count)];
                Vector3 housePosition   = randomHouse.transform.position;
                Vector2 HousePosition2d = new Vector2(housePosition.x, housePosition.y);
                //				angle = Vector2.Angle (
                //					new Vector2(0, _player.baseposY),
                //					HousePosition2d
                //					);
                angle = Vector2.Angle(Vector2.right, _playerPosition - HousePosition2d) + 180;

                //				Debug.Log (HousePosition2d);
                //				Debug.Log (new Vector2(0, _player.baseposY));
                //				Debug.Log (angle);
            }
            else
            {
                //If we can't find any houses, 5% probability that we will lock the tower.
                if (Random.value < 0.05)
                {
//					if (_foundEnemySpawnerLocation) {
//						angle = Vector2.Angle (Vector2.right, _playerPosition - _enemySpawnerLocation) + 180;
//						finalLocked = true;
//					}
//					else {
                    angle = Vector2.Angle(Vector2.right, _playerPosition - furthestLocationFound) + 180;
//					}
                    Locked = true;
                }
                //Lock to furthest distance location
            }


            _player.tokenManager.Destroy(baseTower);
            baseTower = null;
            baseTower = _player.tokenManager.createNewTokenAI(new Vector3(_playerPosition.x, _playerPosition.y, 0), angle);
        }
Ejemplo n.º 28
0
        public void houseTower()
        {
            if (Locked)
            {
                return;
            }

            if (baseTower == null)
            {
                angle       = 270f;
                baseTower   = _player.tokenManager.createNewTokenAI(new Vector3(_startPosition.x, _startPosition.y, 0), angle);
                timeoutLock = Time.time + timeoutLockRate;
            }
            List <House> unclaimedHouses = new List <House>();
            List <House> ownHouses       = new List <House> ();

            //Determine direction base tower should face
            for (int counter = 1; counter <= 100; counter++)
            {
                Vector2    randomPos   = new Vector2(Random.Range(Global.left * 8, Global.right * 8), -14f);
                Vector2    offset      = new Vector2(Random.Range(-0.4f, 0.4f), Random.Range(-0.4f, 0.4f));
                Vector2    tryPosition = _startPosition + offset;
                GameObject go          = AIStrategy.findClosestGameObject(tryPosition, randomPos);
                if (go.tag == "House")
                {
                    House house = go.GetComponent <House> ();
                    if (house.owner == null || house.owner != _player)
                    {
                        unclaimedHouses.Add(house);
                    }
                    Vector2 hPosition = new Vector2(house.transform.position.x, house.transform.position.y);
                    if (house.owner == _player && hPosition != _startPosition)
                    {
                        ownHouses.Add(house);
                    }
                }
            }

            if (unclaimedHouses.Count > 0)
            {
                House randomHouse = unclaimedHouses [Random.Range(0, unclaimedHouses.Count)];
                //Vector3 housePosition = closestHouseLocationFound;
                Vector3 housePosition = randomHouse.transform.position;
                //Vector3 housePosition = closestHouse.transform.position;
                NextHousePosition2d = new Vector2(housePosition.x, housePosition.y);
                angle = Vector2.Angle(Vector2.right, _startPosition - NextHousePosition2d) + 180;



                //Debug.Log ("Current position " + _startPosition + " and next position " + NextHousePosition2d);
            }
            else
            {
                Locked = true;
                Debug.Log("No houses found, locking tower");
            }



            if (Time.time > timeoutLock)
            {
                Debug.Log("Locking in timelock");
                Locked = true;
            }
            if (Locked)
            {
                //Debug.Log("AI found houses owned by AI: " + ownHouses.Count);
                bool foundHome = false;
                if (ownHouses.Count > 0)
                {
//					Debug.Log ("Looking for house with vectors");
//
//					foreach (House house in ownHouses) {
//						if (checkHousePath(house)){
//								//Debug.Log ("Found house owned by AI with vectors");
//								foundHome = true;
//
//
//								if (!_foundFurthestHouseLocation) {
//									furthestHouseLocationFound = house.transform.position;
//									furthestHouseDistance = 0f;
//									furthestHouse = house;
//									_foundClosestHouseLocation = true;
//								}
//
//								housedistance = _startPosition.y - house.transform.position.y;
//
//								if (housedistance > furthestHouseDistance) {
//									furthestHouseLocationFound = house.transform.position;
//									furthestHouseDistance = housedistance;
//									furthestHouse = house;
//									NextHousePosition2d = new Vector2 (house.transform.position.x, house.transform.position.y);
//									angle = Vector2.Angle (Vector2.right, _startPosition - NextHousePosition2d) + 180;
//
//								}
//							}
//						}


//
//					}


                    if (foundHome == false)
                    {
                        //Debug.Log ("Checking for really close house by distance");
                        Debug.Log("Failed to locate target using vectors");
//					//Locked = false;

                        foreach (House house in ownHouses)
                        {
                            if (!_foundClosestHouseLocation)
                            {
                                closestHouseLocationFound = house.transform.position;
                                closestHouseDistance      = 100f;
                                // closestHouseDistance = absoluteDistance(_startPosition, go.gameObject.transform.position);
                                closestHouse = house;
                                _foundClosestHouseLocation = true;
                            }
                            Vector2 candidatePosition2D = new Vector2(house.transform.position.x, house.transform.position.y);
                            if (!existingTowerPosition(candidatePosition2D))
                            {
                                //Debug.Log ("new tower check passed");
                                housedistance = absoluteDistancePlusX(_startPosition, house.transform.position);
                                //Debug.Log (house.transform.position + " " + closestHouseLocationFound + " " + housedistance + " " + closestHouseDistance);

                                if (housedistance < closestHouseDistance)
                                {
                                    closestHouseLocationFound = house.transform.position;
                                    closestHouseDistance      = housedistance;
                                    closestHouse = house;
                                }
                            }
                        }
                        //House randomHouse = ownHouses[Random.Range (0, ownHouses.Count)];
                        //Vector3 housePosition = randomHouse.transform.position;
                        //Vector2 NextHousePosition2d = new Vector2(housePosition.x, housePosition.y);
                        NextHousePosition2d = new Vector2(closestHouseLocationFound.x, closestHouseLocationFound.y);
                        angle = Vector2.Angle(Vector2.right, _startPosition - NextHousePosition2d) + 180;
                        //Debug.Log ("Current position " + _startPosition + " and next position " + NextHousePosition2d);
                    }
                    else
                    {
                        Debug.Log("Located target using vectors");
                    }
                }
                if (absoluteDistanceY(_startPosition, new Vector2(0f, -14f)) < 4)
                {
                    Locked      = true;
                    finalLocked = true;
                    angle       = Vector2.Angle(Vector2.right, _startPosition - new Vector2(0f, -14f)) + 180;
                }
            }
            _player.tokenManager.Destroy(baseTower);
            baseTower = null;
            baseTower = _player.tokenManager.createNewTokenAI(new Vector3(_startPosition.x, _startPosition.y, 0), angle);
        }