// Use this for initialization
    void Start()
    {
        Instance = this;
        for (int i = 0; i < PopulationSize; i++)
        {
            GameObject curRocket = (GameObject)GameObject.Instantiate(RocketPrefab, new Vector3(0, 0, -1000), Quaternion.identity);

            RocketGameObjects.Add(curRocket);
            DNA curDNA = (DNA)gameObject.AddComponent <DNA>();
            Population.Add(curDNA);
            curDNA.RandomSeed(DNASize);

            curRocket.GetComponent <Rocket>().cDNA = curDNA;
            curDNA.MyRocket = curRocket;
        }

        foreach (GameObject curRocketgo in RocketGameObjects)
        {
            foreach (GameObject otherRocketGO in RocketGameObjects)
            {
                if (curRocketgo != otherRocketGO)
                {
                    Physics2D.IgnoreCollision(curRocketgo.GetComponent <Collider2D>(), otherRocketGO.GetComponent <Collider2D>());
                }
            }
        }

        foreach (GameObject RocketGO in RocketGameObjects)
        {
            RocketGO.transform.position = new Vector3(0, 0, 0);
        }
    }
Beispiel #2
0
    public Model(int childCount, int iterationCount, float mutationRate)
    {
        _mutationRate   = mutationRate;
        _childCount     = childCount;
        _iterationCount = iterationCount;

        _rulesets = new RuleSet[_childCount];
        _meshes   = new Mesh[_childCount];

        //InitialiseDB.Initialise(); //can be used to populate a new set of initial L systems in the DB (specified in LSystemDB.cs)
        var ldb         = new LSystemDB();
        var systemsJSON = ldb.ReadFromFile();

        _sampleRules  = new string[_childCount][];
        _sampleAxioms = new string[_childCount][];

        _encode = new Encoder("Ff-+|!£\"GHI^&$");

        //get the L systems from database and assign them to as meshes to GOs
        for (int i = 0; i < _childCount; i++)
        {
            RuleSet tempRS = new RuleSet(systemsJSON[(i % systemsJSON.Count).ToString()]);
            _rulesets[i] = tempRS;
            _meshes[i]   = MeshFromRuleset(i);
            EncodeSamples(i);
        }

        //one GA for the rules and axioms so they don't get jumbled up
        _gaRules  = CreateGA(_sampleRules);
        _gaAxioms = CreateGA(_sampleAxioms);
    }
Beispiel #3
0
 public void Init()
 {
     // Initialize the genes
     // 0 = Forward
     // 1 = Angled Turn
     GA       = new GeneticAlgo(geneLength, 360);
     startPos = this.transform.position;
 }
 public void setup(CustomTerrain ct, GeneticAlgo ga)
 {
     terrain      = ct;
     genetic_algo = ga;
     updateSetup();
     zone = new VegetationConstraint[livesIn.Length];
     for (int i = 0; i < livesIn.Length; i++)
     {
         zone[i] = terrain.getVegetationFromZone(livesIn[i]);//Added
     }
 }
Beispiel #5
0
 public void Init()
 {
     // Initialize our genes
     // 0 = Forward
     // 1 = Left
     // 2 = Right
     GA        = new GeneticAlgo(geneLength, 3);
     timeAlive = 0.0f;
     alive     = true;
     ethan     = Instantiate(ethanPrefab, this.transform.position, this.transform.rotation);
     ethan.GetComponent <UnityStandardAssets.Characters.ThirdPerson.AICharacterControl> ().target = this.transform;
 }
Beispiel #6
0
        private void StartButton_Click(object sender, RoutedEventArgs e)
        {
            generation       = 1;
            generationString = "Generaciones : \n";
            if (!String.IsNullOrEmpty(PopulationTextBox.Text))
            {
                this.population = int.Parse(PopulationTextBox.Text);

                geneticAlgo = new GeneticAlgo(this.population);

                this.ejecutarAlgoritmo();
            }
        }
Beispiel #7
0
 public void Init()
 {
     // Init GeneticAlgo
     // 0 = Forward
     // 1 = Back
     // 2 = Left
     // 3 = Right
     // 4 = Jump
     // 5 = Crouch
     GA          = new GeneticAlgo(geneLength, 6);
     m_Character = GetComponent <ThirdPersonCharacter> ();
     startingPos = this.transform.position;
     timeAlive   = 0;
     alive       = true;
 }
