public static int[] tsp(int[][] adjacencyMatrix)
        {
            AntColonyOptimization.adjacencyMatrix = adjacencyMatrix;
            numberOfNodes = adjacencyMatrix[1].Length;
            int[] visited = new int[numberOfNodes];
            int[] caminho = new int[numberOfNodes + 1];
            int population = 600;
            int raio = 1000;
            Ant[] colony = new Ant[population];

            //gerarVizinhos(raio);

            for (int i = 0; i < population; i++)
            {
                colony[i] = new Ant();
            }

            for (int i = 0; i < numberOfNodes - 1; i++)
            {
                nextCity(colony);

                segueFeromonio(colony, raio);
            }

            fechaCiclo(colony);

            segueFeromonio(colony, 100000);

            for (int i = 0; i < numberOfNodes; i++)
                caminho[i] = colony[0].caminho[i];

            caminho[numberOfNodes] = colony[0].fitness;

            return caminho;
        }
        private void ProcessLiveAnts(IEnumerable<TurnState.Point> ants, int turnNumber)
        {
            ants = ants.Where(x => x.Owner == 0);

            foreach (TurnState.Point point in ants)
            {
                if (this._ownAntTrackingManager.AntHasMovedTo(point.Row, point.Column))
                    continue;

                MapTile tile = GameContext.Map.At(point.Row, point.Column);
                var ant = new Ant(tile);

                tile.CurrentAnt = ant;
                ant.CurrentPosition = tile;
                ant.MovementStrategy = new LongOrientatedDirectionAntStrategy(ant);

            //                if (turnNumber > 5)
            //                {
            //                    MapRoute route =
            //                        tile.DiscoverNearestRoutesTo(6, mapTile => mapTile.CurrentAnt != null).FirstOrDefault();
            //                    if (route != null)
            //                    {
            //                        Ant leader = route.Destination.CurrentAnt;
            //                        ant.MovementStrategy = new FollowLeaderAntStrategy(ant, leader);
            //                    }
            //                }
            }
        }
 private static void nextCity(Ant[] colony)
 {
     for (int i = 0; i < colony.Length; i++)
     {
         colony[i].AddCity();
     }
 }
 private static void fechaCiclo(Ant[] colony)
 {
     foreach (Ant ant in colony)
     {
         ant.fitness += adjacencyMatrix[ant.caminho[0]][ant.caminho[numberOfNodes - 1]];
     }
 }
        public void EnrollToMove(Ant ant, MapTile destination)
        {
            if (destination.State == TileState.Water)
                goto enrollSelf;

            // we do not want many ants moving into the same tile.
            // first one in will move there successfully
            // todo: notify the ant of the collision. We will then ask the ant to reroute itself than forcing it to yield.
            if (this._enrolledDestinations.ContainsKey(destination))
                goto enrollSelf;

            Direction direction;
            MapTile currentPosition = ant.CurrentPosition;

            if (currentPosition.North == destination)
                direction = Direction.North;
            else if (currentPosition.South == destination)
                direction = Direction.South;
            else if (currentPosition.East == destination)
                direction = Direction.East;
            else if (currentPosition.West == destination)
                direction = Direction.West;
            else
                goto enrollSelf;

            var enrolledDetinationKey = new EnrolledDestinationKey(ant, direction);

            this._enrolledDestinations.Add(destination, enrolledDetinationKey);
            this._quickFastForwardMapping.Add(currentPosition, destination);
            return;

            enrollSelf:
            this.EnrollCurrentLocation(ant);
        }
Esempio n. 6
0
 public void CanTurn(Rotation rotation)
 {
     var ant = new Ant(_initialDirection, _initialPosition);
     var expectedDirection = _initialDirection.Rotate(rotation);
     ant.Turn(rotation);
     ant.Direction.Should().Be(expectedDirection);
 }
        public void DoNotIssueMoveIntoStationaryAnt()
        {
            var mock = new MockFactory();
            var outputAdapterMock = mock.CreateMock<IGameOutputAdapter>();

            using (mock.Ordered)
            {
                outputAdapterMock.Expects.One.MethodWith(adapter => adapter.NotifyEndOfTurn());
            }

            var trackerManager = new OwnAntTrackingManager(outputAdapterMock.MockObject);

            MapTile origin = GameContext.Map.At(3, 4);
            MapTile destination = origin.North;
            var ant = new Ant(origin);

            destination.CurrentAnt = new Ant(destination);
            origin.CurrentAnt = ant;

            trackerManager.HasProcessedAllInputMoves();
            trackerManager.EnrollToMove(ant, destination);
            trackerManager.FinalizeAllMoves();

            Assert.IsNotNull(origin.CurrentAnt);
            Assert.AreEqual(ant, origin.CurrentAnt);

            mock.VerifyAllExpectationsHaveBeenMet();
        }
 public PerformedAction(State fromState, Action action, Ant ownAnt, Location nextLocation,
                    Ant friend)
 {
     this.fromState = fromState;
       this.action = action;
       this.ownAnt = ownAnt;
       this.friend = friend;
       this.nextLocation = nextLocation;
 }
Esempio n. 9
0
        /// <summary>
        /// Benachrichtigt andere Ameisen.
        /// </summary>
        /// <param name="coords">Die Koordinaten welche den anderen Ameisen mitgeteilt werden soll</param>
        /// <param name="ant">Die Ameise welche mitteilt</param>
        public void notifyAnts(HashSet <Coordinates> coords, Ant ant)
        {
            BoardObject[] objs = getBoardObjectsInView(ant.Coords, ant.ViewRange * 2);
            for (int i = 0; i < objs.Length; i++)
            {
                BoardObject obj = objs[i];
                if (obj == ant)
                {
                    continue;
                }

                if (obj.isAnt())
                {
                    Ant antToNotify = obj as Ant;
                    antToNotify.AI.notify(coords);
                }
            }
        }
