Exemple #1
0
        public async Task ShouldReturnClusterIdWhenInitClusterCalled()
        {
            //Given
            const string clusterId = "1234";

            _swarmClient.InitCluster(Arg.Any <SwarmInitParameters>()).Returns(Task.FromResult(clusterId));
            var swarmService      = new SwarmApi.Services.SwarmService(_swarmClient, _loggerFactory);
            var serviceController = new SwarmController(swarmService);

            //When
            var response = await serviceController.InitCluster(new SwarmApi.Dtos.ClusterInitParameters {
                AdvertiseAddress = "192.168.0.101",
                ListenAddress    = "192.168.0.101"
            });

            var result  = response as JsonResult;
            var content = result.Value;

            //Then
            Assert.NotNull(result);
            string id = content.GetType().GetProperty("Id").GetValue(content, null).ToString();

            Assert.Equal(200, result.StatusCode);
            Assert.Equal(clusterId, id);
        }
Exemple #2
0
    /**
     * When looking for a target, we first check all the possible/targetables enemies
     */
    void FindPotentialTarget(Vector3 playerPosition, Vector3 swipeEnd)
    {
        // First emptying list previously made
        potentialTargets.Clear();

        // To make it simpler, all the position are replace in the screen
        Vector3 swipeVector = swipeEnd - Camera.main.WorldToScreenPoint(playerPosition);

        swipeVector.Normalize();

        // We are asking the swarmcontroller (who knows all the enemies) a list of enemies and iterate through it
        foreach (PawnAI enemy in SwarmController.GetSwarmController().GetAllEnemies())
        {
            if (IsTargetable(enemy))
            {
                // Like earlier, we convert the world point to screen point
                Vector3 enemyVector = Camera.main.WorldToScreenPoint(enemy.transform.position) - Camera.main.WorldToScreenPoint(playerPosition);
                // We calculate the angle between the swipe and the enemy...
                float angle = Vector3.Angle(swipeVector, enemyVector);
                // the distance between them...
                float distance = Vector3.Distance(playerPosition, enemy.transform.position);
                // and if the angle is between half a cone, and withing distance, a potential target is added to the list
                if (angle < targetingConeAngle / 2 && distance < targetingConeLength)
                {
                    potentialTargets.Add(enemy);
                }
            }
        }
    }
    private IEnumerator DroidDrop()
    {
        droppingDroids = true;
        canShoot       = false;
        animator.StartDropAnimation();
        weakPoint.SetActive(true);

        yield return(new WaitForSeconds(4f));

        animator.CreateDroids();
        StartCoroutine(SetCanShootAfter(true, 1.2f));

        for (int i = 0; i < numberOfDroidsToSpawn; i++)
        {
            SwarmController droid = PoolManager.instance.ReuseObject(droidPrefab, weakPoint.transform.position, Quaternion.identity).GetComponent <SwarmController> ();
            droid.Activate();
            droid.startingHealth = 2.5f;
            droid.SetDefaults();
            yield return(new WaitForSeconds(0.15f));
        }

        yield return(new WaitForSeconds(1.2f - (0.15f * numberOfDroidsToSpawn)));

        weakPoint.SetActive(false);
        nextDropTime   = Time.time + msBeforeDroidDrop / 1000f;
        droppingDroids = false;
    }
Exemple #4
0
    /**
     * Main function of this class
     *
     */
    public void Attack(APawn newTarget)
    {
        // The target should be passed to the function, but if the target is null, the closest one to the player is requested from the Swarmcontroller
        if (newTarget == null)
        {
            target = SwarmController.GetSwarmController().GetClosestEnemy(pawn);
        }
        else
        {
            target = newTarget;
        }

        // Setting the status of the pawn
        pawn.SetStatus(APawn.EStatus.ATTACKING);
        // If the pawn is an AI, the threat level of this AI is incrased
        if (pawn is PawnAI)
        {
            PawnAI ai = pawn as PawnAI;
            ai.AddThreat(1);
        }

        transform.LookAt(target.transform);

        // Animator values are set
        pawn.GetAnimator().SetInteger("cAttackIndex", currentAttackIndex);
        pawn.GetAnimator().SetInteger("cRange", GetRange());
        pawn.GetAnimator().SetTrigger("Attack");

        // In order to launch different animation, the animation index is modified here. If it exceed the max number of attack it goes back to zero
        currentAttackIndex++;
        if (currentAttackIndex > maxAttackIndex)
        {
            currentAttackIndex = 0;
        }
    }
