Ejemplo n.º 1
0
    // ************************************************* Here is all of the code pertaining to the trading system *****************************************************
    //Called when a trade is first initiated
    private void initiateTrade(GameObject obj)
    {
        AgentScript otherAgent = obj.GetComponent <AgentScript>();

        inTrade = otherAgent.requestTrade(); // Request a trade with the other agent

        if (inTrade)                         // If inTrade, then we can make an offer to the other agent
        {
            freeze();
            initiator = true;             // We initated the trade
            // Generate an offer
            float ratio = myValueTable.getRatio(resourceToReceive, resourceToTrade);
            ratio += ratio * (health - 40f) / 100f;
            if (otherAgent.recieveTradeOffer(resourceToReceive, resourceToTrade, ratio))               //Propose the offer
            {
                StartCoroutine(processTrade(resourceToReceive, resourceToTrade, ratio, otherAgent));   //If accepted, start the exchange with the other agent
                SimManager.instance.updateTradeRatio(resourceToReceive, resourceToTrade, ratio, transform.position);
            }
            else                 //Otherwise we were refused, end the trade
            {
                otherAgent.endTrade();
                endTrade();
            }
        }
        else
        {
            targetTradePartner = null;             //We were rejected
        }
    }
Ejemplo n.º 2
0
 public void AgentDone()
 {
     if (this.isScriptValid() && this.getScriptType() == "AgentScript")
     {
         AgentScript.Done();
     }
 }
    // Start is called before the first frame update
    void Start()
    {
        // Big objects - objects that the agent can hide behind standing.
        bigObjList = new List <GameObject>();
        GameObject[] objs = GameObject.FindGameObjectsWithTag("Big Object");
        for (int i = 0; i < objs.Length; i++)
        {
            bigObjList.Add(objs[i]);
            coversCombined.Add(objs[i]);
        }

        // Small objects - objects that the agent can cover behind crouching.
        smallObjList = new List <GameObject>();
        objs         = GameObject.FindGameObjectsWithTag("Small Object");
        for (int i = 0; i < objs.Length; i++)
        {
            smallObjList.Add(objs[i]);
            coversCombined.Add(objs[i]);
        }

        visitedCovers = new List <GameObject>();

        movementScript = gameObject.GetComponent <MovementScript>();

        player = GameObject.FindGameObjectWithTag("Player");

        decisionMaking = gameObject.GetComponent <DecisionMakingScript>();

        agentScript = gameObject.GetComponent <AgentScript>();
    }
Ejemplo n.º 4
0
 public void AgentAddRewardDirectly(float reward)
 {
     if (this.isScriptValid() && this.getScriptType() == "AgentScript")
     {
         AgentScript.AddReward(reward);
     }
 }
Ejemplo n.º 5
0
 public void AgentDescisionRequest()
 {
     if (this.isScriptValid() && this.getScriptType() == "AgentScript")
     {
         AgentScript.AgentDescisionRequest();
     }
 }
Ejemplo n.º 6
0
    // Start is called before the first frame update
    void Start()
    {
        movePathList = new List <Vector3>();

        agentScript = gameObject.GetComponent <AgentScript>();

        move = true;
    }
Ejemplo n.º 7
0
 public void AgentAlwaysUpdate()
 {
     if (this.isScriptValid() && this.getScriptType() == "AgentScript" && !this.isDoneInProgress())
     {
         AgentScript.AgentAlwaysUpdateInternal();
         AgentScript.AgentAlwaysUpdate();
     }
 }
Ejemplo n.º 8
0
 public void setInitAgent(MLAgents.Brain brain)
 {
     if (this.isScriptValid())
     {
         AgentScript.GiveBrain(brain);
         //AgentScript.AgentReset();
     }
 }
Ejemplo n.º 9
0
 IEnumerator setStatus(AgentScript agent)
 {
     while (true)
     {
         UIManagerScript.instance.setStatus(agent);
         yield return(new WaitForSeconds(2.0f));
     }
 }
Ejemplo n.º 10
0
    public void Apply(AgentScript Agent)
    {
        float allReward = 0;

        foreach (float i in bag.ToArray())
        {
            allReward += i;
        }
        Agent.AddReward(allReward);
        BagReset();
    }