Esempio n. 10
0
        private void UpdateVariableMaxDependencies(Ant <Edge> ant)
        {
            int    bestIndex          = this._bestDependencies - 1;
            double currentProbability = this._dependenciesProbability[bestIndex];

            this._dependenciesProbability[bestIndex] += currentProbability * ant.Solution.Quality * 0.5;

            double sum = 0;

            foreach (double value in this._dependenciesProbability)
            {
                sum += value;
            }
            for (int index = 0; index < this._dependenciesProbability.Length; index++)
            {
                this._dependenciesProbability[index] /= sum;
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Just as ants can see various types of food, they can
        /// also visually detect other game elements. This method
        /// is called if the ant detects an ant from an enemy colony.
        /// Read more: "http://wiki.antme.net/en/API1:SpotsEnemy(Ant)"
        /// </summary>
        /// <param name="ant">spotted ant</param>
        public override void SpotsEnemy(Ant ant)
        {
            // It is sufficient to only spread the info once per ant.
            if (HasSeenForeignAnt != true)
            {
                // Range of 500 to get many friends informed.
                SpreadInfoForeignAntsExist(500);
            }

            // Apples are besides bugs the main source for gathering points.
            // Therefore only attack ants if not currently carrying an apple.
            if (!IsCarryingApple)
            {
                // One-on-One (Offence is the beste Defense).
                Drop(); // Sugar is less important
                Attack(ant);
            }
        }
        protected bool CheckBestTour()
        {
            Ant    bestAnt        = antin.FindBestAnt();
            double tourLengthTemp = bestAnt.TourLength;

            if (tourLengthTemp < TourLength)
            {
                TourLength = tourLengthTemp;
                BestTour.Clear();
                for (int i = 0; i < bestAnt.Tour.Count; i++)
                {
                    BestTour.Add(bestAnt.Tour[i]);
                    BestIteration = iteration;
                }
                return(true);
            }
            return(false);
        }
Esempio n. 13
0
    private void NextMove(Move move)
    {
        Ant a = move.Next(Ants, AntPrefab);

        if (a == null)
        {
            ShowMessage("MOVE ERROR");
            StopMoves();
        }
        else
        {
            a.MoveCoroutines.Enqueue(new MoveCoroutineParams(a, a.PrevRoom.Obj.transform.position, move.Room.Obj.transform.position));
            if (a.MoveCoroutines.Count == 1)
            {
                StartCoroutine(MoveObj(a.MoveCoroutines.Peek()));
            }
            a.PrevRoom = move.Room;
        }
    }
Esempio n. 14
0
    protected override void LetVisit(Ant ant)
    {
        // Return the ant from where it came
        Location temp = ant.destination;

        ant.destination = ant.origin;
        ant.origin      = temp;

        // Give Ant food
        if (ant.foodCarrying < Ant.carryCapacity && foodAvailable > 0f)
        {
            float foodGiving = Ant.carryCapacity - ant.foodCarrying;
            foodGiving        = (foodGiving < foodAvailable) ? foodGiving : foodAvailable;
            foodAvailable    -= foodGiving;
            ant.foodCarrying += foodGiving;
        }

        Accept(ant);
    }
Esempio n. 15
0
        private void InitializeAnts()
        {
            var totalAnts = AcoOptions.TotalAnts;

            Ants = new Ant[totalAnts];

            // since we are returning to the initial city the trail must have a length of the total cities + 1
            var pathLength = _tspInstance.CitiesSet.Count + 1;

            // initialize a new path
            var sequentialPath = new int[pathLength];

            // initially set a sequential path
            var index      = 0;
            var cities     = _tspInstance.CitiesSet;
            var enumerator = cities.GetEnumerator();

            while (enumerator.MoveNext())
            {
                var current = enumerator.Current.Key;
                // instead of index we could have used current - 1 but to make sure that it will always start from 0 we used this counter
                sequentialPath[index] = current;
                index++;
            }

            // path must end at 1
            sequentialPath[sequentialPath.Length - 1] = 1;

            // initially we want to set random trails/paths to the ants
            for (int i = 0; i < totalAnts; i++)
            {
                // clone sequential path so we could pass it to the GetRandomPath function and get a random path
                var tmpPath = (int[])sequentialPath.Clone();
                var ant     = new Ant(tmpPath);

                // turns the sequential path that was passed into the constructor to a rando path/trail
                ant.SetRandomPath(Random);

                // calculates the total distance of the ant's path/trail
                CalculatePathDistance(ant);
                Ants[i] = ant;
            }
        }
Esempio n. 16
0
        private void ButtonAdd_Click(object sender, EventArgs e)
        {
            //zabezpieczenie przez znakami lub pustym polem
            if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "[^0-9]") || (textBox1.Text == ""))
            {
                MessageBox.Show("Musisz wpisać liczbę");
            }

            else
            {
                for (int i = 0; i < int.Parse(textBox1.Text); i++)
                {
                    Ant ant = new Ant(new Point(World.Cells[0].Point.X, World.Cells[0].Point.Y), World.Cells);
                    ant.AntCells[0].cellPheromoneUp++;
                    World.Ants.Add(ant);
                    AntCountLabel.Text = World.Ants.Count.ToString();
                }
            }
        }