Exemple #5
0
    public override void doDie(Creature killer)
    {
        SwarmController.getInstance().notifyTargetDestroyed();

        Vector3 originalPos = _gameInstance.transform.position;

        GameObject.Destroy(_gameInstance);

        GameObject fractured = GameObject.Instantiate(
            Resources.Load("Models/Target_Castle/Fractured/target_castle_fractured"),
            World.getInstance().getTerrainTransform()) as GameObject;

        fractured.transform.position = originalPos;

        fractured.AddComponent <TowerCollapse> ().setFlags(true, true);

        GameObject ps = ParticleSystemTable.getInstance().instantiateParticleSystem("PS_Collapse");

        ps.transform.position = originalPos;
        ps.AddComponent <ParticleSystemCollector> ();
        ps.GetComponent <ParticleSystem> ().Play();
        ps.AddComponent <AudioSource> ().loop = false;
        SoundTable.getInstance().getAudioPlayer(ps.GetComponent <AudioSource> (), "sound_collapse");
        ps.GetComponent <AudioSource> ().Play();

        CameraShake.INSTANCE.prepareShake();

        LevelManager.getInstance().notifyTargetDestroyed();
    }
Exemple #6
0
 public override EState Run()
 {
     controller.GetPawn().GetAttack().Attack(SwarmController.GetSwarmController().GetPlayer());
     controller.bToken = false;
     controller.GetPawn().bHasAttacked = true;
     return(EState.SUCCESS);
 }
Exemple #7
0
    private void Awake()
    {
        GridGameObjectNames gridGONames = Resources.Load <GridGameObjectNames>("GridGameObjectNames");

        terrainGrid    = GameObject.Find(gridGONames.TerrainGridGameObjectName).GetComponent <Grid>();
        terrainTilemap = terrainGrid.GetComponentInChildren <Tilemap>();

        markerGrid    = GameObject.Find(gridGONames.MarkerGridGameObjectName).GetComponent <Grid>();
        markerTilemap = markerGrid.GetComponentInChildren <Tilemap>();

        numberGrid    = GameObject.Find(gridGONames.NumberGridGameObjectName).GetComponent <Grid>();
        numberTilemap = numberGrid.GetComponentInChildren <Tilemap>();

        randomizerGrid    = GameObject.Find(gridGONames.RandomizerGridGameObjectName).GetComponent <Grid>();
        randomizerTilemap = randomizerGrid.GetComponentInChildren <Tilemap>();

        waterTileName = gridGONames.WaterTileName;

        swarmController = SwarmController.GetInstance();

        if (potSprite == null)
        {
            throw new Exception("ERROR: Failed to find potSprite");
        }
    }
Exemple #8
0
    private void recomputeStrategy(int spawnZone)
    {
        recomputeAggro(spawnZone);
        Queue <byte> targets = computeTargets(spawnZone);

        SwarmController.getInstance().setTargetsToAttack(spawnZone, targets);
    }
Exemple #9
0
    static public SwarmMember CreateNew(Transform swarmMemberPrefab, SwarmController controller, SwarmMemberConfig config, Transform target)
    {
        var swarmPrefab = Instantiate(swarmMemberPrefab, controller.transform.position, Quaternion.identity);
        var swarmMember = swarmPrefab.GetComponent <SwarmMember>();

        swarmMember.Init(controller, config, target);
        return(swarmMember);
    }
 public override bool Try()
 {
     if (Vector3.Distance(controller.transform.position, SwarmController.GetSwarmController().GetPlayer().transform.position) > distance)
     {
         return(bInvert ? true : false);
     }
     return(bInvert ? false : true);
 }