Ejemplo n.º 11
0
 public void setStatus(AgentScript agent)
 {
     this.agent = agent;
     if (agent)
     {
         name.text           = "Name: " + agent.transform.parent.name;
         infected.text       = "Infected: " + agent.infected;
         hunger.text         = "Hunger: " + agent.hunger;
         agentsAround.text   = "Agents arond: " + agent.agentsAround;
         infectedAround.text = "Infecteds around: " + agent.infectedAround;
     }
     showStatus();
 }
Ejemplo n.º 12
0
 // Use this for initialization
 void Start()
 {
     while (NumberOfAgents > 0)
     {
         AgentScript AnAgent = (AgentScript)Instantiate(prefab, new Vector3(2 * Random.value - 1, 1, 2 * Random.value - 1), Quaternion.identity);
         i = i + 1;
         AnAgent.aindex = i;
         NumberOfAgents = NumberOfAgents - 1;
         AnAgent.avPri  = 50;
         AnAgent.GetComponent <NavMeshAgent> ().stoppingDistance = 1.5f;
         AnAgent.naz = false;
     }
 }
    // Update is called once per frame
    public void shoot()
    {
        areaScript  = transform.parent.parent.GetComponentInParent <AreaScript>();
        agentScript = transform.parent.parent.GetComponent <AgentScript>();
        if (Physics.Raycast(transform.position, transform.forward, out RaycastHit hit, 15))
        {
            GameObject shot = hit.transform.gameObject;
            if (shot.CompareTag("enemy"))
            {
                areaScript.DestroyEnemy(shot);
                Debug.Log("Hit Enemy");
            }

            else
            {
                agentScript.AddReward(-0.0002f);
            }
        }
Ejemplo n.º 14
0
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hit) && !isFollowing)
            {
                if ((hit.transform.tag == "Agent" || hit.transform.tag == "InfectedAgent") && checkForDoubleClick(Time.realtimeSinceStartup, hit.transform.gameObject))
                {
                    followCoroutine = follow(hit.transform.gameObject);
                    StartCoroutine(followCoroutine);
                }

                if (hit.transform.tag == "Agent" || hit.transform.tag == "InfectedAgent")
                {
                    if (agent != null)
                    {
                        agent.dishighlight();
                    }
                    agent = hit.transform.GetComponentInChildren <AgentScript>();
                    agent.highlight();
                    if (statusCoroutine != null)
                    {
                        StopCoroutine(statusCoroutine);
                    }
                    statusCoroutine = setStatus(agent);
                    StartCoroutine(statusCoroutine);
                }
                else
                {
                    //StopCoroutine(statusCoroutine);
                    //UIManagerScript.instance.hideStatus();
                }
            }
        }
        if (Input.GetMouseButtonDown(1))
        {
            StartCoroutine(unfollow());
        }
        moveCamera();
    }
Ejemplo n.º 15
0
    public void DestroyEnemy(GameObject enemy)
    {
        GameObject  agent       = transform.Find("Agent").gameObject;
        AgentScript agentScript = agent.GetComponent <AgentScript>();

        for (int i = 0; i < enemylist.Count; i++)
        {
            if (GameObject.ReferenceEquals(enemylist[i], enemy))
            {
                Destroy(enemylist[i]);
                enemylist.Remove(enemylist[i]);
                agentScript.AddReward(1f);
            }
        }

        if (enemylist.Count == 0)
        {
            //agentScript.AddReward(5f);
            agentScript.EndEpisode();
        }
    }
Ejemplo n.º 16
0
    // Start is called before the first frame update
    void Start()
    {
        // Getting all allied AI units.
        allyAgents = new List <GameObject>();
        GameObject[] agents = GameObject.FindGameObjectsWithTag("Enemy");
        for (int i = 0; i < agents.Length; i++)
        {
            allyAgents.Add(agents[i]);
        }

        noOfAgents = allyAgents.Count;

        coverFinder    = gameObject.GetComponent <CoverFinderScript>();
        movementScript = gameObject.GetComponent <MovementScript>();
        agentScript    = gameObject.GetComponent <AgentScript>();
        emotion        = gameObject.GetComponent <EmotionScript>();

        player       = GameObject.FindGameObjectWithTag("Player");
        playerScript = player.GetComponent <PlayerScript>();

        decisionTimer = 0.0f;
    }