Esempio n. 17
0
    private void ResolveDecision(Ant ant)
    {
        // No resolution for ants that are just born
        if (ant.decision == null)
        {
            return;
        }

        // Placing the pheromones: the pheromones number check is made by the list-converting method
        pheromoneMaps[ant.team.teamId][ant.gameCoordinates.x][ant.gameCoordinates.y] = PheromoneDescriptor.ListFromDigestList(ant.decision.pheromones);

        // Displays the pheromones
        pheromoneMapDisplayer.UpdateCell(pheromoneMaps, ant.gameCoordinates.x, ant.gameCoordinates.y);

        TurnError error = TreatDecision(ant);

        ant.pastTurn = new PastTurnDigest(ant.decision, error);
        ant.mindset  = ant.decision.newMindset;
    }
Esempio n. 18
0
    private TurnError TreatDecision(Ant ant)
    {
        Decision decision = ant.decision;

        if (decision == null || decision.choice == null)
        {
            return(TurnError.ILLEGAL);
        }

        switch (decision.choice.type)
        {
        case ActionType.NONE:
            return(TurnError.NONE);

        case ActionType.MOVE:
            return(ActMove(ant, decision.choice.direction));

        case ActionType.ATTACK:
            return(ActAttack(ant, decision.choice.direction));

        case ActionType.EAT:
            return(ActEat(ant, decision.choice.direction, decision.choice.quantity));

        case ActionType.STOCK:
            return(ActStock(ant, decision.choice.direction, decision.choice.quantity));

        case ActionType.GIVE:
            return(ActGive(ant, decision.choice.direction, decision.choice.quantity));

        case ActionType.ANALYSE:
            return(ActAnalyse(ant, decision.choice.direction));

        case ActionType.COMMUNICATE:
            return(ActCommunicate(ant, decision.choice.direction, decision.choice.word));

        case ActionType.EGG:
            return(ActEgg(ant, decision.choice.direction));

        default:
            Debug.LogWarning("Unknown ActionType: " + decision.choice.type);
            return(TurnError.ILLEGAL);
        }
    }
Esempio n. 19
0
        private void UpdateContainerDeposits(Player player, Ant ant)
        {
            if (ant.PlayerUnit.Unit.Container != null &&
                ant.PlayerUnit.Unit.Engine == null &&
                ant.PlayerUnit.Unit.Container.Metal < ant.PlayerUnit.Unit.Container.Capacity)
            {
                // Standing containers
                if (ant.PheromoneDepositNeedMinerals != 0 &&
                    ant.PheromoneDepositNeedMineralsLevel != ant.PlayerUnit.Unit.Container.Level)
                {
                    player.Game.Pheromones.DeletePheromones(ant.PheromoneDepositNeedMinerals);
                    ant.PheromoneDepositNeedMinerals = 0;
                }
                if (ant.PheromoneDepositNeedMinerals == 0)
                {
                    int range = 2;
                    if (ant.PlayerUnit.Unit.Container.Level == 2)
                    {
                        range = 3;
                    }
                    else if (ant.PlayerUnit.Unit.Container.Level == 3)
                    {
                        range = 4;
                    }

                    ant.PheromoneDepositNeedMineralsLevel = ant.PlayerUnit.Unit.Container.Level;
                    int intensity = (ant.PlayerUnit.Unit.Container.Metal * 100 / ant.PlayerUnit.Unit.Container.Capacity) / 100;
                    ant.PheromoneDepositNeedMinerals = player.Game.Pheromones.DropPheromones(player, ant.PlayerUnit.Unit.Pos, range, PheromoneType.ToHome, 1, true);
                }
                else
                {
                    int intensity = (ant.PlayerUnit.Unit.Container.Metal * 100 / ant.PlayerUnit.Unit.Container.Capacity) / 100;
                    player.Game.Pheromones.UpdatePheromones(ant.PheromoneDepositNeedMinerals, 1);
                }
            }
            if (ant.PheromoneDepositNeedMinerals != 0 &&
                (ant.PlayerUnit.Unit.Container == null || ant.PlayerUnit.Unit.Container.Metal >= ant.PlayerUnit.Unit.Container.Capacity))
            {
                // Exits no longer. Remove deposit.
                player.Game.Pheromones.DeletePheromones(ant.PheromoneDepositNeedMinerals);
                ant.PheromoneDepositNeedMinerals = 0;
            }
        }
Esempio n. 20
0
    private void UpdateAntIntention(ref Ant ant)
    {
        // Make sure the ant intends to go home if it is carrying a resource
        if (ant.hasResource == true)
        {
            ant.intention = (CONST.homeCoordinates - ant.coordinates).normalized;
        }
        else
        {
            if (Time.time > ant.nextRandomizationTimestamp)
            {
                // Randomize intention
                ant.intention = Random.insideUnitCircle.normalized;

                // Randomize next randomization timestamp
                ant.nextRandomizationTimestamp = Time.time + Random.Range(ANT.randomizationPeriodMin, ANT.randomizationPeriodMax);
            }
        }
    }