Exemple #11
0
    public Pathfinder(SpawnPoint spawnArea, Vector3 mainTarget)
    {
        _swarm      = SwarmController.getInstance();
        _spawnArea  = spawnArea;
        _grid       = _swarm._obstacleGrid;
        _mainTarget = mainTarget;

        _towerPositions = new Dictionary <byte, int> ();
    }
Exemple #12
0
    void Spawn()
    {
        var swarmPrefab = Random.Range(0, EnemiesToSpawn.Count);
        var spawned     = GameObject.Instantiate(EnemiesToSpawn[swarmPrefab], getSpawnPosition(), Quaternion.identity);

        SpawnedSwarm = spawned;
        spawned.OnAllInvadersDeath += OnAllInvadersDeath;
        spawned.OnInvaderDeath     += OnInvaderDied;
    }
Exemple #13
0
    public void countDownFinished()
    {
        LevelData data = _levels [_currentLevel];

        _gameActive = true;
        SwarmController.getInstance().beginWave(data._spawnPace, data._wavesData [_currentWave]._enemiesPerSubWave);
        UIBuilder.INSTANCE.setEnemyArmyText(SwarmController.getInstance().getCurrentArmySize());
        UIBuilder.INSTANCE.setWaveText(_currentWave + 1, data._waveCount);
    }
Exemple #14
0
    protected override void Start()
    {
        base.Start();

        // Similar to the PawnAI, the controller is possessed here.
        controller = GetComponent <AIController>();
        controller.Possess(this);

        attack.SetTarget(SwarmController.GetSwarmController().GetPlayer());
    }
    public void SetController(GameObject theController)
    {
        Controller = theController;
        SwarmController swarmController = Controller.GetComponent <SwarmController>();

        minVelocity = swarmController.minVelocity;
        maxVelocity = swarmController.maxVelocity;
        randomness  = swarmController.randomness;
        chasee      = swarmController.chasee;
        inited      = true;
    }
    public void setMainPath(Stack <int> reversePath)
    {
        SwarmController swarmInstance = SwarmController.getInstance();

        while (reversePath.Count > 0)
        {
            int     index = reversePath.Pop();
            Vector3 pos   = swarmInstance._positions [index];
            _pathToTarget.Enqueue(pos);
        }
    }
Exemple #17
0
 // Called at the end of an animation
 void EndAttack()
 {
     if (pawn.controller.nextInput == PlayerController.EInput.NONE)
     {
         currentAttackIndex = 0;
     }
     pawn.SetStatus(APawn.EStatus.IDLE);
     if (pawn.controller is AIController)
     {
         PawnAI ai = pawn as PawnAI;
         ai.AddThreat(-1);
         SwarmController.GetSwarmController().TakeToken();
     }
 }
    public void setTowerPath(byte towerSpawnId, Stack <int> reversePath)
    {
        SwarmController swarmInstance = SwarmController.getInstance();
        Queue <Vector3> solution      = new Queue <Vector3> ();

        while (reversePath.Count > 0)
        {
            int     index = reversePath.Pop();
            Vector3 pos   = swarmInstance._positions [index];
            solution.Enqueue(pos);
        }

        _pathsToTowers.Add(towerSpawnId, solution);
    }
Exemple #19
0
        public async Task ShouldReturnOkWhenLeaveClusterCalledWithoutErrors()
        {
            //Given
            var swarmService      = new SwarmApi.Services.SwarmService(_swarmClient, _loggerFactory);
            var serviceController = new SwarmController(swarmService);

            //When
            var response = await serviceController.LeaveCluster();

            var result = response as ContentResult;

            //Then
            Assert.NotNull(result);
            Assert.Equal(200, result.StatusCode);
        }