Ejemplo n.º 17
0
    IEnumerator processTrade(int rid1, int rid2, float ratio, AgentScript otherAgent)
    {
        //First we need to calculate how much of each resource can be traded.
        while (resources[rid2] >= 1f && otherAgent.resources[rid1] >= ratio)
        {
            if (otherAgent.dead)
            {
                break;                           // If they die during the exchange, continue on like nothing happened
            }
            resources[rid1]            += ratio; // Gain ratio resources
            resources[rid2]            -= 1f;    // Lose 1 resource
            otherAgent.resources[rid1] -= ratio; //Other agent loses ratio
            otherAgent.resources[rid2] += 1f;    //Other agent gains 1

            processResourceChanges();            //Updates health for both agents
            otherAgent.processResourceChanges();

            yield return(new WaitForSeconds(0.1f));
        }

        otherAgent.endTrade();         //End the trade
        endTrade();
    }
Ejemplo n.º 18
0
 public void setDead()
 {
     if (this.isScriptValid() && !this.isDead())
     {
         if (AgentScript)
         {
             setOnceDone();
             AgentScript.die();
             AgentScript.innerDie();
         }
         else if (UnitScript)
         {
             UnitScript.die();
         }
         else
         {
             Debug.LogError("Couldn't setDead() because the script was valid");
         }
     }
     else
     {
         Debug.LogError("Couldn't setDead() because the script was valid");
     }
 }
Ejemplo n.º 19
0
    //public float strengthCoef = 20000f;
    //public float maxTurn = 20f;

    // Start is called before the first frame update
    void Start()
    {
        Im = GetComponent <AgentScript>();
    }
Ejemplo n.º 20
0
    // Update is called once per frame
    void Update()
    {
        CheckIfNearCover();

        if (Input.GetMouseButton(0))
        {
            shootingTime += Time.deltaTime;
            if (ammo > 0 && reloading == false && shooting == false)
            {
                if (accuracy - (shootingTime / 2) > 5)
                {
                    accuracy -= (shootingTime / 2);
                }
                else
                {
                    accuracy = 5;
                }

                StartCoroutine(Shoot());
                Ray        ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                RaycastHit hit;
                if (Physics.Raycast(ray, out hit))
                {
                    if (hit.collider != null)
                    {
                        GameObject hitObject = hit.collider.gameObject;
                        if (hitObject.CompareTag("Enemy"))
                        {
                            StartCoroutine(AttackingAgent(hitObject.gameObject));

                            AgentScript agentScript = hitObject.GetComponent <AgentScript>();
                            if (agentScript == null)
                            {
                                return;
                            }

                            int random = Random.Range(0, 101);
                            if (random <= accuracy)
                            {
                                agentScript.ReceiveDamage(damage);
                            }
                        }
                        else
                        if (hitObject.CompareTag("Big Object") || hitObject.CompareTag("Small Object"))
                        {
                            //if(attackedCover != hitObject.gameObject)
                            //{
                            StartCoroutine(AttackingCover(hitObject.gameObject));
                            //}
                        }
                    }
                }
            }
        }
        else
        {
            shootingTime = 0.0f;
            accuracy     = 30;
        }

        if (Input.GetKeyDown(KeyCode.R))
        {
            UnityEngine.Debug.Log("R pressed, ammo " + ammo + " reloading " + reloading);
            if (reloading == false && ammo < clipAmount)
            {
                StartCoroutine(Reload());
            }
        }

        if (Input.GetKeyDown(KeyCode.LeftControl))
        {
            if (crouching)
            {
                crouching = false;
                gameObject.transform.localScale = new Vector3(2.77f, 4.22f, 3.06f);
            }
            else
            {
                crouching = true;
                gameObject.transform.localScale = new Vector3(2.77f, 3.0f, 3.06f);
            }
        }
    }
