Exemplo n.º 1
0
        public override string ToString()
        {
            string result = "|";

            Genes.ForEach(x => result += x.ToString() + "|");
            return(result);
        }
Exemplo n.º 2
0
 public override IGenotype ShallowCopy()
 {
     return(new CollectiveGenotype <T>(Genes.Length)
     {
         Genes = Genes.Clone() as byte[]
     });
 }
Exemplo n.º 3
0
 protected virtual void setGenes(Genes newGenes)
 {
     genes          = newGenes;
     material.color = (genes.isMale) ? maleColour : femaleColour;
     moveSpeed      = genes.speed;
     adultSize      = genes.size;
 }
 public BitChromosome(int length, Genes.BitGeneFactory bitGeneFactory)
 {
     this.length = length;
     this.bits = new Genes.BitGene[this.length];
     for (int i = 0; i < this.length; ++i)
         this.bits[i] = (Genes.BitGene)bitGeneFactory.GetNewGene();
 }
Exemplo n.º 5
0
    void Awake()
    {
        Globals.Player = gameObject;

        genes = new Genes();

        genes.isPlant = false;
        genes.size    = 1.0f;

        genes.swCircle   = 0;
        genes.swSquare   = 0;
        genes.swStar     = 0.5f;
        genes.swRose     = 0;
        genes.swRose2    = 0;
        genes.swCardioid = 0.5f;

        genes.playerFollowStrength    = 0;
        genes.bubbleInterval          = 1e9f;
        genes.playerHealthRestoreBase = 0;

        genes.species = 0;

        //genes.UpdateColor();
        genes.color = Color.blue;

        transform.FindChild("Blob").gameObject.GetComponent <BlobShape>().Genes = genes;
    }
 public override IGenotype ShallowCopy()
 {
     return(new Int32Genotype(sizeof(int))
     {
         Genes = Genes.Clone() as byte[],
     });
 }
Exemplo n.º 7
0
 private void Awake()
 {
     vitalFunctions = GetComponent <VitalFunctions>();
     genes          = GetComponent <Genes>();
     perceptor      = GetComponentInChildren <Perceptor>();
     communicator   = GetComponentInChildren <BehaviourCommunicator>();
 }
Exemplo n.º 8
0
 public override IGenotype ShallowCopy()
 {
     return(new UInt16Genotype(sizeof(ushort))
     {
         Genes = Genes.Clone() as byte[]
     });
 }
Exemplo n.º 9
0
    public void Register(Genes genes)
    {
        foreach (Entry x in species)
        {
            float d = genes.Difference(x.genes);
            if (d < cSpeciesOffset)
            {
                // found it!
                x.count++;
                x.maxCount++;
                genes.species   = x.id;
                genes.isFounder = false;
                return;
            }
        }
        // a new species, hurray!
        Entry y = new Entry();

        y.id            = speciesId++;
        y.genes         = genes.Clone(); // can we have a clone plz?
        y.count         = 1;
        genes.species   = y.id;
        genes.isFounder = true;
        species.Add(y);
    }
Exemplo n.º 10
0
    public Genes CrossGenes(Genes other, Genes out_)
    {
        //crosses all genes on object and puts result into out_
        List <Gene> newGenes = new List <Gene>();

        foreach (Gene gene in genes)
        {
            try
            {
                Gene matching = other.GetGene(gene.name);
                newGenes.Add(gene.CrossGene(matching, gene.name));
            }
            catch (ArgumentException e)
            {
                print(e);
                Debug.LogWarning(String.Format("'{0}' Could not find a matching gene for '{1}' in '{2}', skipping...", name, gene.name, other.gameObject.name), gameObject);
            }
        }

        out_.genes.Clear();
        foreach (Gene gene in newGenes)
        {
            out_.SetGene(gene);
        }

        return(out_);
    }
