コード例 #1
0
    private static int SortbyFitness(GameObject o1, GameObject o2)
    {
        //attach to main camera
        OrgClass o1fit = (OrgClass)o1.GetComponent("OrgClass");
        OrgClass o2fit = (OrgClass)o2.GetComponent("OrgClass");

        return(o1fit.fitness.CompareTo(o2fit.fitness));
    }
コード例 #2
0
    void runTourn()
    {
        //grab 3-5 orgs for tournament
        //rank reproduce orgs
        int tournsize;

        if (cubes.Count > 5)
        {
            tournsize = 5;
        }
        else
        {
            tournsize = cubes.Count;
        }
        tournament = new List <GameObject>();
        while (tournament.Count < tournsize)
        {
            GameObject neworg = cubes[Random.Range(0, cubes.Count)];
            if (neworg == null)
            {
                cubes.Remove(neworg);
                //Debug.Log("killed a null cube");
                neworg = cubes[Random.Range(0, cubes.Count - 1)];
            }
            else
            {
                if (!tournament.Contains(neworg))
                {
                    tournament.Add(neworg);
                }
            }
        }
        //order the tournament by fitness
        //Debug.Log("tourn" + tournament.Count + "cubes" + cubes.Count);
        tournament.Sort(SortbyFitness);

        if (tournament.Count > 1)
        {
            float total_fit = 0.0f;
            for (int i = 0; i < tournament.Count; i++)
            {
                OrgClass org = (OrgClass)tournament[i].GetComponent("OrgClass");
                total_fit += org.fitness;
            }
            float repro_prob = Random.Range(0.0f, 1.0f);
            int   winner_i   = -1;
            float fit_prob   = 0.0f;
            while (fit_prob < repro_prob)
            {
                winner_i += 1;
                OrgClass org = (OrgClass)tournament[winner_i].GetComponent("OrgClass");
                fit_prob += org.fitness / total_fit;
            }
            GameObject winner    = tournament[4];
            GameObject offspring = GenerateOffspring(winner);
            //winner.renderer.material.color = Color.red;
            cubes.Add(offspring);
            //Debug.Log("new offspring through tournament");
            Destroy(tournament[0].gameObject);
            //Debug.Log("killed org in tournament");
            cubes.Remove(tournament[0]);
            tournament.Clear();
        }
        else if (tournament.Count == 1)
        {
            GameObject winner    = tournament[(tournament.Count - 1)];
            GameObject offspring = GenerateOffspring(winner);
            //Debug.Log ("tournament size of 1");
            cubes.Add(offspring);
            cubes.Remove(winner);
        }
    }