Esempio n. 1
0
//    double crossoverRate = 0.9;


    public override List <BotBehavior> crossOver(List <BotBehavior> individuals, int populationGoalSize)
    {
        int numberOfCrossovers      = populationGoalSize;   //(int)Mathf.Floor(individuals.Count * (float)crossoverRate);
        List <BotBehavior> children = new List <BotBehavior> ();

        for (int i = numberOfCrossovers / 2; i > 0; i--)
        {
            int parentx = UnityEngine.Random.Range(0, individuals.Count);
            int parenty = UnityEngine.Random.Range(0, individuals.Count);

            BotBehavior p1 = BotBehavior.deepClone <BotBehavior>(individuals[parentx]);
            BotBehavior p2 = BotBehavior.deepClone <BotBehavior>(individuals[parenty]);

            Tuple <BehaviourNode, int> firstPoint = selectNodeOf(p1);
            Tuple <BehaviourNode, int> secPoint   = selectNodeOf(p2);

            //doing the crossover

            //preventing swapping of root nodes --> pointless and undefined
            if (firstPoint.First != null && secPoint.First != null)
            {
                BehaviourNode temp = firstPoint.First.getNextNodes()[firstPoint.Second];
                firstPoint.First.getNextNodes()[firstPoint.Second] = secPoint.First.getNextNodes()[secPoint.Second];
                secPoint.First.getNextNodes()[secPoint.Second]     = temp;
            }


            children.Add(p1);
            children.Add(p2);
        }

        return(children);
    }
Esempio n. 2
0
 public static void saveBotToFile(BotBehavior b, String filename)
 {
     using (Stream tw = File.Open(filename, FileMode.Create))
     {
         var formatter = new BinaryFormatter();
         formatter.Serialize(tw, b);
     }
 }
Esempio n. 3
0
    private Tuple <BehaviourNode, int> selectNodeOf(BotBehavior bot)
    {
        BehaviourNode parentNode = null;
        int           index      = 0;

        iterate(bot.getRoot(), 0, null, ref parentNode, ref index, 0);

        return(new Tuple <BehaviourNode, int>(parentNode, index));
    }
Esempio n. 4
0
        private void SpawnUser(IUser user, PlayerTeam team)
        {
            if (CheckUserStillActive(user))
            {
                IPlayer ply       = user.GetPlayer();
                IPlayer newPlayer = Game.CreatePlayer(spawnPos); // create a new blank player

                Game.CreateDialogue("Respawning " + ply.Name, ply);
                if (ply.IsBot)
                {
                    Game.CreateDialogue(ply.Name + " is a bot", ply);
                    var botBehavior = new BotBehavior(true, PredefinedAIType.BotD);
                    ply.SetBotBehavior(botBehavior);
                    newPlayer.SetBotBehavior(botBehavior);

                    rnd = new Random();
                    var i = rnd.Next(0, _Classes.Length - 1);

                    var o = Game.GetFirstObject(_Classes[i]) as IObjectActivateTrigger;
                    if (o == null)
                    {
                        Game.CreateDialogue(ply.Name + " not teleported because _Classes[" + i + "] is null.", ply);
                        return;
                    }

                    Game.CreateDialogue("Going to choose class for bot " + ply.Name, ply);
                    ClassChooser(new TriggerArgs(o, ply, false));
                    return;
                }

                if (team == PlayerTeam.Team1)
                {
                    newPlayer.SetTeam(PlayerTeam.Team1);
                    spawnPos = Game.GetSingleObjectByCustomId("Blue").GetWorldPosition();
                }
                if (team == PlayerTeam.Team2)
                {
                    newPlayer.SetTeam(PlayerTeam.Team2);
                    spawnPos = Game.GetSingleObjectByCustomId("Red").GetWorldPosition();
                }
                if (team.Equals(PlayerTeam.Team3))
                {
                    newPlayer.SetTeam(PlayerTeam.Team3);
                    spawnPos = Game.GetSingleObjectByCustomID("Middle").GetWorldPosition();
                }

                newPlayer.SetUser(user);                 // set user (this will make the user control the player instance)
                newPlayer.SetProfile(user.GetProfile()); // set user's profile
                newPlayer.SetWorldPosition(spawnPos);
            }
            else
            {
                CheckTeams(team);
            }
        }
Esempio n. 5
0
    public static BotBehavior loadBotFromFile(String filename)
    {
        BotBehavior bb = new BotBehavior();

        using (Stream tw = File.Open(filename, FileMode.Open))
        {
            var formatter = new BinaryFormatter();
            bb = (BotBehavior)formatter.Deserialize(tw);
        }
        return(bb);
    }