Beispiel #8
0
    // Start is called before the first frame update
    void Awake()
    {
        gameController = FindObjectOfType <GameController>();
        geneticAlgo    = FindObjectOfType <GeneticAlgo>();
        bird           = GetComponent <Bird>();

        weights1 = new float[inputLayerSize, hidenLayerSize];
        weights2 = new float[hidenLayerSize];
        bias1    = new float[hidenLayerSize];

        //for observation in editor
        hidenNode = new float[hidenLayerSize];

        SetRandomParameters();
        //SetTestParameters();
    }
 public void Combine(GeneticAlgo GA1, GeneticAlgo GA2)
 {
     for (int i = 0; i < geneLength; i++)
     {
         if (i < geneLength / 2)
         {
             int c = GA1.genes [i];
             genes [i] = c;
         }
         else
         {
             int c = GA2.genes [i];
             genes [i] = c;
         }
     }
 }
Beispiel #10
0
        private void btnStart_Click(object sender, EventArgs e)
        {
            GeneticAlgo geneticAlgo = new GeneticAlgo();
            List<Cromosoma> initPopulation = obtenerPoblacionInicial(tamanioPoblacion);
            geneticAlgo.generarRistras(ref initPopulation, generaciones, probabilidadDeCruza, probabilidadDeMutacion);

            dgResults.Rows.Clear();
            for (int i = 0; i < initPopulation.Count - 1; i++)
            {
                String sol = "| ";
                for (int j = 0; j < 8; j++)
                {
                    sol = sol + initPopulation[i].genes[j] + " | ";
                }
                dgResults.Rows.Add(new Object[] { sol, initPopulation[i].conveniencia });

            }
            board1.Genes = initPopulation[0].genes;
        }
Beispiel #11
0
        private List<Cromosoma> obtenerPoblacionInicial(int population)
        {
            List<Cromosoma> initPop = new List<Cromosoma>();
            GeneticAlgo RandomGen = new GeneticAlgo();
            for (int i = 0; i < population; i++)
            {
                List<int> genes = new List<int>(new int[] {0, 1, 2, 3, 4, 5, 6, 7});
                Cromosoma chromosome = new Cromosoma();
                chromosome.genes = new int[8];
                for (int j = 0; j < 8; j++)
                {
                    int geneIndex = (int)(RandomGen.obtenerAleatorio(0,genes.Count-1)+0.5);
                    chromosome.genes[j] = genes[geneIndex];
                    genes.RemoveAt(geneIndex);
                }

                initPop.Add(chromosome);
            }
            return initPop;
        }
    public void StartTest()
    {
        MatchAlgo   matchAlgo   = new MatchAlgo();
        GeneticAlgo geneticAlgo = new GeneticAlgo();

        System.Random rand = new System.Random();
        List <WeightsForBoardEval> weights = new List <WeightsForBoardEval>();

        for (int i = 0; i < 50; i++)
        {
            WeightsForBoardEval w = new WeightsForBoardEval(rand);
            weights.Add(w);
            Console.WriteLine("pesInizRand = " + w);
        }

        SortedList <WeightScore, int> scoreMap = new SortedList <WeightScore, int>();

        //per ogni peso = giocatore, fa giocare 3 match come oca e 3 match come volpe al giocatore contro un giocatore casuale
        for (int i = 0; i < weights.Count; i++)
        {
            int score = 0;
            WeightsForBoardEval weight        = weights[i];
            AlphaBeta           playerAsFox   = new AlphaBeta(PawnType.Fox, 3, weight, false);
            AlphaBeta           playerAsGoose = new AlphaBeta(PawnType.Goose, 3, weight, false);
            score  = matchAlgo.MatchTwoAi(playerAsFox, null, 3, -1, -1).first;
            score += matchAlgo.MatchTwoAi(playerAsGoose, null, 3, -1, -1).first;
            WeightScore ws = new WeightScore(weight, score);
            scoreMap.Add(ws, score);
        }

        Console.WriteLine("aiTester prima di evoluzione");
        // evolve 50 volte la popolazione
        for (int i = 0; i < 50; i++)
        {
            Console.WriteLine("\n \n \n \n inizio evoluzione generazione " + i);
            scoreMap = geneticAlgo.Evolve(scoreMap, 0.3, 0.1, 0.01);
        }
        Console.WriteLine("best weights " + scoreMap.Keys[0]);
        Console.WriteLine("finito completamente aiTester ore: " + DateTime.Now.ToString("h:mm:ss tt"));
        Console.ReadKey();
    }