Esempio n. 21
0
    private static MySpecialCollectionList <IBeast> GetSpecialCollectionList()
    {
        var ant = new Ant()
        {
            Name = "Mr Ant"
        };
        var cat = new Cat()
        {
            Name = "Mr Cat"
        };
        var dog = new Dog()
        {
            Name = "Mr Dog"
        };
        var Special            = new Special <IBeast>(ant);
        var specialCollection1 = new MySpecialCollection <IBeast>()
        {
            Items =
            { new Special <IBeast>(ant),
              new Special <IBeast>(cat),
              new Special <IBeast>(dog) }
        };

        specialCollection1.Name = "Special Collection1";
        var specialCollection2 = new MySpecialCollection <IBeast>()
        {
            Items =
            { new Special <IBeast>(ant),
              new Special <IBeast>(dog) }
        };

        specialCollection2.Name = "Special Collection2";
        var specialCollectionList = new MySpecialCollectionList <IBeast>()
        {
            Items =
            {
                specialCollection1, specialCollection2
            }
        };

        specialCollectionList.Name = "Special Collection List";
        return(specialCollectionList);
    }
Esempio n. 22
0
    private void CheckForAnts()
    {
        var ants = AntManager.Ants;

        foreach (Ant ant in ants)
        {
            if (ant.Nest.Player != this.nest.Player)
            {
                Vector2 antPosition = ant.AntGameObject.transform.position;
                float   antDistance = Vector2.Distance(antPosition, this.antGameObject.transform.position);
                if (antDistance < sensorRange)
                {
                    MoveToPosition(antPosition);
                    antToFollow = ant;
                    state       = "charge";
                }
            }
        }
    }
Esempio n. 23
0
        public void Ant_moves_five_steps()
        {
            World world = new World();
            Ant   ant   = new Ant(world);

            ant.Move(5);

            Location currentLocation = new Location {
                XCoordinate = 2, YCoordinate = 3, Colour = "white"
            };

            Assert.That(ant.CurrentLocation, Is.EqualTo(currentLocation));

            Location previousLocation = new Location {
                Colour = "white", XCoordinate = 3, YCoordinate = 3
            };

            Assert.That(ant.World.Locations[0], Is.EqualTo(previousLocation));
        }
Esempio n. 24
0
    public void RemoveAntFromList(Ant ant)
    {
        if (ant == null)
        {
            Debug.Log("Ant null in RemoveAntFromList in AntManager");
        }

        antList.Remove(ant);

        switch (ant.antType)
        {
        case Ant.AntType.EXCAVATOR:
            excavatorAnts.Remove(ant);
            RemoveFromExcavatorCount(ant);
            break;

        case Ant.AntType.FORAGER:
            foragerAnts.Remove(ant);
            RemoveFromForagerCount(ant);
            break;

        case Ant.AntType.GARDENER:
            gardenerAnts.Remove(ant);
            RemoveFromGardenerCount(ant);
            break;

        case Ant.AntType.QUEEN:
            queenAnts.Remove(ant);
            RemoveFromQueenCount(ant);
            break;

        case Ant.AntType.SOLDIER:
            soliderAnts.Remove(ant);
            RemoveFromSoldierCount(ant);
            break;

        case Ant.AntType.TRASH_HANDLER:
            trashHandlerAnts.Remove(ant);
            RemoveFromTrashHandlerCount(ant);
            break;
        }
    }
Esempio n. 25
0
 void Start()
 {
     netRadius = net.transform.localScale.x;
     //Bind
     sliders = GetComponentsInChildren <Slider>();
     for (int i = 0; i < sliders.Length; i++)
     {
         Slider slider = sliders[i];
         if (i != 2)
         {
             slider.onValueChanged.AddListener((float value) => OnSliderChanged(value, slider));
         }
         //数量改变
         else
         {
             slider.onValueChanged.AddListener((float value) => OnCountChanged(value, slider));
         }
     }
     //Get Value
     rate        = sliders[0].value;
     decay       = sliders[1].value;
     count       = (int)sliders[2].value;
     speed       = sliders[3].value;
     carry       = sliders[4].value;
     radius      = sliders[5].value;
     maxAntCount = (int)sliders[2].maxValue;
     //produce ants
     for (int i = 0; i < maxAntCount; i++)
     {
         Vector3 pos = Random.insideUnitSphere * netRadius;
         pos = pos.normalized * (netRadius / 2 + pos.magnitude);
         pos = new Vector3(pos.x + net.transform.position.x, 0.5f, pos.z + net.transform.position.z);
         GameObject antObj = Instantiate(antPrefab, pos, Quaternion.identity);
         Ant        ant    = antObj.GetComponent <Ant>();
         ants.Add(ant);
         antObj.SetActive(false);
     }
     ProduceAnts();
     //get foods
     foods = GameObject.FindGameObjectsWithTag("Food").ToList();
     etas  = new float[ants.Count];
 }
        public void TestNoCollisions_1()
        {
            GameState state = new GameState(10, 10, 1, 1, 1, 5, 1);

            state.Set(new Tile[, ]
            {
                { _, _, _, _, _, _, _, _, _, _ },
                { _, _, _, _, _, _, _, _, _, _ },
                { _, _, _, _, _, a, _, _, _, _ },
                { _, _, a, a, a, a, a, _, _, _ },
                { _, _, a, a, _, _, _, _, _, _ },
                { _, _, a, a, _, A, _, _, _, _ },
                { _, _, _, _, _, _, _, _, _, _ },
                { _, _, _, _, _, _, _, _, _, _ },
                { _, _, _, _, _, _, _, _, _, _ },
                { _, _, _, _, _, _, _, _, _, _ },
            });

            AttackManager dut = new AttackManager(state);

            dut.MoveOffensive(state);


            foreach (Ant a in state.MyAnts)
            {
                Assert.IsTrue(a.hasMoved);
            }


            for (int i = 0; i < state.MyAnts.Count; i++)
            {
                Ant      a    = state.MyAnts[i];
                Vector2i aPos = a.position + Vector2i.AllDirections[(int)a.direction];
                for (int j = 0; j < i; j++)
                {
                    Ant      b    = state.MyAnts[j];
                    Vector2i bPos = b.position + Vector2i.AllDirections[(int)b.direction];

                    Assert.AreNotEqual(aPos, bPos);
                }
            }
        }