Esempio n. 6
0
    public override List <BotBehavior> select(List <KeyValuePair <int, BotBehavior> > evaluatedBehavior, float toKeep)
    {
        int parents                = (int)(evaluatedBehavior.Count * toKeep);
        int currentNumParents      = 0;
        List <BotBehavior> winners = new List <BotBehavior>();
        List <KeyValuePair <int, BotBehavior> > parentsCopy = new List <KeyValuePair <int, BotBehavior> >(evaluatedBehavior);

        if (evaluatedBehavior.Count < tournamentSize)
        {
            foreach (KeyValuePair <int, BotBehavior> pair in parentsCopy)
            {
                winners.Add(pair.Value);
            }
        }
        else
        {
            while (currentNumParents < parents)
            {
                int starting = UnityEngine.Random.Range(0, parentsCopy.Count - tournamentSize);
                //Debug.Log("starting pos: " + starting);
                BotBehavior max      = parentsCopy[starting].Value;
                int         maxValue = parentsCopy[starting].Key;

                int index = 0;
                for (int i = starting + 1; i < starting + tournamentSize; i++)
                {
                    // Debug.Log("value: " + evaluatedBehavior[i].Key);

                    if (maxValue < parentsCopy[i].Key)
                    {
                        maxValue = parentsCopy[i].Key;
                        max      = parentsCopy[i].Value;
                        index    = i;
                    }
                }
                // Debug.Log("maxv: " + maxValue);


                winners.Add(max);
                if (uniqueParents)
                {
                    parentsCopy.Remove(parentsCopy[index]);
                    Debug.Log("reduced parents pool: " + parentsCopy.Count);
                }
                currentNumParents++;
            }
        }

        return(winners);
    }
Esempio n. 7
0
        /// <summary>
        /// Spawns a player that has already spawned before
        /// </summary>
        /// <param name="user">The user</param>
        /// <param name="team">The team for this user</param>
        /// <param name="isBot">Whether the player to respawn is a bot or not</param>
        private void Respawn(IUser user, PlayerTeam team, bool isBot)
        {
            if (IsUserStillActive(user) && !user.IsSpectator)
            {
                var player = Game.CreatePlayer(_PlayerSpawnPosition);
                if (isBot)
                {
                    var botBehavior = new BotBehavior(true, PredefinedAIType.BotB);
                    player.SetBotBehavior(botBehavior);
                }

                player.SetProfile(user.GetProfile());
                if (team == PlayerTeam.Team1)
                {
                    player.SetTeam(PlayerTeam.Team1);
                    _PlayerSpawnPosition = Game.GetSingleObjectByCustomId(GetBlueRandomPosition()).GetWorldPosition();

                    if (winner == PlayerTeam.Team1)
                    {
                        _PlayerSpawnPosition = Game.GetSingleObjectByCustomID("PlayerPeach").GetWorldPosition();
                    }
                    SetPlayerToMarioTwo(player);
                }
                if (team == PlayerTeam.Team2)
                {
                    player.SetTeam(PlayerTeam.Team2);
                    _PlayerSpawnPosition = Game.GetSingleObjectByCustomId(GetRedRandomPosition()).GetWorldPosition();
                    if (winner == PlayerTeam.Team2)
                    {
                        _PlayerSpawnPosition = Game.GetSingleObjectByCustomID("PlayerPeach").GetWorldPosition();
                    }
                    SetPlayerToMarioOne(player);
                }
                if (team.Equals(PlayerTeam.Team3))
                {
                    player.SetTeam(PlayerTeam.Team3);
                    _PlayerSpawnPosition = Game.GetSingleObjectByCustomID(PLAYER_MIDDLE_SPAWN_BLOCK_ID).GetWorldPosition();
                }
                player.SetUser(user);
                player.SetWorldPosition(_PlayerSpawnPosition);
            }
            else
            {
                SubstractPlayerFromThisTeam(team);
            }
        }
    public GameObject GetNewBot(Vector3 botPosition, BotBehavior.BehaviorType bType)
    {
        GameObject newBot = botPooler.GetPooledObject();

        if (newBot != null)
        {
            newBot.transform.position = botPosition;
            BotBehavior newBotScript = newBot.GetComponent <BotBehavior>();
            newBotScript.behaviorType           = bType;
            newBotScript.gameControllerInstance = this.gameObject;
            newBotScript.Corrupt(false);
            newBotScript.bullet = null;
            newBotScript.ReStart();
            newBot.SetActive(true);
        }
        return(newBot);
    }
Esempio n. 9
0
    private void spawnIndividuals()
    {
        //Spawn new individuals with new behavior
        int numOfNewIndividuals = Mathf.Min(concurrentTestSize, behaviorsToEvaluate.Count);

        //Debug.Log ("Still " +  behaviorsToEvaluate.Count + " individuals left to test.");
        //Debug.Log ("Spawning " + numOfNewIndividuals + " new  individuals.");
        for (int i = 0; i < numOfNewIndividuals; i++)
        {
            //Debug.Log ("Spawning individual " + i);
            BotBehavior b = behaviorsToEvaluate.Dequeue();
            currentBehaviors.Add(b);
            GameObject go = Instantiate(individualPrefab);
            go.GetComponent <BotController> ().setBotBehavior(b);
            go.transform.position = new Vector3(0, 10 * i, 0);          //Set location of individual
            go.SetActive(true);
            currentIndividuals.Add(go.transform);
        }
        bestCurrentBot = currentIndividuals [0];                //Initialize on random individual
    }