Ejemplo n.º 21
0
 public virtual void RewardAtDie(AgentScript unit)
 {
 }
Ejemplo n.º 22
0
 private void Awake()
 {
     gameObject.GetComponent <Animator>().SetInteger(WalkDirection, 4);
     _agentScript = GetComponent <AgentScript>();
 }
Ejemplo n.º 23
0
    public void Update()
    {
        if (Input.GetMouseButtonUp(0))
        {
            if (selected)
            {
                Debug.Log(selected.title + " was selected!");   //para saber si detecta la opción//

                myAgent = GameObject.FindGameObjectWithTag("Prota").GetComponent <AgentScript>();

                Debug.Log(myAgent);
                myAgent.MoverPersonaje();



                if (selected.title == "talk")
                {
                    Debug.Log(selected.title + " VAMOS PROGRESANDO COÑO!");  //para saber si detecta la opción//


                    // VIDE_Assign assigned;
                    // assigned = GameObject.Find("ElaineMenu").AddComponent<VIDE_Assign>();
                    //   Debug.Log("ASSIGNED: " + assigned);
                    // diagUI.Begin(assigned);
                    //   GameObject x = GameObject.Find("NPC_Charlie");
                    //   dialogue2 = x.AddComponent<VIDE_Data>();
                    //   Debug.Log("DIALOGUE: " + assigned);
                    //myAgent.TryInteract(assigned);
                    // dialogue.BeginDialogue(GetComponent<VIDE_Assign>());
                    //    Debug.Log("ASSIGNED2: " + assigned);
                    //myAgent.OnGUI(dialogue);
                    myAgent.TryInteract(/*dialogue.GetComponent<VIDE_Assign>()*/);

                    /*  assigned = GameObject.Find("NPC_Charlie").GetComponent<VIDE_Assign>();
                     *
                     * if (!diagUI.dialogue.isLoaded)
                     * {
                     *
                     *    //... and use it to begin the conversation
                     *    diagUI.Begin(assigned);
                     *    while (diagUI.dialogue.isLoaded)
                     *    {
                     *
                     *
                     *        if (Input.GetMouseButtonDown(0))
                     *    {
                     *
                     *        diagUI.NextNode();
                     *
                     *    }
                     *    }
                     * }
                     * else
                     * {
                     *    //If conversation already began, let's just progress through it
                     *    diagUI.NextNode();
                     * }*/
                }
            }


            Destroy(gameObject);
        }
    }
Ejemplo n.º 24
0
 void Start()
 {
     agentScript = this.GetComponent <AgentScript>();
     agent       = this.GetComponent <NavMeshAgent>();
 }
Ejemplo n.º 25
0
 public override void RewardAtDie(AgentScript unit)
 {
     AddReward(-1f);
 }
Ejemplo n.º 26
0
 void Start()
 {
     agent      = GetComponent <AgentScript>();
     chosenRoom = agent.currentRoom;
 }