Esempio n. 27
0
        public static async Task <Ant> Create()
        {
            Caption.Title("Add Ant");
            List <Hive> hives = await Context.Get.Hives.ToListAsync();

            if (hives.Count == 0)
            {
                Caption.Error("You cannot add Ants without a Hive");
                return(null);
            }

            var ant = new Ant();

            Console.WriteLine("Add a new Ant");
            ant.Name            = Ask.String("Name");
            ant.AgeInDays       = Ask.Value("Age in Days");
            ant.FavoriteAntGame = Ask.String("Favourite Game");

            return(ant);
        }
Esempio n. 28
0
        public void CheckAntCanMove(
            int degree,
            Colors inputColor,
            Point ptIn,
            int expectedDegree,
            Colors expectedColor,
            Point ptOut)
        {
            var map = new Map(10, 10);
            var ant = new Ant();

            ant.Coordinate = ptIn;
            ant.Angle      = degree;
            map.SetColor(ant.Coordinate, inputColor);
            var rcolor = ant.Move(map);

            Assert.That(ant.Coordinate, Is.EqualTo(ptOut), "Endpoint not as expected");
            Assert.That(ant.Angle, Is.EqualTo(expectedDegree), "Angle not as expected");
            Assert.That(rcolor, Is.EqualTo(expectedColor), "Color not as expected");
        }
Esempio n. 29
0
 /// <summary>
 /// Erhöht die Anzahl der Ameisen eines Ameisentyps um eins.
 /// </summary>
 /// <param name="ant">Die neue Ameise.</param>
 public void incrementAnts(Ant ant)
 {
     AntCount++;
     if (ant.isCarry())
     {
         CarryCount++;
     }
     else if (ant.isScout())
     {
         ScoutCount++;
     }
     else if (ant.isWarrior())
     {
         WarriorCount++;
     }
     else
     {
         throw new RuntimeException("Unknown ant type.");
     }
 }
Esempio n. 30
0
    //[Command]
    void CmApply(int x, int y)
    {
        //Debug.Log("Entered PlayerID: " + player);

        Position destination = new Position(x, y);
        bool     applied;

        if (!dirtBuildClicked && !wallBuildClicked)
        {
            if (!shiftClicked)
            {
                Ant testAnt = selectedObject1st.GetComponent <Ant>();
                //if (testAnt == null) print("NOOOOOOOOOOOOOOOOO");
                applied = selectedObject1st.GetComponent <Ant>().applyNewRoute(destination, (player));
            }
            else
            {
                applied = selectedObject1st.GetComponent <Ant>().applyNewRoute(destination, player, false);
            }
        }
        else
        {
            if (!shiftClicked)
            {
                applied = selectedObject1st.GetComponent <Ant>().applyNewRoute(destination, player, true, true, (dirtBuildClicked ? 'e' : 's'));
            }
            else
            {
                applied = selectedObject1st.GetComponent <Ant>().applyNewRoute(destination, player, false, true, (dirtBuildClicked ? 'e' : 's'));
            }
        }
        if (applied)
        {
            selectedObject2nd = null;
        }
        else
        {
            selectedObject2nd = null;
            print("could not apply move!");
        }
    }
Esempio n. 31
0
        public override void CreateSolution()
        {
            this._iterationBestAnt = null;

            for (int antIndex = 0; antIndex < this.ColonySize; antIndex++)
            {
                this.ConstructionGraph.ResetValidation(false);

                for (int i = 0; i < 2; i++)
                {
                    this.ConstructionGraph.Components[i].IsValid = true;
                }

                Ant <DRComponent> ant = new Ant <DRComponent>(antIndex, this);

                ant.CreateSoltion();

                if (!IsValid(ant.Solution))
                {
                    continue;
                }

                if (this._complement != null)
                {
                    ant.Solution = ExtensionMethodsUtility.Merge(ant.Solution, _complement);
                }

                this.EvaluateSolutionQuality(ant.Solution);

                if (this._iterationBestAnt == null || ant.Solution.Quality > this._iterationBestAnt.Solution.Quality)
                {
                    this._iterationBestAnt = ant;
                }


                if (this.OnPostAntSolutionContruction != null)
                {
                    this.OnPostAntSolutionContruction(ant, null);
                }
            }
        }
Esempio n. 32
0
    public void FixedUpdate()
    {
        if (Constants.multiplayer && Network.isClient)
        {
            return;
        }
        //Move the ant in its desired direction
        transform.Translate(velocity());

        //If there is an ant to attack, attack it
        Ant ant = behavior.antToAttack();

        if (ant != null)
        {
            float distance = Mathf.Sqrt((ant.gameObject.transform.position - transform.position).sqrMagnitude);
            if (distance < this.range)
            {
                ant.doDamage(this.damage * Time.deltaTime);
            }
        }
    }
Esempio n. 33
0
 /// <summary>
 /// Verringert die Anzahl der Ameisen eines Ameisentyps um eins.
 /// </summary>
 /// <param name="ant">Die zu verringernde Ameise.</param>
 public void decreaseAnts(Ant ant)
 {
     DeathCount++;
     AntCount--;
     if (ant.isCarry())
     {
         CarryCount--;
     }
     else if (ant.isScout())
     {
         ScoutCount--;
     }
     else if (ant.isWarrior())
     {
         WarriorCount--;
     }
     else
     {
         throw new RuntimeException("Unknown ant type.");
     }
 }