Beispiel #13
0
    public void CreateGA()
    {
        System.Random r = new System.Random(Time.frameCount);

        string selectType = "god mode";
        string mutateType = "randomChoice";
        string crossType  = "OnePt";

        Encoder    encoder    = new Encoder();
        string     target     = encoder.Encode(TextureNoise.CreateNoise(width, height, r));
        Fitness    fitness    = new Fitness(target);
        Population population = new Population(20, fitness._targetString)
        {
            _name = "images"
        };
        Selection selection = new Selection(selectType);
        CrossOver crossover = new CrossOver(crossType);
        Mutation  mutation  = new Mutation(mutateType);

        geneticAlgo = new GeneticAlgo(encoder, fitness, population, selection, crossover, mutation);
    }
Beispiel #14
0
    // Update is called once per frame
    void FixedUpdate()
    {
        if (transform.position.y > 1.5 | transform.position.y < -1.5)
        {
            alife = false;
        }

        if (alife)
        {
            GeneticAlgo ga = FindObjectOfType <GeneticAlgo>();
            if (ga != null & ga.regularisationWeight != 0 & nn)
            {
                //if (ga.regularisationWeight!=0 & nn)
                //{
                //    score += Time.deltaTime - nn.RegularisationTerm();
                //}
            }
            else
            {
                score += Time.deltaTime;
            }
        }
    }
Beispiel #15
0
    // Update is called once per frame
    void Update()
    {
        //Debug.Log(transform.forward);
        float[] values;
        float   fitness;
        string  id;

        KeyControl();

        duration -= Time.deltaTime;
        GameObject.FindGameObjectWithTag("text duration").GetComponent <Text>().text = "Elapsed Duration : " + duration.ToString() + "\n" +
                                                                                       "Camera Movement Status : " + isMoveCamera.ToString() + "\n" +
                                                                                       "Camera Follow Status : " + isFollowCamera.ToString() + "\n" +
                                                                                       "Press 'L' to hide camera information" + "\n" +
                                                                                       "Press 'I' to display camera information" + "\n";

        if (duration <= 0)
        {
            System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
            stopWatch.Start();

            GeneticAlgo GA = new GeneticAlgo(counterId);
            GA.Generations    = generations;
            GA.MutationRate   = mutationRate;
            GA.CrossoverRate  = crossoverRate;
            GA.FitnessFile    = @fitnessFile;
            GA.Elitism        = elitism;
            GA.PopulationSize = populationSize;
            GA.Compute();

            GA.GetBest(out values, out fitness, out id, out duration);

            isMoveCamera   = (Random.value > 0.5f) ? true : false;
            isFollowCamera = (Random.value > 0.5f) ? true : false;

            if (!isFollowCamera)
            {
                isMoveCamera = false;
            }

            while (fitness != 1.0f)
            {
                GA.Compute();
                GA.GetBest(out values, out fitness, out id, out duration);
            }

            hasilPosGenerated = new Vector3(values[0], values[1], values[2]);
            hasilRotGenerated = new Vector3(values[3], values[4], values[5]);

            initialId = id;

            stopWatch.Stop();
            System.TimeSpan ts = stopWatch.Elapsed;
            executionTime = System.String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                                                 ts.Hours, ts.Minutes, ts.Seconds,
                                                 ts.Milliseconds / 10);

            GameObject.FindGameObjectWithTag("text pose").GetComponent <Text>().text = "Id Pose : " + initialId + "\n"
                                                                                       + "Duration : " + duration + "\n"
                                                                                       + "Execution Time : " + executionTime + "\n"
                                                                                       + "Fitness : " + fitness.ToString();
            counterId = initialId;

            if (ts.Milliseconds >= 50)
            {
                GameObject.FindGameObjectWithTag("text pose").GetComponent <Text>().color = new Color(255, 0, 0);
            }
            else
            {
                GameObject.FindGameObjectWithTag("text pose").GetComponent <Text>().color = new Color(0, 253, 243);
            }

            smartCam.transform.rotation = Quaternion.Euler(hasilRotGenerated + transform.rotation.eulerAngles);
            smartCam.transform.position = transform.position + (transform.rotation * hasilPosGenerated);
            if (isFollowCamera)
            {
                smartCam.transform.parent = transform;
            }
            else
            {
                smartCam.transform.parent = null;
            }
            temp = Regex.Replace(counterId, @"[\d-]", string.Empty);
            if (temp == "MSF")
            {
                isZoom = Random.value > 0.5f ? true : false;
            }
        }

        if (isMoveCamera)
        {
            CameraMovementPose();
        }

        var screenPoint = Vector3.Distance(smartCam.transform.position, transform.position);

        if (screenPoint > CameraDistance)
        {
            if (!isFollowCamera)
            {
                if (duration > 1f)
                {
                    smartCam.transform.LookAt(transform);
                    duration = duration - Time.deltaTime * 1f;
                }
            }
        }
    }