Ejemplo n.º 27
0
    // Update is called once per frame
    void Update()
    {
        if (dead)
        {
            return;
        }

        //Update the heatmap with my current position
        HeatMap.instance.AddHeat(transform.position, SimManager.instance.colors[id] * Time.deltaTime);

        //Update my health and check if I should perform some other action
        health -= healthLoss * Time.deltaTime;
        if (health <= 0)
        {
            Die();
        }
        if (health >= 90)
        {
            Reproduce();
        }

        //Agent asks these questions to determine what to do
        // 1. Do I want to gather or trade?
        //    a. If gather, do I know where a resource I can gather from is?
        //       -If so, move to that resource. If not, wander.
        //    b. If trade, do I see an agent I want to trade with?
        //       -If so, move to that agent. If not, wander.

        //This is the state code. It determines what this agent would like to do.
        float desiredResourceLevel = maxResourceCount / (50f / health);

        desiredResourceLevel = desiredResourceLevel <= maxResourceCount ? desiredResourceLevel : maxResourceCount;

        //desired is how many resources this agent would like to be carrying before it attmepts to trade
        if (totalResources < desiredResourceLevel)
        {
            mode = Modes.Gather;
        }
        else
        {
            targetResource = null;
            mode           = Modes.Trade;
        }


        //Determine if I want to trade by the total number of resources I am currently carrying.
        if (mode == Modes.Gather)
        {
            //Select resource
            if (targetResource == null)
            {
                float dist = float.MaxValue;

                //Go to closest resource that is not my resource
                for (int j = 0; j < closeResources.Length; j++)
                {
                    if (closeResources[j].GetComponent <Resource>().id != id && Vector3.SqrMagnitude(transform.position - closeResources[j].transform.position) < dist)
                    {
                        dist           = Vector3.SqrMagnitude(transform.position - closeResources[j].transform.position);
                        targetResource = closeResources[j];
                    }
                }
            }
            else if (targetResource != null && targetResource.GetComponent <Resource>().isEmpty())                // If my current target resource is empty, move on
            {
                targetResource = null;
            }

            //Acutally mine the resource
            if (targetResource != null)
            {
                movementDir = (targetResource.transform.position - transform.position).normalized;
            }
            else                 //Or wander randomely
            {
                Wander();
            }
        }

        //Actively look for a trade
        if (mode == Modes.Trade && !inTrade && tradeCooldown <= 0f)
        {
            // Targets with different priorities
            GameObject firstTarget  = null;
            GameObject secondTarget = null;

            // Find the resource in my inventory that I have the most of (Will determine who to trade with with this resource)
            int   mostNotMineId     = 0;
            float mostNotMineAmount = 0;
            for (int i = 0; i < resources.Length; i++)
            {
                if (i != id && resources[i] > mostNotMineAmount)
                {
                    mostNotMineId     = i;
                    mostNotMineAmount = resources[i];
                }
            }

            // first see who is the best person to trade with in my radius.
            if (targetTradePartner == null)
            {
                float highestTradeQuantity  = 0;
                float highestTradeQuantity2 = 0;
                bool  foundPriorityDeal     = false;

                for (int k = 0; k < closeAgents.Length; k++)
                {
                    if (closeAgents[k] == gameObject)
                    {
                        continue;                                                   //Skip myself
                    }
                    AgentScript tempAgent = closeAgents[k].GetComponent <AgentScript>();
                    if (!tempAgent.inTrade && !tempAgent.dead)                       //The agent I wish to trade with may die while I am looking at them, this will handle that case.

                    {
                        float min = Mathf.Min(tempAgent.resources[id], mostNotMineAmount);
                        //Is there someone trading for my resource (most prefered)
                        if (min > 5f && min > highestTradeQuantity)
                        {
                            firstTarget          = closeAgents[k];
                            highestTradeQuantity = min;
                            foundPriorityDeal    = true;
                        }

                        //No point checking for the best deal if a priority deal was found.
                        if (foundPriorityDeal)
                        {
                            continue;
                        }

                        //Otherwise find the best deal by resource value
                        for (int i = 0; i < tempAgent.resources.Length; i++)
                        {
                            float min2 = Mathf.Min(tempAgent.resources[i], mostNotMineAmount);
                            float deal = min2 * myValueTable.getRatio(i, mostNotMineId);
                            if (min2 > 5f && deal > highestTradeQuantity2)
                            {
                                secondTarget          = closeAgents[k];
                                highestTradeQuantity2 = deal;
                                resourceToReceive     = i;
                            }
                        }
                    }
                }

                //Did I find a priority value?
                if (firstTarget != null)
                {
                    targetTradePartner = firstTarget;
                    resourceToTrade    = mostNotMineId;
                    resourceToReceive  = id;
                }
                else if (secondTarget != null)                     // No priority value, did I find another option?
                {
                    targetTradePartner = secondTarget;
                    resourceToTrade    = mostNotMineId;
                }
            }

            //Move to that person
            if (targetTradePartner != null)
            {
                //If our current target gets too far away or gets into a trade before we get there, move to a new target.
                AgentScript temp = targetTradePartner.GetComponent <AgentScript>();
                if (Vector3.Distance(transform.position, targetTradePartner.transform.position) > 20f || temp.inTrade || temp.dead)
                {
                    targetTradePartner = null;
                }
                else
                {
                    movementDir = (targetTradePartner.transform.position - transform.position).normalized;
                }
            }
            else                 // If no person to trade with found
            {
                Wander();
            }
        }

        // If we failed a trade, then we will wander for the designated time
        if (tradeCooldown > 0)
        {
            if (mode == Modes.Trade)
            {
                Wander();
            }
            tradeCooldown -= Time.deltaTime;
        }

        //Change size based on health
        transform.localScale = new Vector3(health / 50f + 0.25f, 1, health / 50f + 0.25f);
    }