Esempio n. 34
0
        public App()
        {
            //Lets create a new weather object
            Weather weather = new Weather();

            //We also create an Ant and a Plant.
            Plant plant = new Plant();
            Ant   ant   = new Ant();

            //Now we set the plant and and to observe the weather
            weather.AddObserver(plant);
            weather.AddObserver(ant);

            //Now we change the weather and track down the observers
            weather.ChangeWeather();
            weather.ChangeWeather();
            weather.ChangeWeather();
            weather.ChangeWeather();

            Console.ReadLine();
        }
Esempio n. 35
0
        public void Test_Fight_With_Other_Should_Lose()
        {
            //initialize
            IInfo       info = A.Fake <IInfo>();
            IRandomTest rnd  = A.Fake <IRandomTest>();

            var ant = new Ant(info, rnd);

            var producerConsumer = A.Fake <IProducerConsumerMessages <string> >();

            ant.ProducerConsumer = producerConsumer;
            var other = A.Fake <IDynamicObject>();

            A.CallTo(() => other.Strength).ReturnsLazily(() => 4);
            A.CallToSet(() => other.Strength).To(6);
            //act
            ant.Fight(other);
            //assert
            A.CallTo(() => other.AddStrength(2)).MustHaveHappened();
            Assert.AreEqual(State.Depressed, ant.State);
        }
Esempio n. 36
0
        public void Test_Fight_With_Other_Should_Win()
        {
            //initialize
            var ant = new Ant()
            {
                Strength = 3
            };

            var other            = A.Fake <IDynamicObject>();
            var producerConsumer = A.Fake <IProducerConsumerMessages <string> >();

            ant.ProducerConsumer = producerConsumer;
            A.CallTo(() => other.Strength).Returns(1);
            A.CallTo(() => other.SetState(A <State> ._)).Invokes(() => other.State = State.Depressed);

            //act
            ant.Fight(other);
            //assert
            Assert.AreEqual(5, ant.Strength);
            Assert.AreEqual(State.Depressed, other.State);
        }
Esempio n. 37
0
    private void Initialize(Transform trainer, Ant[] tmp)
    {
        trainer.GetComponentInChildren <Sandbox>().Initialize(
            clone, -sandboxHeightRange + heightIncr * (float)counter++);

        float angle = 0f;
        float incr  = Mathf.PI * 2f / (float)agentInstances;
        // Clone ant present in scene.
        Ant ant = trainer.GetComponentInChildren <Ant>();

        for (int i = 0; i < agentInstances; i++)
        {
            ant      = i > 0 ? Instantiate(ant.gameObject, trainer).GetComponent <Ant>() : ant;
            ant.name = "Ant " + i;
            float radius = Random.Range(minSpawnRadius, maxSpawnRadius);
            ant.GetComponent <WalkerAgent>().Initialize(new Vector3(
                                                            radius * Mathf.Cos(angle), 0f, radius * Mathf.Sin(angle)));
            angle += incr;
            tmp[i] = ant;
        }
    }
Esempio n. 38
0
    public BuildingTask GetJob(Ant ant)
    {
        Queue.Sort((taskA, taskB) =>
        {
            Vector3 va   = taskA.BaseTile.transform.position;
            Vector3 vb   = taskB.BaseTile.transform.position;
            Vector3 vant = ant.transform.position;

            return(Mathf.Abs(va.x - vant.x) + Mathf.Abs(va.z - vant.z) < Mathf.Abs(vb.x - vant.x) + Mathf.Abs(vb.z - vant.z) ? -1 : 1);
        });

        var job = Queue.Where((task) => task.Ant == null || task.Ant == ant).FirstOrDefault();

        if (job != null)
        {
            job.Ant = ant;
            return(job);
        }

        return(null);
    }
Esempio n. 39
0
        public AntColony(int citiesCount, int[,] distance)
        {
            this.citiesCount = citiesCount;
            this.distance = distance;
            INIT_PHEROMONE = 1.0 / citiesCount;
            prng = new Random();

            ants = new Ant[this.citiesCount];
            for (int i = 0; i < citiesCount; ++i)
            {
                ants[i] = new Ant(citiesCount, i);
            }

            pheromone = new double[citiesCount, citiesCount];
            for (int i = 0; i < citiesCount; ++i)
            {
                for (int j = 0; j < citiesCount; ++j)
                {
                    pheromone[i, j] = INIT_PHEROMONE;
                }
            }

            bestRoute = new int[citiesCount];
        }
Esempio n. 40
0
 public override void UnderAttack(Ant ant) { BeingAttacked(this, new ItemEventArgs(Items.EnemyAnt.Track(ant))); }
        public void SimpleTrackingCase()
        {
            var mock = new MockFactory();
            var outputAdapterMock = mock.CreateMock<IGameOutputAdapter>();

            using (mock.Ordered)
            {
                outputAdapterMock.Expects.One
                    .Method(adapter => adapter.MoveAnt(0, 0, 0))
                    .WithAnyArguments();

                outputAdapterMock.Expects.One.MethodWith(adapter => adapter.NotifyEndOfTurn());
            }

            var trackerManager = new OwnAntTrackingManager(outputAdapterMock.MockObject);

            MapTile origin = GameContext.Map.At(3, 4);
            MapTile destination = origin.North;
            var ant = new Ant(origin);

            origin.CurrentAnt = ant;

            trackerManager.HasProcessedAllInputMoves();
            trackerManager.EnrollToMove(ant, destination);
            trackerManager.FinalizeAllMoves();

            Assert.IsNull(origin.CurrentAnt);

            trackerManager.AntHasMovedTo(destination.Row, destination.Column);

            Assert.IsNull(origin.CurrentAnt);
            Assert.AreEqual(ant, destination.CurrentAnt);

            mock.VerifyAllExpectationsHaveBeenMet();
        }