Exemple #20
0
        public async Task ShouldReturnBadRequestWhenDeleteMethodCalledWithEmptyId()
        {
            //Given
            var swarmService      = new SwarmApi.Services.SwarmService(_swarmClient, _loggerFactory);
            var serviceController = new SwarmController(swarmService);

            //When
            var response = await serviceController.DeleteService(null);

            var result = response as ContentResult;

            //Then
            Assert.NotNull(result);
            Assert.Equal(400, result.StatusCode);
        }
Exemple #21
0
        public async Task ShouldReturnSystemInfoWhenInspectCluster()
        {
            //Given
            _swarmClient.GetSwarmInfo().Returns(Task.FromResult(_any.Create <SwarmInspectResponse>()));
            var swarmService      = new SwarmApi.Services.SwarmService(_swarmClient, _loggerFactory);
            var serviceController = new SwarmController(swarmService);

            //When
            var response = await serviceController.InspectCluster();

            var result = response as JsonResult;

            //Then
            Assert.NotNull(result);
            Assert.Equal(200, result.StatusCode);
        }
Exemple #22
0
        public async Task ShouldReturnInternalServerErrorWhenLeaveClusterCalledWithError()
        {
            //Given
            _swarmClient.When(x => x.LeaveCluster(Arg.Any <bool>())).Do(_ => throw new ArgumentException(""));
            var swarmService      = new SwarmApi.Services.SwarmService(_swarmClient, _loggerFactory);
            var serviceController = new SwarmController(swarmService);

            //When
            var response = await serviceController.LeaveCluster();

            var result = response as ContentResult;

            //Then
            Assert.NotNull(result);
            Assert.Equal(500, result.StatusCode);
        }
    private Vector3 Calc()
    {
        Vector3 randomize = new Vector3((Random.value * 2) - 1, (Random.value * 2) - 1, (Random.value * 2) - 1);

        randomize.Normalize();
        SwarmController swarmController = Controller.GetComponent <SwarmController>();
        Vector3         flockCenter     = swarmController.flockCenter;
        Vector3         flockVelocity   = swarmController.flockVelocity;
        Vector3         follow          = chasee.transform.localPosition;

        flockCenter   = flockCenter - transform.localPosition;
        flockVelocity = flockVelocity - rigidbody.velocity;
        follow        = follow - transform.localPosition;

        return(flockCenter + flockVelocity + follow * 2 + randomize * randomness);
    }
Exemple #24
0
        public async Task ShouldReturnInternalServerErrorWhenInspectClusterAndErrorOccur()
        {
            //Given
            _swarmClient.When(x => x.GetSwarmInfo()).Do(_ => throw new ArgumentException(""));
            var swarmService      = new SwarmApi.Services.SwarmService(_swarmClient, _loggerFactory);
            var serviceController = new SwarmController(swarmService);

            //When
            var response = await serviceController.InspectCluster();

            var result = response as ContentResult;

            //Then
            Assert.NotNull(result);
            Assert.Equal(500, result.StatusCode);
        }
Exemple #25
0
        public async Task ShouldDeleteServiceBasedOnIDWhenDeleteCalled()
        {
            //Given
            const string id                = "1234";
            var          swarmService      = new SwarmApi.Services.SwarmService(_swarmClient, _loggerFactory);
            var          serviceController = new SwarmController(swarmService);

            //When
            var response = await serviceController.DeleteService(id);

            var result = response as ContentResult;

            //Then
            Assert.NotNull(result);
            Assert.Equal(204, result.StatusCode);
        }
 // Setup singleton
 void Awake()
 {
     if (i == null)
     {
         i = this;
     }
     else
     {
         Debug.LogError("There should only be 1 SwarmController in the scene!");
     }
     // Convert action register to dictionary for performance
     actionRegister = new Dictionary <string, ControllerAction>();
     foreach (ControllerActionSerialized cas in actionRegisterSerialized)
     {
         actionRegister.Add(cas.input, cas.actions);
     }
 }
