// ************************************************* 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 } }
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(); }