Esempio n. 42
0
        public int selectNextCity(Ant ant)
        {
            int from, to;
            double denom = 0.0;

            from = ant.currCity;

            for (to = 0; to < citiesCount; ++to)
            {
                if (ant.tabu[to] == 0)
                {
                    denom += antProduct(from, to);
                }
            }

            Debug.Assert(denom != 0, "Denom is zero");

            while (true)
            {
                double p;
                to++;
                if (to >= citiesCount)
                {
                    to = 0;
                }
                if (ant.tabu[to] == 0)
                {
                    p = antProduct(from, to) / denom;
                    if (prng.NextDouble() < p)
                    {
                        return to;
                    }
                }
            }
        }
 public LongOrientatedDirectionAntStrategy(Ant ant)
     : base(ant, null)
 {
     this._direction = NextGlobalDirection();
     this.GenerateNewRoute();
 }
 public void can_feed_a_snake()
 {
     IAnimal ant = new Ant();
     ant.Feed().ShouldEqual("ant fed");
 }
Esempio n. 45
0
 public void CanMoveForward()
 {
     var ant = new Ant(_initialDirection, _initialPosition);
     ant.MoveForward();
     ant.Position.Should().Be(_initialDirection.MoveFrom(_initialPosition));
 }
Esempio n. 46
0
 //eating takes up a turn. It replenishes hunger to full
 protected override void Feed(Ant ant, int amount)
 {
 }
Esempio n. 47
0
 //the ant picks up and object. Picking up an object means that the object moves when this ant does
 protected override void PickUp(Ant ant)
 {
 }
 private void EnrollCurrentLocation(Ant ant)
 {
     this._finalizedMovements.Add(ant.CurrentPosition, ant);
 }
Esempio n. 49
0
 //eating takes up a turn. It replenishes hunger to full
 protected override void Feed(Ant ant, int amount)
 {
     StateProperty = State.Feeding;
     //take food from carrying amount and add it to the hunger of the ant being fed
 }
 public void cannot_groom_a_snake()
 {
     IAnimal snake = new Ant();
     snake.Groom();
 }
Esempio n. 51
0
 //the ant picks up and object. Picking up an object means that the object moves when this ant does
 protected override void PickUp(Ant ant)
 {
     //not used by queen
 }
Esempio n. 52
0
	private void DeclareAntIntention (Ant ant, Command command)
	{
		Vector3 intendedPos = ant.positionAfterCommand (command);
		Debug.Log (ant + " intends to " + command + "\nintendedPos is " + intendedPos);
		if (command == Command.BACKWARD ||
			command == Command.FORWARD ||
			command == Command.PUSH) {
			bool valid = positionPossibleNextStep (ant, intendedPos);
//			Debug.Log ("valid = " + valid);

			if (!valid) {
				command = Command.WAIT;
			}
		}

	
		switch (command) {
		case Command.FORWARD:
			DeclareVoxelIntention (ant, ant, intendedPos, ant.MoveForward, true, commandPriority [command], false);
			break;
		case Command.BACKWARD:
			DeclareVoxelIntention (ant, ant, intendedPos, ant.MoveBackward, true, commandPriority [command], false);
			break;
		case Command.TURN_L:
			DeclareVoxelIntention (ant, ant, intendedPos, ant.TurnLeft, false, commandPriority [command], false);
			break;
		case Command.TURN_R:
			DeclareVoxelIntention (ant, ant, intendedPos, ant.TurnRight, false, commandPriority [command], false);
			break;
		case Command.PUSH:
//			Debug.Log ("Declare Push");
			if (intendedNextPositions.ContainsKey (intendedPos)) {
				DynamicVoxel pushPosVox;
				intendedNextPositions.TryGetValue (intendedPos, out pushPosVox);
//				Debug.Log ("pushPosVox " + ((pushPosVox == null) ? "null" : pushPosVox.name));
				//if this ant is pushing, and the voxel ahead is pushable, and it currently intends to stay put
				if (command == Command.PUSH && pushPosVox.isPushable && pushPosVox.position == pushPosVox.GetIntendedPosition ()) {
//					Debug.Log ("pushable and staying put");

					DeclareVoxelIntention (pushPosVox, ant, pushPosVox.position + ant.forwardDirection, pushPosVox.MoveDirection (ant.forwardDirection), true, commandPriority [command], false);
					DeclareVoxelIntention (ant, ant, intendedPos, ant.Push, true, commandPriority [command], false);
				} else {
					DeclareVoxelIntention (ant, ant, ant.position, ant.Wait, false, commandPriority [Command.WAIT], false);
				}
			}
			break;
		case Command.FIRE:
//			Debug.Log ("Declare Fire");
			DeclareVoxelIntention (ant, ant, intendedPos, ant.Fire, false, commandPriority [Command.FIRE], false);
			DynamicVoxel firePosVox;
			intendedNextPositions.TryGetValue (ant.position + ant.forwardDirection, out firePosVox);
//			Debug.Log("Fire pos " + ant.position + ant.forwardDirection + " firePosBox = " + ((firePosVox == null)? "null" : firePosVox.name));
			if (firePosVox != null && firePosVox.isBurnable && firePosVox.GetIntendedPosition () == firePosVox.position) {
//				Debug.Log("Will burn " + firePosVox);
				intendedNextPositions.Remove (firePosVox.position);
				DeclareVoxelIntention (firePosVox, ant, Vector3.one * -1, firePosVox.Burn, false, commandPriority [Command.FIRE], false);
			}
			break;
		case Command.BUILD:
//			Debug.Log ("Declare Build");
			DynamicVoxel buildPosVox;
			intendedNextPositions.TryGetValue (ant.position + ant.forwardDirection, out buildPosVox);
			if (buildPosVox == null) {
				DeclareVoxelIntention (ant, ant, ant.position, ant.Build, false, commandPriority [Command.BUILD], false);
				Crate buildCrate = ant.GetBuildCrate ();
				DeclareVoxelIntention (buildCrate, ant, ant.position + ant.forwardDirection, buildCrate.Assemble, false, commandPriority [Command.BUILD], false);
			} else {
//				Debug.Log ("Build Pos occupied by " + buildPosVox);
				DeclareVoxelIntention (ant, ant, intendedPos, ant.Wait, false, commandPriority [Command.WAIT], false);
			}
			break;
		default:
			DeclareVoxelIntention (ant, ant, ant.positionAfterCommand (Command.WAIT), ant.Wait, false, commandPriority [Command.WAIT], false);
			break;
		
		}
		
	}