Exemplo n.º 11
0
    public Genes Clone()
    {
        Genes g = new Genes();

        g.isPlant                  = this.isPlant;
        g.size                     = this.size;
        g.swCircle                 = this.swCircle;
        g.swSquare                 = this.swSquare;
        g.swStar                   = this.swStar;
        g.swStarCount              = this.swStarCount;
        g.swStarPower              = this.swStarPower;
        g.swStarRadiusMin          = this.swStarRadiusMin;
        g.swRose                   = this.swRose;
        g.swRosePetals             = this.swRosePetals;
        g.swRose2                  = this.swRose2;
        g.swRoseAbsPetals          = this.swRoseAbsPetals;
        g.swCardioid               = this.swCardioid;
        g.playerFollowStrength     = this.playerFollowStrength;
        g.bubbleInterval           = this.bubbleInterval;
        g.playerHealthRestoreBase  = this.playerHealthRestoreBase;
        g.reproductionIntervalBase = this.reproductionIntervalBase;
        g.color                    = this.color;
        g.species                  = this.species;
        g.isFounder                = this.isFounder;
        return(g);
    }
Exemplo n.º 12
0
    public float Difference(Genes other)
    {
        if (isPlant != other.isPlant)
        {
            return(1.0f);
        }
        float d =
            D(size, other.size, 1.0f)
            + D(swCircle, other.swCircle, 1.0f)
            + D(swSquare, other.swSquare, 1.0f)
            + D(swStar, other.swStar, 1.0f)
            + D(swStarCount, other.swStarCount, 1.0f)
            + D(swStarPower, other.swStarPower, 1.0f)
            + D(swStarRadiusMin, other.swStarRadiusMin, 1.0f)
            + D(swRose, other.swRose, 1.0f)
            + D(swRosePetals, other.swRosePetals, 1.0f)
            + D(swRose2, other.swRose2, 1.0f)
            + D(swRoseAbsPetals, other.swRoseAbsPetals, 1.0f)
            + D(swCardioid, other.swCardioid, 1.0f)
            + D(playerFollowStrength, other.playerFollowStrength, 3.0f)
            + D(bubbleInterval, other.bubbleInterval, 3.0f)
            + D(playerHealthRestoreBase, other.playerHealthRestoreBase, 3.0f);

        return(Mathf.Sqrt(d / 10.0f));
    }
Exemplo n.º 13
0
    public GameObject SpawnFromPool(string tag, Vector3 pos, Genes father, Genes mother)
    {
        if (!poolDict.ContainsKey(tag))
        {
            Debug.LogWarning("Pool doesnt have this tag");
            return(null);
        }
        var obj = poolDict[tag].Dequeue();

        obj.SetActive(true);
        var obj_agent  = obj.GetComponent <Agent>();
        var obj_life   = obj.GetComponent <LifeComponent>();
        var obj_vision = obj.GetComponent <VisionComponent>();

        obj_agent.ResetAgent(true, father, mother);
        obj_life.ResetLifeStatus();
        obj_vision.ResetVision();
        obj.transform.position = pos;

        if (tag == "rabbit")
        {
            World.instance.actualRabbitAmount++;
        }
        if (tag == "wolf")
        {
            World.instance.actualWolfAmount++;
        }

        World.instance.UpdateUI();
        return(obj);
    }
Exemplo n.º 14
0
    public override void Init(Coord coord)
    {
        base.Init(coord);
        moveFromCoord = coord;
        genes         = Genes.RandomGenes(1);

        material.color = (genes.isMale) ? maleColour : femaleColour;

        switch (Specimen)
        {
        case Specimen.Undefined:
            mySleepBehaviour = SleepBehaviour.None;
            break;

        case Specimen.Plant:
            mySleepBehaviour = SleepBehaviour.None;
            break;

        case Specimen.Rabbit:
            mySleepBehaviour = SleepBehaviour.Crepuscular;
            break;

        case Specimen.Fox:
            mySleepBehaviour = SleepBehaviour.Nocturnal;
            break;

        default:
            Debug.LogWarning("Specimen is undefined");
            break;
        }

        ChooseNextAction();
    }