Esempio n. 10
0
    void createInitialPopulation()
    {
        behaviorsToEvaluate = new Queue <BotBehavior> ();
        for (int i = 0; i < populationSize; i++)
        {
            BotBehavior bb = new BotBehavior();

            bb.GrowTree(4, new List <Type> {
                typeof(ExtendLegNode),
                typeof(ModulusNode),
                typeof(InversionNode)
            }, new List <Type> {
                typeof(TimeNode),
                typeof(TimeNode),                       //Second TimeNode to increase likelihood it is chosen
                typeof(ConstantFactorNode)
            }, 2);


            behaviorsToEvaluate.Enqueue(bb);
        }
        lastBestBot = new Tuple <int, BotBehavior>(0, behaviorsToEvaluate.Peek());

        evaluatedBehavior = new List <KeyValuePair <int, BotBehavior> > ();
    }
Esempio n. 11
0
 int evaluate(Transform currentIndividual, BotBehavior currentBehavior)
 {
     return((int)((currentIndividual.position.x * 10) - currentBehavior.calculateHeight() * 0.2f));
 }
Esempio n. 12
0
 public void setBotBehavior(BotBehavior behavior)
 {
     this.behavior = behavior;
 }
Esempio n. 13
0
    void ChangeState(BotBehavior newBehavior)
    {
        if (currentBehaviorCoroutine != null)
        {
            StopCoroutine(currentBehaviorCoroutine);
            currentBehaviorCoroutine = null;
        }


        if (newBehavior == BotBehavior.WAKE)
        {
            currentBehavior          = newBehavior;
            currentBehaviorCoroutine = WakingUp();
        }
        if (newBehavior == BotBehavior.IDLE)
        {
            currentBehavior          = newBehavior;
            currentBehaviorCoroutine = Idleing();
        }
        if (newBehavior == BotBehavior.SCANNING)
        {
            if (currentBehavior == newBehavior) // Was I already scanning?
            {
                if (detectedEvidence.Length > 1)
                {
                    bool newEvidence = false;
                    for (int i = 0; i < detectedEvidence.Length; i++)
                    {
                        if (!detectedEvidence[i].GetComponent <StandardObject>().amAnalyzed)
                        {
                            newEvidence = true;
                            break;
                        }
                    }

                    if (newEvidence)
                    {
                        currentBehaviorCoroutine = ScanningSuccess();
                    }
                    else
                    {
                        currentBehaviorCoroutine = ScanningFail();
                    }
                }
                else
                {
                    currentBehaviorCoroutine = ScanningFail();
                }
            }
            else // If I wasn't start now!
            {
                currentBehavior          = newBehavior;
                currentBehaviorCoroutine = Scanning();

                detectedEvidence = GameObject.FindGameObjectsWithTag("Evidence");
            }
        }

        if (newBehavior == BotBehavior.MOVING)
        {
            bool continueMoving = false;
            // Am I already on the way, no need to recalculate destination, unless the object is already scanned
            if (currentBehavior == BotBehavior.MOVING)
            {
                if (!detectedEvidence[chosenEvidence].GetComponent <StandardObject>().amAnalyzed)
                {
                    continueMoving           = true;
                    currentBehavior          = newBehavior;
                    currentBehaviorCoroutine = Moving();
                }
            }

            if (!continueMoving)
            {
                // Can't move if no evidence is found
                if (detectedEvidence.Length < 1)
                {
                    currentBehavior          = BotBehavior.IDLE;
                    currentBehaviorCoroutine = Idleing();
                }
                else
                {
                    bool newEvidence = false;
                    for (int i = 0; i < detectedEvidence.Length; i++)
                    {
                        if (!detectedEvidence[i].GetComponent <StandardObject>().amAnalyzed)
                        {
                            chosenEvidence      = i;
                            evidenceLocation    = detectedEvidence[i].transform.position;
                            evidenceLocation.y += idleHeight;
                            newEvidence         = true;
                            break;
                        }
                    }

                    if (newEvidence)
                    {
                        currentBehavior          = newBehavior;
                        currentBehaviorCoroutine = Moving();

                        // Journey
                        startLocation = transform.position;
                        journeyStart  = Time.time;
                        journeyLength = Vector3.Distance(startLocation, evidenceLocation) / 4;
                    }
                    else
                    {
                        currentBehavior          = BotBehavior.IDLE;
                        currentBehaviorCoroutine = Idleing();
                    }
                }
            }
        }

        if (newBehavior == BotBehavior.INDICATING)
        {
            if (!detectedEvidence[chosenEvidence].GetComponent <StandardObject>().amAnalyzed&& !detectedEvidence[chosenEvidence].GetComponent <StandardObject>().IsGrabbed())
            {
                currentBehavior          = newBehavior;
                currentBehaviorCoroutine = Indicating();
            }
            else
            {
                currentBehavior          = BotBehavior.IDLE;
                currentBehaviorCoroutine = Idleing();
            }
        }

        if (currentBehaviorCoroutine != null)
        {
            currentBehavior = newBehavior;
            StartCoroutine(currentBehaviorCoroutine);
        }
    }