Exemple #27
0
        public async Task ShouldReturnInternalServerErrorWhenGetServicesCalledAndErrorOccour()
        {
            //Given
            _swarmClient.When(x => {
                x.GetServices();
            }).Do(_ => { throw new Exception(); });
            var swarmService      = new SwarmApi.Services.SwarmService(_swarmClient, _loggerFactory);
            var serviceController = new SwarmController(swarmService);

            //When
            var response = await serviceController.GetService();

            var result = response as ContentResult;

            //Then
            Assert.NotNull(result);
            Assert.Equal(500, result.StatusCode);
        }
Exemple #28
0
        public async Task ShouldReturnBadRequestWhenIpIsNotValidAddress(string adverIp, string listenIp, string message)
        {
            //Given
            var swarmService      = new SwarmApi.Services.SwarmService(_swarmClient, _loggerFactory);
            var serviceController = new SwarmController(swarmService);

            //When
            var response = await serviceController.InitCluster(new SwarmApi.Dtos.ClusterInitParameters {
                AdvertiseAddress = adverIp,
                ListenAddress    = listenIp
            });

            var result = response as ContentResult;

            //Then
            Assert.NotNull(result);
            Assert.Equal(400, result.StatusCode);
            Assert.Equal(message, result.Content);
        }
Exemple #29
0
        public async Task ShouldReturnInternalServerErrorWhenInitClusterCalledWithError()
        {
            //Given
            _swarmClient.When(x => x.InitCluster(Arg.Any <SwarmInitParameters>())).Do(_ => throw new InvalidCastException());
            var swarmService      = new SwarmApi.Services.SwarmService(_swarmClient, _loggerFactory);
            var serviceController = new SwarmController(swarmService);

            //When
            var response = await serviceController.InitCluster(new SwarmApi.Dtos.ClusterInitParameters {
                AdvertiseAddress = "192.168.0.101",
                ListenAddress    = "192.168.0.101"
            });

            var result = response as ContentResult;

            //Then
            Assert.NotNull(result);
            Assert.Equal(500, result.StatusCode);
        }
    public override void doDie(Creature killer)
    {
        GameTowerInstance gti = killer as GameTowerInstance;

        SwarmController.getInstance().notifySoldierKilled(_spawnZoneSource, gti.getSpawn());
        LevelManager.getInstance().notifyEnemyKilled(getEnemyTemplate());

        World.getInstance().unregisterEnemy(this);

        _gameInstance.GetComponent <EnemyController> ().enabled = false;
        _gameInstance.GetComponent <HealthBarController> ().destroy();

        _gameInstance.AddComponent <AudioSource> ().loop = false;
        SoundTable.getInstance().getAudioPlayer(_gameInstance.GetComponent <AudioSource> (), "sound_enemy_death");
        _gameInstance.GetComponent <AudioSource> ().Play();
        _gameInstance.GetComponent <Animator> ().SetBool("Death", true);
        _gameInstance.AddComponent <EnemyDeathController> ();

        //GameObject.Destroy (_gameInstance);
    }
Exemple #31
0
        public void Control_swarm_of_10_with_pid()
        {
            var receivedSeries = new List<Timestamped<double>>();
            var t0 = 0.AsMinute();
            var setpoint = 100.0.At(t0.Add(5.min()));

            var swarm = Enumerable.Range(0, 10).Select(i => new LinearMosquito(2.0.In(1.min()), t0)).ToList();
            // max.At(5.min)=10x10=100

            var specifiedSwarm = swarm.Select(m => m.WithSpec(new Engine<double>()
                { Gradient = m.Gradient, Stages = new SortedSet<double>() {0.0, 100.0} }));

            var swarmController = new SwarmController(
                specifiedSwarm, new PowerBasedAllocator(), new PIDAlgorithm(0.5, 0.5, 0.5, 0.0));

            swarmController.Receive += (t) => receivedSeries.Add(t);
            swarmController.Send(setpoint);

            var clock = new Clock(t0);
            swarm.ForEach(m => clock.Subscribe(m));

            clock.Tick(5.min());
            Assert.AreEqual(setpoint, receivedSeries.Last());
        }