Ejemplo n.º 28
0
    void NextGeneration()
    {
        UIScript.instance.generation.text = "Gen : " + ++genCount;
        //evalute agent fitness
        float maxScore = GetMaxScore();

        UIScript.instance.prevScoreText.text = "PrevScore : " + maxScore;
        //group them
        //discard the bad agents
        //select the good agents
        List <GameObject> sucessors = GetGoodAgents(maxScore);

        if (sucessors.Count == 0)
        {
            UIScript.instance.generation.text = "Gen : Extinct";
            return;
        }
        int goodAgentCount = sucessors.Count;
        int remainingAgent = noOfAgent - goodAgentCount;

        //fill remaining population crossover
        for (int i = 0; i < remainingAgent; i++)
        {
            GameObject temp = Instantiate(agentPrefab, Vector3.zero + agentParent.position, Quaternion.identity, agentParent);
            if (Random.value < crossOverProbability)
            {
                AgentScript a1 = sucessors[Random.Range(0, goodAgentCount)].GetComponent <AgentScript>();
                AgentScript a2 = sucessors[Random.Range(0, goodAgentCount)].GetComponent <AgentScript>();
                float[][,] tempWeights = CrossOverWeights(a1.neural.GetWeights(), a2.neural.GetWeights());
                float[][] tempBias = CrossOverBias(a1.neural.GetBias(), a2.neural.GetBias());
                temp.GetComponent <AgentScript>().Intialize(tempWeights, tempBias, neuronsPerLayer);
            }
            else
            {
                AgentScript a = sucessors[Random.Range(0, goodAgentCount)].GetComponent <AgentScript>();
                float[][,] tempWeights = MutationWeights(a.neural.GetWeights());
                float[][] tempBias = MutationBias(a.neural.GetBias());
                temp.GetComponent <AgentScript>().Intialize(tempWeights, tempBias, neuronsPerLayer);
            }
            //mutate agent
            //add them to agentList
            agentList.Add(temp);
        }
        foreach (GameObject go in sucessors)
        {
            if (go)
            {
                if (elitism)
                {
                    GameObject  temp = Instantiate(agentPrefab, Vector3.zero + agentParent.position, Quaternion.identity, agentParent);
                    AgentScript a    = go.GetComponent <AgentScript>();
                    float[][,] tempWeights = a.neural.GetWeights();
                    float[][]   tempBias = a.neural.GetBias();
                    AgentScript b        = temp.GetComponent <AgentScript>();
                    b.Intialize(tempWeights, tempBias, neuronsPerLayer);
                    //Debug.Log("bs : "+a.neural.CompareBias(b.neural.GetBias()));
                    agentList.Add(temp);
                }
                Destroy(go);
            }
        }
        //adding
        //clearobstacle
        ClearObstacle();
        //clear score
        score = 0f;
        //start obstacle spawner
        StartCoroutine(CreateObject());
        CurrentAgent = agentList.Count;
    }
Ejemplo n.º 29
0
 // Start is called before the first frame update
 void Start()
 {
     decisionMaking = gameObject.GetComponent <DecisionMakingScript>();
     movementScript = gameObject.GetComponent <MovementScript>();
     agentScript    = gameObject.GetComponent <AgentScript>();
 }
Ejemplo n.º 30
0
 /// <summary>
 /// Start this instance.
 /// </summary>
 /// <remarks>
 /// Invoked by MainCSharp to get agentPersistence from <see cref="HelperScript"/>.
 /// </remarks>
 public void Start()
 {
     agentPersistence = parentScript.helperCube.GetComponent <HelperScript>().agentPersistence;
     agent            = parentScript.agentCube.GetComponent <AgentScript>();
 }