Exemplo n.º 15
0
        protected override void OnEnd()
        {
            GameObject target = this.GetComponent <Species>().targetObject;

            if (target != null && target.GetComponent <Mate>() != null)
            {
                Mate m = target.GetComponent <Mate>();
                if (m.GetComponent <Animator>().GetInteger(mateTimeProperty) > 0)
                {
                    //Mate not suitable.
                    this.GetComponent <Animator>().SetInteger(mateTimeProperty, Random.Range(1000, 2500));
                }
                else
                {
                    if (this.gameObject.GetInstanceID() > target.GetInstanceID())                     //I WILL BEAR THIS CHILD
                    {
                        GameObject child = Instantiate(this.gameObject);
                        child.transform.position = this.transform.position;
                        child.transform.SetParent(this.transform.parent);

                        Genes mg = this.GetComponent <Genes>();
                        Genes og = target.GetComponent <Genes>();

                        Genes cg = child.GetComponent <Genes>();

                        mg.MutateTo(og, cg);
                    }

                    this.GetComponent <Species>().targetObject = null;
                    this.GetComponent <Animator>().SetInteger(mateTimeProperty, Random.Range(1000, 5000));
                    this.GetComponent <Animator>().SetBool(mateFoundProperty, false);
                }
            }
        }
Exemplo n.º 16
0
 public ByteChromosome(int length, Genes.ByteGeneFactory byteFactory)
 {
     this.length = length;
     this.bytes = new Genes.ByteGene[this.length];
     for (int i = 0; i < this.length; ++i)
         this.bytes[i] = (Genes.ByteGene)byteFactory.GetNewGene();
 }
Exemplo n.º 17
0
 // Start is called before the first frame update
 void Start()
 {
     if (readGenesOnStart)
     {
         Genes genes = GetComponent <Genes>();
         if (genes != null)
         {
             try
             {
                 ColorUtility.TryParseHtmlString(genes.GetValue <string>("earlyColor"), out earlyColor);
                 ColorUtility.TryParseHtmlString(genes.GetValue <string>("optimumColor"), out optimumColor);
                 ColorUtility.TryParseHtmlString(genes.GetValue <string>("lateColor"), out lateColor);
                 healthToColorRatio = genes.GetValue <float>("healthToColorRatio");
             }
             catch (Exception e)
             {
                 print(e);
                 Debug.LogWarning("A gene could not be read, some variables may be using default values!", gameObject);
             }
         }
         else
         {
             Debug.LogWarning(String.Format("A gene script was not given to '{0}', using default values!", name), gameObject);
         }
     }
 }
Exemplo n.º 18
0
        //Give birth to two children
        public Genome(Genome Father, Genome Mother, bool XY, Int64 id)
        {
            ID         = id;
            this.Genes = new List <String>();
            //Get half the length
            int HalfLength = (int)Math.Round((Father.Genes.Count / 2D), 0);

            //If XY is true then spawn first three of father and last three of mother otherwise do the opposite
            if (XY)
            {
                //Father
                for (int i = 0; i < HalfLength; i++)
                {
                    Genes.Add(Father.Genes[i]);
                }
                //Mother
                for (int i = HalfLength; i < Mother.Genes.Count; i++)
                {
                    Genes.Add(Mother.Genes[i]);
                }
            }
            else
            {
                //Mother
                for (int i = 0; i < HalfLength; i++)
                {
                    Genes.Add(Mother.Genes[i]);
                }
                //Father
                for (int i = HalfLength; i < Father.Genes.Count; i++)
                {
                    Genes.Add(Father.Genes[i]);
                }
            }
        }
Exemplo n.º 19
0
 void Start()
 {
     estado  = GetComponent <Estado> ();
     caminar = GetComponent <Caminar> ();
     genes   = GetComponent <Genes> ();
     ObjetivoPuntoAleatorio = false;
 }