Esempio n. 53
0
 public void IssueOrder(Ant ant, Direction direction)
 {
     // output: 'o 1 2 n' or move ant at location 1,2 north
     Console.WriteLine("o " + ant.row + " " + ant.col + " " + this.CDIRECTIONS[(int)direction]);
     Console.Out.Flush();
 }
Esempio n. 54
0
        protected override void Feed(Ant ant, int amount)
        {
            /**
             *
             * The ant takes food from the closest food source, and feeds a specified ant in its current location
             */
            if (File.Exists(LocationProperty + @"\FoodStash_" + ColonyIDProperty.ToString("D2")))
            {
                int foodAmount = 0;

                using (StreamReader sr = new StreamReader(LocationProperty + @"\FoodStash_" + ColonyIDProperty.ToString("D2")))
                {
                    String line = sr.ReadToEnd();

                    int.TryParse(line, out foodAmount);

                    if (foodAmount > amount)
                    {
                        foodAmount -= amount;
                        this.CarryAmountProperty += amount;
                    }
                    else
                    {
                        this.CarryAmountProperty += foodAmount;
                        foodAmount = 0;
                    }
                    sr.Close();

                }
                File.WriteAllText(LocationProperty + @"\FoodStash_" + ColonyIDProperty.ToString("D2"), String.Empty);
                using (StreamWriter sw = File.CreateText(LocationProperty + @"\FoodStash_" + ColonyIDProperty.ToString("D2")))
                {
                    sw.WriteLine(foodAmount);
                    sw.Close();
                }

                if (foodAmount <= 0)
                {
                    File.Delete(LocationProperty + @"\FoodStash_" + ColonyIDProperty.ToString("D2"));
                }

                ant.HungerProperty += this.CarryAmountProperty;
                this.CarryingProperty = 0;
            }
        }
 public MoveDirection(Ant ant, Direction direction)
     : base(ant, null)
 {
     this._direction = direction;
 }
Esempio n. 56
0
 //the ant picks up an object. Picking up an object means that the object moves when this ant does
 protected override void PickUp(Ant ant)
 {
     string strcarryType = ant.TypeProperty.ToString();
     CarriedAntProperty = ant;
     CarriedObjectFullPathProperty = ant.FullPathProperty;
     CarriedObjectLocationProperty = ant.LocationProperty;
     CarryingProperty = (Carrying) Enum.Parse(typeof (Carrying), strcarryType);
     ant.BeingCarriedProperty = true;
 }
Esempio n. 57
0
	public void RegisterAnt(Ant ant){
		if(!allAnts.Contains(ant))
			allAnts.Add(ant);
	}
Esempio n. 58
0
 public override void SpotsEnemy(Ant ant) { Spotted(this, new ItemEventArgs(Items.EnemyAnt.Track(ant))); }
 public EnrolledDestinationKey(Ant ant, Direction direction)
 {
     this.Ant = ant;
     this.Direction = direction;
 }
        public void TwoAntsCannotMoveIntoSameTile()
        {
            var mock = new MockFactory();
            var outputAdapterMock = mock.CreateMock<IGameOutputAdapter>();

            using (mock.Ordered)
            {
                outputAdapterMock.Expects.One
                    .Method(adapter => adapter.MoveAnt(0, 0, 0))
                    .WithAnyArguments();

                outputAdapterMock.Expects.One.MethodWith(adapter => adapter.NotifyEndOfTurn());
            }

            var trackerManager = new OwnAntTrackingManager(outputAdapterMock.MockObject);

            MapTile origin1 = GameContext.Map.At(3, 4);
            MapTile destination = origin1.North;
            MapTile origin2 = destination.North;
            var ant1 = new Ant(origin1);
            var ant2 = new Ant(origin2);

            origin1.CurrentAnt = ant1;
            origin2.CurrentAnt = ant2;

            trackerManager.HasProcessedAllInputMoves();
            trackerManager.EnrollToMove(ant1, destination);
            trackerManager.EnrollToMove(ant2, destination);
            trackerManager.FinalizeAllMoves();

            trackerManager.AntHasMovedTo(destination.Row, destination.Column);

            mock.VerifyAllExpectationsHaveBeenMet();
        }