Exemplo n.º 20
0
    // Start is called before the first frame update
    void Start()
    {
        //reading gene script for variable values
        if (readGenesOnStart)
        {
            Genes genes = GetComponent <Genes>();
            if (genes != null)
            {
                try
                {
                    expectedLifetime = genes.GetValue <int>("expectedLifetime");
                    deathTimeSkew    = genes.GetValue <float>("deathTimeSkew");
                }
                catch (Exception e)
                {
                    print(e);
                    Debug.LogWarning("A gene could not be read, some variables may be using default values!", gameObject);
                }
            }
            else
            {
                Debug.LogWarning(String.Format("A gene script was not given to '{0}', using default values!", name), gameObject);
            }
            BalanceFloats(allDependencies, 0, maxEfficiency);
        }

        timeAliveLeft = expectedLifetime;
    }
Exemplo n.º 21
0
        /// <summary>
        /// Adds gene between two nodes.
        /// There cannot be two genes between same nodes.
        /// </summary>
        private void AddGene(Random rnd, ref int innovation, List <Gene> allGenes)
        {
            int latter;
            int first;

            do
            {
                first = rnd.Next(0, Nodes.Count);
            }while(Nodes[first].Type == NodeType.Output);
            Node input = Nodes[first];
            Node output;
            int  j = 0;

            do
            {
                latter = rnd.Next(0, Nodes.Count);
                output = Nodes[latter];
                ++j;
                if (j > 10 && input.Layer >= output.Layer)
                {
                    for (int i = 0; i < Nodes.Count; i++)
                    {
                        if (input.Layer < Nodes[i].Layer)
                        {
                            output = Nodes[i];
                        }
                    }
                }
            } // SHOULD NOT PICK THE SAME LAYER
            while (input.Layer >= output.Layer);

            Gene gene = null;

            foreach (var item in allGenes)
            {
                if (item.In.Number == input.Number && item.Out.Number == output.Number)
                {
                    gene      = item.ShallowCopy();
                    gene.In   = input;
                    gene.Type = GeneType.Enabled;
                    gene.Out  = output;
                    break;
                }
            }

            if (gene == null)
            {
                gene = new Gene(input, output, 0f, GeneType.Enabled, ++innovation);
                var g = gene.ShallowCopy();
                g.Type = GeneType.AddGene;
                allGenes.Add(g);
            }
            if (Genes.ContainsValue(gene))
            {
                return;
            }
            gene.Weight = gene.AssignRandomWeight(rnd);
            gene.In.OutgoingConnections.Add(gene);
            Genes.Add(gene.Innovation, gene);
        }
Exemplo n.º 22
0
    public void Render(GameObject objeto)
    {
        //Mostrar el nombre del individuo
        textoNombre.text = objeto.name;
        // Mostrar los genes del individuo
        Genes  genes   = objeto.GetComponent <Genes>();
        string genCode = "";

        foreach (int n in genes.getGenes())
        {
            genCode += n.ToString();
        }
        textoGenes.text = "Genes: " + genCode;

        textoFuerza.text    = "Fuerza: " + genes.fuerza;
        textoVelocidad.text = "Velocidad: " + genes.velocidad;
        textoTve.text       = "Tiempo vida\nestmado: " + genes.getLongevidad() + " segundos";

        // Mostrar color del individuo
        imagenColor.color = genes.col;

        //Asignar genes al sample 3D
        sampleGenes.SetGenes(genes.getGenes());

        //Mostrar informacion del estado del individuo
        Estado estado = objeto.GetComponent <Estado>();

        textoHambre.text  = "Hambre: " + estado.hambre;
        textoEnergia.text = "Energía: " + estado.energia;
        textoSalud.text   = "Salud: " + estado.salud;

        sampleGenes.decodeGenes();          // se pone al final para evitar errores con el decofigicador de genes
    }
Exemplo n.º 23
0
    public void InheritGenes(Genes mother, Genes father)
    {
        randomGenes(speed, mother.speed, father.speed);

        randomGenes(visonDistance, mother.visonDistance, father.visonDistance);

        randomGenes(visonDistance, mother.visonDistance, father.visonDistance);

        randomGenes(strength, mother.strength, father.strength);

        randomGenesLow(criticalPercent, mother.criticalPercent, father.criticalPercent);

        randomGenesInt(offSpringAmount, mother.offSpringAmount, father.offSpringAmount);

        if (strength <= 0)
        {
            strength = 1;
        }
        if (speed <= 0)
        {
            speed = 1;
        }
        if (visonDistance <= 2)
        {
            visonDistance = 2;
        }
        if (reperductiveUrge <= 0)
        {
            reperductiveUrge = 0.01f;
        }
        if (offSpringAmount <= 0)
        {
            offSpringAmount = 1;
        }
    }
Exemplo n.º 24
0
    void Atacar(Pelear yo, Collider otro)
    {
        Genes genOtro = otro.GetComponent <Genes> ();

        if (genes == null || genOtro == null)
        {
            return;
        }

        int sim = Utils.similitudGenetica(yo.genes, genOtro);

        if (sim < 70)
        {
            //Atacar!!!
            //print("soy " + yo.name + " y estoy atacando a " + otro.name);
            Estado estadoEnemigo = otro.GetComponent <Estado> ();
            Debug.DrawLine(yo.transform.position + Vector3.up, otro.transform.position + Vector3.up, genes.col, 1f);
            // decrementar la salud enemiga
            estadoEnemigo.salud -= ((20 / 8) * genes.fuerza);         // la fuerza maxima es 8, por lo tanto se divide 20(maximo de ataque) entre 8 y se multiplica por su propia fuerza

            targetEnemigo = estadoEnemigo.gameObject;
            laser.SetPosition(0, transform.position);
            laser.SetPosition(1, otro.transform.position);
            laser.enabled = true;

            yo.atacar = false;
            yo.StartCoroutine(yo.reAtacar());
        }
    }
Exemplo n.º 25
0
    // Start is called before the first frame update

    void Start()
    {
        //reading gene script for variable values
        if (readGenesOnStart)
        {
            Genes genes = GetComponent <Genes>();
            if (genes != null)
            {
                try
                {
                    dependencyAmount  = genes.GetValue <float>("dependencyAmount");
                    minValue          = genes.GetValue <int>("minValue");
                    maxValue          = genes.GetValue <int>("maxValue");
                    optimumPercentage = genes.GetValue <float>("optimumPercentage");
                }
                catch (Exception e)
                {
                    print(e.ToString());
                    Debug.LogWarning("A gene could not be read, some variables may be using default values!", gameObject);
                }
            }
            else
            {
                Debug.LogWarning(String.Format("A gene script was not given to '{0}', using default values!", name), gameObject);
            }
        }

        depAmountChanged = false;
        prevDepAmount    = dependencyAmount;
    }
Exemplo n.º 26
0
    private void ObtenerEstadisticas()
    {
        //Obtener todos los individuos;
        individuos = GameObject.FindGameObjectsWithTag("Individuo");

        Dictionary <string, int> razas = new Dictionary <string, int>();

        foreach (GameObject g in individuos)
        {
            //Obtener codigo de familia
            Genes  genes     = g.GetComponent <Genes>();
            string codigoFam = genes.familia;

            if (!razas.ContainsKey(codigoFam))
            {
                razas.Add(codigoFam, 1);
            }
            else
            {
                razas [codigoFam]++;
            }

            CalcularMejorAdaptado(g);
        }
        RazasVivas      = razas.Count;
        IndividuosVivos = individuos.Length;

        // imprimir estadisticas
        text.text  = "";
        text.text += ("Razas vivas: " + RazasVivas) + "\n";
        text.text += ("Individuos nacidos: " + individuosNacidos) + "\n";
        text.text += ("Individuos Muertos: " + individuosMuertos) + "\n";
        text.text += ("Mutaciones Generadas: " + mutaciones);
    }
Exemplo n.º 27
0
 public override IGenotype ShallowCopy()
 {
     return(new UInt64Genotype(sizeof(ulong))
     {
         Genes = Genes.Clone() as byte[],
     });
 }
Exemplo n.º 28
0
        public List <Gene <T> > GetElites(int elitismOverride = 0)
        {
            List <Gene <T> > elites = new List <Gene <T> >();

            if (Genes.Count < 1)
            {
                return(elites);
            }

            if (elitismOverride != 0)
            {
                elites.Capacity = elitismOverride;
            }
            else
            {
                elites.Capacity = settings.elitism;
            }

            FitnessScaling <T> .ScaleFitness(Genes, settings.scalingType);

            Genes.Sort();

            Elite = new Gene <T>(Genes[0]);
            for (int i = 0; i < elites.Capacity && i < Genes.Count; i++)
            {
                elites.Add(new Gene <T>(Genes[i]));
            }

            return(elites);
        }
Exemplo n.º 29
0
 private double GetDecodedValue()
 {
     return(Genes
            .Reverse()
            .Select((x, i) => (x ? Math.Pow(2, i) : 0))
            .Sum());
 }
Exemplo n.º 30
0
    void debug_cross_over()
    {
        Genes[] second_gen = new Genes[evolution_settings.maximumNumberOfBrushStrokes * evolution_settings.populationPoolNumber];
        compute_resources.second_gen_population_pool_buffer.GetData(second_gen);

        population_member_to_string(second_gen);
    }
Exemplo n.º 31
0
        public IGenome Copy()
        {
            Dictionary <Guid, INode> nodeReplacements = new Dictionary <Guid, INode>();
            List <IGene>             genes            = Genes.Select(g => g.Copy()).ToList();

            genes.ToList().ForEach(g =>
            {
                if (!nodeReplacements.Any(nr => nr.Key == g.NodeIn.Id))
                {
                    nodeReplacements.Add(g.NodeIn.Id, g.NodeIn.Copy());
                }

                if (!nodeReplacements.Any(nr => nr.Key == g.NodeOut.Id))
                {
                    nodeReplacements.Add(g.NodeOut.Id, g.NodeOut.Copy());
                }

                g.NodeIn  = nodeReplacements[g.NodeIn.Id];
                g.NodeOut = nodeReplacements[g.NodeOut.Id];
            });

            return(new Genome()
            {
                Id = Id,
                Genes = genes,
                Nodes = nodeReplacements.Select(nr => nr.Value).ToList()
            });
        }
Exemplo n.º 32
0
        // 새로운 노드를 추가함.
        // 기존의 연결 중 무작위로 선택해서 기존의 연결은 비활성화시키고,
        // 그 사이에 새로운 노드를 추가함.
        // in ==(w₁)==> out 이었다면
        // in =(w₂)=> new =(w₃)=> out과 같이 변이가 일어남. (w₁w₂w₃는 연결의 가중치)
        // 이때 구조적 혁신이 기존 성능에 주는 영향을 최소화하기 위해서 w₂= w₁, w₃= 1로 설정함.
        public void MutateNode(Random r)
        {
            if (Genes.Count == 0)
            {
                return;
            }
            Gene gene = RandomGenes(r);

            if (gene == null || !gene.Enable)
            {
                return;
            }

            gene.Enable = false;

            Gene gene1 = gene.Clone();

            gene1.Out        = NodeIndex;
            gene1.Weight     = 1.0;
            gene1.Innovation = Pool.NewInnovation();
            gene1.Enable     = true;
            Genes.Add(gene1);

            Gene gene2 = gene.Clone();

            gene2.In         = NodeIndex;
            gene2.Innovation = Pool.NewInnovation();
            gene2.Enable     = true;
            Genes.Add(gene2);


            ++NodeIndex;
        }
 public DoubleChromosome(int length, Genes.DoubleGeneFactory doubleGeneFactory)
 {
     this.length = length;
     this.doubleValues = new Genes.DoubleGene[this.length];
     for (int i = 0; i < this.length; ++i)
         this.doubleValues[i] = (Genes.DoubleGene)doubleGeneFactory.GetNewGene();
 }