private void PopulateTradeRouteMenu(TradeRoute tradeRoute) { if (tradeRoute == null) { throw new ArgumentNullException("tradeRoute"); } var contextMenu = ContextMenu; if (contextMenu != null) { contextMenu.Items.Clear(); } if (tradeRoute.SourceColony.OwnerID != _appContext.LocalPlayer.EmpireID) { return; } if (contextMenu == null) { contextMenu = new ContextMenu(); ContextMenu = contextMenu; } contextMenu.Items.Add( new MenuItem { Header = _resourceManager.GetString("Cancel trade route"), CommandParameter = tradeRoute, Command = GalaxyScreenCommands.CancelTradeRoute }); }
/// <summary> /// Save the trade route. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnSave_Click(object sender, EventArgs e) { using (SectorContext db = new SectorContext()) { TradeRoute toSave; if (currentRouteId == -1) { toSave = new TradeRoute(); db.routes.Add(toSave); } else { toSave = (from t in db.routes where (t.id == currentRouteId) select t).FirstOrDefault(); } if (toSave != null) { toSave.star1X = (int)nud1X.Value; toSave.star1Y = (int)nud1Y.Value; toSave.star2X = (int)nud2X.Value; toSave.star2Y = (int)nud2Y.Value; db.SaveChanges(); currentRouteId = toSave.id; } } UpdateListbox(); }
public ActionResult Edit(int?id, TradeEditView input) { TradeRoute route = null; using (var session = DB.Instance.GetSession()) { if (id.HasValue) { route = session.Load <TradeRoute>(id); route.Name = input.Route.Name; route.Notes = input.Route.Notes; } else { route = new TradeRoute { Name = input.Route.Name }; session.Store(route); } session.SaveChanges(); } if (id.HasValue) { return(RedirectToAction("View", new { id = route.Id })); } return(RedirectToAction("Edit", new { id = route.Id })); }
/// <summary> /// Notification of a trade route being removed. /// </summary> public void DisconnectTradeRoute(TradeRoute tr) { if (tr == mSelectedRoute) { mSelectedRoute = null; } }
/// <summary> /// Updates the data section of the form. /// </summary> /// <param name="star">The planet to display in the data section of the form</param> private void UpdateData(TradeRoute route) { nud1X.Value = route.star1X; nud1Y.Value = route.star1Y; nud2X.Value = route.star2X; nud2Y.Value = route.star2Y; nud1X.Focus(); }
public void TradeRoute_WhenCheckingShipValidForJoiningRoute_Should_RespondYesIfShipDesignMeetsAllCriteria() { var tradeRoute = new TradeRoute(); var shipDesignToCheck = new ShipClassDesign(); var shipIsValid = tradeRoute.ShipDesignValidForRoute(shipDesignToCheck); Assert.IsTrue(shipIsValid); }
public void RegisterTradeRoute(TradeRoute tradeRoute) { if (TradeRoutes.Contains(tradeRoute)) { return; } TradeRoutes.Add(tradeRoute); }
public void RegisterTradeRoute(TradeRoute tradeRoute) { if (TradeRoutes.Contains(tradeRoute)) { return; } TradeRoutes.Add(tradeRoute); _sender.Publish("oilextractor.traderoute.changed", this); }
/// <summary> /// Callback triggered when the player clicks on something. /// </summary> void OnClick(int button) { if (button == 0) { if (mIsValid) { if (mTargetTown != null) { if (mRoute.Connect(mTargetTown)) { // See if there is a duplicate route foreach (TradeRoute tr in TradeRoute.list) { if (tr != mRoute && tr.GetConnectedTown(mRoute.town0) == mRoute.town1) { // Copy the trade path tr.CopyPath(mRoute.path); // Ensure that no towns are still referencing this trade route foreach (Town t in Town.list) { t.DisconnectTradeRoute(tr); } Object.Destroy(mGO); break; } } // This route has now been created mIsValid = false; mTargetTown = null; mRoute = null; mGO = null; } } else { mRoute.Add(mTargetPos); } } } else if (!mRoute.UndoAdd()) { foreach (Town t in Town.list) { t.DisconnectTradeRoute(mRoute); } Object.Destroy(mGO); mIsValid = false; mTargetTown = null; mRoute = null; mGO = null; } }
public void TradeRoute_ShouldBeAbleTo_Give_ListOfTradePriorities() { var tradeRoute = new TradeRoute(); var tradePriorities = tradeRoute.GetTrades(); Assert.AreEqual(TradePriorityEnum.PlanetaryInstallations, tradePriorities[0]); Assert.AreEqual(TradePriorityEnum.TNMinerals, tradePriorities[1]); Assert.AreEqual(TradePriorityEnum.Colonists, tradePriorities[2]); Assert.AreEqual(TradePriorityEnum.Fuel, tradePriorities[3]); Assert.AreEqual(TradePriorityEnum.MaintenanceSupply, tradePriorities[4]); Assert.AreEqual(TradePriorityEnum.SNGoodsAndResources, tradePriorities[5]); }
public static TradeRoute Create(Starport origin, Starport destination, Commodity commodity, int buy, int sell) { TradeRoute route = new TradeRoute(); route.Commodity = commodity; route.Origin = origin; route.Destination = destination; route.Buy = buy; route.Sell = sell; return(route); }
public void UnregisterTradeRoute(TradeRoute tradeRoute) { if (!TradeRoutes.Contains(tradeRoute)) { return; } TradeRoutes.Remove(tradeRoute); _resourceManager.ReturnVehicle(ExtractedOilSlick.type); _sender.Publish("oilextractor.traderoute.changed", this); }
// Start is called before the first frame update void Start() { _tradeRoute = transform.GetComponent <TradeRoute>(); _tradeRoute.TradeRoutePath = this; _oilVehicle = _tradeRoute.OilVehicle; _currentPathManagerEdge = PathManagerEdges[0]; _currentSpeed = 0.01f; _accelerating = true; _oilVehicle.SetActive(true); _isPaused = true; _oilVehicle.transform.position = _currentPathManagerEdge.PathManager.waypoints[_currentPathManagerEdge.EntryWaypoint.transform.GetSiblingIndex()].transform.position; _tradeRoute.BeginLoadingOil(); }
public TradeRoute[] SortTradeRoutes(TradeRoute[] givenRoute) { TradeRoute[] tempArray; if (givenRoute.Length > 1) { int[] pivot = { (int)Mathf.Floor(givenRoute.Length / 2), 0, 1 }; tempArray = new TradeRoute[givenRoute.Length]; for (int i = 0; i < givenRoute.Length; i++) { if (i != pivot[0]) { if (givenRoute[i].GetDistance() < givenRoute[pivot[0]].GetDistance()) { //Debug.Log("iteration + " + pivot[1] + " :" + givenRoute[i].GetNames()); tempArray[pivot[1]] = givenRoute[i]; pivot[1]++; } else { //Debug.Log("if bigger iteration " + (tempArray.Length - pivot[2]) + ": " + givenRoute[i].GetNames()); tempArray[tempArray.Length - pivot[2]] = givenRoute[i]; pivot[2]++; } } } //Create the two sub arrays tempArray[pivot[1]] = givenRoute[pivot[0]]; TradeRoute[] small = new TradeRoute[pivot[1]]; TradeRoute[] big = new TradeRoute[pivot[2] - 1]; //Debug.Log(givepivot[0]); for (int i = 0; i < small.Length; i++) { small[i] = tempArray[i]; } small = SortTradeRoutes(small); small.CopyTo(tempArray, 0); for (int i = 0; i < big.Length; i++) { big[i] = tempArray[pivot[1] + 1 + i]; } big = SortTradeRoutes(big); big.CopyTo(tempArray, pivot[1] + 1); } else { tempArray = givenRoute; } return(tempArray); }
/// <summary> /// Starts a new trade route. /// </summary> public TradeRoute StartNewTradeRoute(Town town) { if (mGO == null) { mGO = new GameObject("Trade Route Creator"); mRoute = mGO.AddComponent <TradeRoute>(); mRoute.texture = pathTexture; } if (town != null) { mRoute.Connect(town); } return(mRoute); }
/// <summary> /// Starts a new trade route. /// </summary> public TradeRoute StartNewTradeRoute (Town town) { if (mGO == null) { mGO = new GameObject("Trade Route Creator"); mRoute = mGO.AddComponent<TradeRoute>(); mRoute.texture = pathTexture; } if (town != null) { mRoute.Connect(town); } return mRoute; }
/// <summary> /// Finds the next trade route connected to the specified town. /// </summary> static public TradeRoute FindNext(TradeRoute tradeRoute, Town town, bool reverse) { bool found = false; TradeRoute first = null; TradeRoute last = null; foreach (TradeRoute tr in TradeRoute.list) { if (tr == tradeRoute) { // Now that we've found the current node, if we're going in reverse, we can use the last node if (reverse && last != null) { return(last); } // Remember that we've found the current node found = true; } else if (tr.GetConnectedTown(town) != null) { // If the current node has already been found and we're going in order, we're done if (found && !reverse) { return(tr); } // Remember this node if (first == null) { first = tr; } last = tr; } } // If we were going in reverse, just return the last available node if (reverse) { return((last == null) ? tradeRoute : last); } // Going in order? Just return the first node. return((first == null) ? tradeRoute : first); }
public void FindHAvingOnlyOneOtherStarportShouldCalculateProfit() { Starport origin = Starports.DrzewieckiGateway; Starport[] destinations = new[] { Starports.McKayPort, Starports.DrzewieckiGateway }; TradeRouteCalculator finder = new TradeRouteCalculator(destinations); TradeRoute route = finder.Find(origin); Assert.AreEqual(5133, route.Buy); Assert.AreEqual(5818, route.Sell); Assert.AreEqual(685, route.Profit); Assert.AreNotEqual(Starports.DrzewieckiGateway, route.Destination); }
/// <summary> /// Reset the listbox and data area. /// </summary> private void ResetListboxAndData() { using (SectorContext db = new SectorContext()) { if (db.routes.Count() > 0) { TradeRoute current = (from r in db.routes orderby r.id ascending select r).FirstOrDefault(); currentRouteId = current.id; UpdateGUI(current); } else { UpdateListbox(); } } }
public void EstablishTradeRoute(City city) { if (city == null) { return; } if (false == _resourceManager.AttemptToReserveVehicle(ExtractedOilSlick.type)) { return; } var go = Instantiate(TradeRoutePrefab); go.transform.position = transform.position; go.transform.parent = transform; go.transform.name = city.Name + " Trade Route"; TradeRoute tradeRoute = go.GetComponent <TradeRoute>(); tradeRoute.City = city; tradeRoute.OilExtractor = this; }
/// <summary> /// Update the listbox and data sections. /// </summary> /// <param name="star"></param> private void UpdateGUI(TradeRoute route) { UpdateListbox(); UpdateData(route); }
public override void ReadXml(XmlReader reader) { int num = reader.ReadVersionAttribute(); this.guid = reader.GetAttribute <ulong>("GUID"); this.userDefinedName = reader.GetAttribute("UserDefinedString"); this.TurnWhenToProceedWithRazing = reader.GetAttribute <int>("TurnWhenToProceedWithRazing"); this.ShouldRazeRegionBuildingWithSelf = reader.GetAttribute <bool>("ShouldRazeRegionBuildingWithSelf"); this.ShouldInjureSpyOnRaze = reader.GetAttribute <bool>("ShouldInjureSpyOnRaze"); this.AdministrationSpeciality = reader.GetAttribute <string>("AdministrationSpeciality"); AICityState aicityState; if (!StaticString.IsNullOrEmpty(this.AdministrationSpeciality) && (!Databases.GetDatabase <AICityState>(false).TryGetValue(this.AdministrationSpeciality, out aicityState) || !aicityState.IsGuiCompliant)) { this.AdministrationSpeciality = StaticString.Empty; } base.ReadXml(reader); int attribute = reader.GetAttribute <int>("Count"); reader.ReadStartElement("Districts"); this.districts.Clear(); for (int i = 0; i < attribute; i++) { District district = new District(reader.GetAttribute <ulong>("GUID")); reader.ReadElementSerializable <District>(ref district); if (district != null) { this.AddDistrict(district); } } reader.ReadEndElement("Districts"); if (num >= 2) { if (reader.IsNullElement()) { reader.Skip(); } else { Militia militia = new Militia(reader.GetAttribute <ulong>("GUID")); militia.Empire = this.Empire; reader.ReadElementSerializable <Militia>(ref militia); this.Militia = militia; if (this.Militia != null) { base.AddChild(this.Militia); } } } int attribute2 = reader.GetAttribute <int>("Count"); reader.ReadStartElement("Improvements"); this.cityImprovements.Clear(); for (int j = 0; j < attribute2; j++) { CityImprovement cityImprovement = new CityImprovement(reader.GetAttribute <ulong>("GUID")); reader.ReadElementSerializable <CityImprovement>(ref cityImprovement); if (cityImprovement != null) { this.AddCityImprovement(cityImprovement, false); } } reader.ReadEndElement("Improvements"); this.WorldPosition = reader.ReadElementSerializable <WorldPosition>(); if (num >= 2 && this.Militia != null) { this.Militia.WorldPosition = this.WorldPosition; } if (reader.IsStartElement("BesiegingEmpireIndex")) { int num2 = reader.ReadElementString <int>("BesiegingEmpireIndex"); this.BesiegingEmpireIndex = num2; } if (num >= 3) { if (reader.IsNullElement()) { reader.Skip(); } else { CadastralMap cadastralMap = new CadastralMap(); reader.ReadElementSerializable <CadastralMap>(ref cadastralMap); this.CadastralMap = cadastralMap; } } if (num >= 4) { this.TradeRoutes.Clear(); int attribute3 = reader.GetAttribute <int>("Count"); reader.ReadStartElement("TradeRoutes"); for (int k = 0; k < attribute3; k++) { TradeRoute item = new TradeRoute(); reader.ReadElementSerializable <TradeRoute>(ref item); this.TradeRoutes.Add(item); } base.SetPropertyBaseValue(SimulationProperties.IntermediateTradeRoutesCount, 0f); base.SetPropertyBaseValue(SimulationProperties.IntermediateTradeRoutesDistance, 0f); base.SetPropertyBaseValue(SimulationProperties.IntermediateTradeRoutesGain, 0f); reader.ReadEndElement("TradeRoutes"); } if (num >= 5) { int attribute4 = reader.GetAttribute <int>("Count"); if (this.Ownership.Length < attribute4) { this.Ownership = new float[attribute4]; } reader.ReadStartElement("Ownerships"); for (int l = 0; l < attribute4; l++) { this.Ownership[l] = reader.ReadElementString <float>("Ownership"); } reader.ReadEndElement("Ownerships"); } if (num >= 6) { this.DryDockPosition = reader.ReadElementSerializable <WorldPosition>(); } if (num >= 7) { Camp camp = new Camp(reader.GetAttribute <ulong>(Camp.SerializableNames.CampGUID)) { Empire = this.Empire }; reader.ReadElementSerializable <Camp>(ref camp); if (camp != null) { for (int m = 0; m < camp.Districts.Count; m++) { camp.Districts[m].City = this; base.AddChild(camp.Districts[m]); camp.Districts[m].Refresh(false); } this.Camp = camp; } } if (num >= 8) { this.lastNonInfectedOwnerIndex = reader.ReadElementString <int>("LastNonInfectedOwnerIndex"); } }
/// <summary> /// Finds the next trade route connected to the specified town. /// </summary> public static TradeRoute FindNext(TradeRoute tradeRoute, Town town, bool reverse) { bool found = false; TradeRoute first = null; TradeRoute last = null; foreach (TradeRoute tr in TradeRoute.list) { if (tr == tradeRoute) { // Now that we've found the current node, if we're going in reverse, we can use the last node if (reverse && last != null) return last; // Remember that we've found the current node found = true; } else if (tr.GetConnectedTown(town) != null) { // If the current node has already been found and we're going in order, we're done if (found && !reverse) return tr; // Remember this node if (first == null) first = tr; last = tr; } } // If we were going in reverse, just return the last available node if (reverse) return (last == null) ? tradeRoute : last; // Going in order? Just return the first node. return (first == null) ? tradeRoute : first; }
/// <summary> /// Draws the UI for the current town. /// </summary> void DrawTownUI() { Vector2 mousePos = UI.GetMousePos(); Rect rect = new Rect(Screen.width * 0.5f + 130f, Screen.height * 0.5f - 260f, 292f, 270f); // Allow the opposite town's resources to be dragged straight to this window for simplicity's sake if (mDragResource != -1 && Input.GetMouseButtonUp(0) && rect.Contains(mousePos)) { if (mDragTown == this) { mDragTown = null; } mSelectedRoute.SetExportedResource(mDragTown, mDragResource); CancelDrag(); } // Draw the resources Rect inner = UI.DrawWindow(rect, name); DrawResources(this, inner); inner.y += inner.height - 40f; inner.height = 40f; if (GUI.Button(inner, "Establish a New Trade Route", Config.Instance.skin.button)) { showInfo = false; TradeRouteCreator.Instance.StartNewTradeRoute(this); } if (mSelectedRoute != null) { rect = new Rect(rect.x, Screen.height * 0.5f + 40f, 292f, 225f); // Allow main town's resources to be dragged straight to this window for simplicity's sake if (mDragResource != -1 && Input.GetMouseButtonUp(0) && rect.Contains(mousePos)) { if (mDragTown != this) { mDragTown = null; } mSelectedRoute.SetExportedResource(mDragTown, mDragResource); CancelDrag(); } Town town = mSelectedRoute.GetConnectedTown(this); inner = UI.DrawWindow(rect, town.name); // See if we have more than one trade route TradeRoute next = TradeRoute.FindNext(mSelectedRoute, this, true); // Draw trade route navigation buttons if (next != mSelectedRoute) { if (GUI.Button(new Rect(rect.x + 20f, rect.y - 18f, 40f, 40f), "<<", Config.Instance.skin.button)) { mSelectedRoute = next; } else if (GUI.Button(new Rect(rect.x + rect.width - 60f, rect.y - 18f, 40f, 40f), ">>", Config.Instance.skin.button)) { mSelectedRoute = TradeRoute.FindNext(mSelectedRoute, this, false); } } DrawResources(town, inner); } }
public TradeOrders(TradeRoute Destination, List <Item> Manifests) { this.Destination = Destination; this.Manifests = Manifests; }
/// <summary> /// Draw the user interface for the town. /// </summary> void DrawGUI() { float alpha = showInfo ? 1.0f : 0.0f; mAlpha = Mathf.Lerp(mAlpha, alpha, Time.deltaTime * (showInfo ? 4.0f : 2.0f)); if (mAlpha > 0.001f) { // Block camera control if (showInfo) { StrategicCamera.allowInput = false; } UI.SetAlpha(mAlpha); { // Automatically choose the first available trade route if (mSelectedRoute == null || (mSelectedRoute.town0 != this && mSelectedRoute.town1 != this)) { mSelectedRoute = null; foreach (TradeRoute tr in TradeRoute.list) { Town town = tr.GetConnectedTown(this); if (town != null) { mSelectedRoute = tr; break; } } } // Draw the town's UI DrawTownUI(); // If we have a trade route we can draw the trade UI if (mSelectedRoute != null) { DrawTradeUI(); } // Draw the ship-related UI DrawBuildShipsUI(); DrawFreeShipsUI(); // Cancel all dragging operations on mouse up if (Input.GetMouseButtonUp(0)) { CancelDrag(); } // Draw the dragged resource DrawIconUI(); // Draw the exit button if (GUI.Button(new Rect(Screen.width * 0.5f - 75.0f, Screen.height - 45.0f, 150.0f, 40.0f), "Return to Game", Config.Instance.skin.button)) { showInfo = false; } } UI.RestoreAlpha(); } }
public void AddTradeRoute(TradeRoute tradeRoute) { Debug.Log("ADD TRADE ROUTE"); }
/// <summary> /// Draw the user interface for the town. /// </summary> void DrawGUI() { float alpha = showInfo ? 1.0f : 0.0f; mAlpha = Mathf.Lerp(mAlpha, alpha, Time.deltaTime * (showInfo ? 4.0f : 2.0f)); if (mAlpha > 0.001f) { // Block camera control if (showInfo) StrategicCamera.allowInput = false; UI.SetAlpha(mAlpha); { // Automatically choose the first available trade route if (mSelectedRoute == null || (mSelectedRoute.town0 != this && mSelectedRoute.town1 != this)) { mSelectedRoute = null; foreach (TradeRoute tr in TradeRoute.list) { Town town = tr.GetConnectedTown(this); if (town != null) { mSelectedRoute = tr; break; } } } // Draw the town's UI DrawTownUI(); // If we have a trade route we can draw the trade UI if (mSelectedRoute != null) DrawTradeUI(); // Draw the ship-related UI DrawBuildShipsUI(); DrawFreeShipsUI(); // Cancel all dragging operations on mouse up if (Input.GetMouseButtonUp(0)) CancelDrag(); // Draw the dragged resource DrawIconUI(); // Draw the exit button if (GUI.Button(new Rect(Screen.width * 0.5f - 75.0f, Screen.height - 45.0f, 150.0f, 40.0f), "Return to Game", Config.Instance.skin.button)) { showInfo = false; } } UI.RestoreAlpha(); } }
public void AddTradeRoute(CampaignStation exportStation, CampaignStation importStation, TradeRoute.ResourceType resourceType, int quantity) { TradeRoute tradeRoute = new TradeRoute(); tradeRoute.SetData(exportStation, importStation, resourceType, quantity); _tradeRoutes.Add(tradeRoute); }
public TradeOrders WhatShouldIBuy(Inventory traderInventory, TradeCity currentCity, List <TradeRoute> avaliableTradeRoutes) { int bestProfit = 0; Item bestItem = new Item(); int canAffordOfBestItem = 0; TradeRoute bestRoute = avaliableTradeRoutes[0]; int purchasedPrice = 0; foreach (TradeRoute route in avaliableTradeRoutes) { TradeCity destination = route.CityOne; if (route.CityOne == currentCity) { destination = route.CityToo; } Log("Assesing city:" + destination); foreach (TradeData currentTradeData in currentCity.MarketPlace.TradeDataManifest) { if (currentTradeData.CurrentCost() < traderInventory.currency) { Log("Can Afford " + currentTradeData.ToString()); foreach (TradeData destinationTradeData in destination.MarketPlace.TradeDataManifest) { if (currentTradeData.Item == destinationTradeData.Item) { if (destinationTradeData.CurrentCost() - currentTradeData.CurrentCost() > bestProfit) { Log("Can make a new best profit at :" + (destinationTradeData.CurrentCost() - currentTradeData.CurrentCost()) + " better then :" + bestProfit); bestProfit = destinationTradeData.CurrentCost() - currentTradeData.CurrentCost(); bestItem.Type = currentTradeData.Item; canAffordOfBestItem = traderInventory.currency / currentTradeData.CurrentCost(); bestRoute = route; purchasedPrice = currentTradeData.CurrentCost(); } else { Log("Can not make a new best profit at :" + (destinationTradeData.CurrentCost() - currentTradeData.CurrentCost()) + " worse then :" + bestProfit); } } } } else { Log("Can Not Afford " + currentTradeData.ToString()); } } } List <Item> manifest = new List <Item>(); bestItem.PurchasedPrice = purchasedPrice; manifest.Add(bestItem); TradeOrders tradeOrder = GameObject.FindGameObjectWithTag("GameManager").AddComponent <TradeOrders>(); tradeOrder.Manifests = manifest; tradeOrder.Destination = bestRoute; Log("Decided on " + canAffordOfBestItem + " of " + bestItem.Type + " at " + bestItem.PurchasedPrice + " for a gain of " + bestProfit); return(tradeOrder); }
/// <summary> /// Callback triggered when the player clicks on something. /// </summary> void OnClick (int button) { if (button == 0) { if (mIsValid) { if (mTargetTown != null) { if (mRoute.Connect(mTargetTown)) { // See if there is a duplicate route foreach (TradeRoute tr in TradeRoute.list) { if (tr != mRoute && tr.GetConnectedTown(mRoute.town0) == mRoute.town1) { // Copy the trade path tr.CopyPath(mRoute.path); // Ensure that no towns are still referencing this trade route foreach (Town t in Town.list) t.DisconnectTradeRoute(tr); Object.Destroy(mGO); break; } } // This route has now been created mIsValid = false; mTargetTown = null; mRoute = null; mGO = null; } } else { mRoute.Add(mTargetPos); } } } else if (!mRoute.UndoAdd()) { foreach (Town t in Town.list) t.DisconnectTradeRoute(mRoute); Object.Destroy(mGO); mIsValid = false; mTargetTown = null; mRoute = null; mGO = null; } }
/// <summary> /// Notification of a trade route being removed. /// </summary> public void DisconnectTradeRoute(TradeRoute tr) { if (tr == mSelectedRoute) mSelectedRoute = null; }
private void MakeNewTradeRoutes(TurnInfo thisPlayer) { float tempSystemSI = 0; int chosenEnemySystem = -1, chosenPlayerSystem = -1; string tempOwner = null; for (int i = 0; i < MasterScript.systemListConstructor.systemList.Count; ++i) //For all systems { if (MasterScript.systemListConstructor.systemList[i].systemOwnedBy == null) //If system is not owned ignore it { continue; } if (MasterScript.systemListConstructor.systemList[i].systemOwnedBy == thisPlayer.playerRace) //If system is owned by the player { for (int j = 0; j < MasterScript.systemListConstructor.systemList[i].permanentConnections.Count; ++j) //For all systems connected to this system { int sys = MasterScript.RefreshCurrentSystem(MasterScript.systemListConstructor.systemList[i].permanentConnections[j]); if (MasterScript.systemListConstructor.systemList[sys].systemOwnedBy == null || MasterScript.systemListConstructor.systemList[sys].systemOwnedBy == thisPlayer.playerRace) //If the system is owned by this player or not at all ignore it { continue; } GameObject enemySystem = MasterScript.systemListConstructor.systemList[sys].systemObject; bool routeExists = false; //Say the proposed route between these systems does not exist for (int k = 0; k < allTradeRoutes.Count; ++k) //For all existing trade routes { if ((allTradeRoutes[k].enemySystem == sys && allTradeRoutes[k].playerSystem == i) || (allTradeRoutes[k].playerSystem == sys && allTradeRoutes[k].enemySystem == i)) //Check to see if the proposed one exists { routeExists = true; } } if (routeExists == false) //If the route doesn't exist { systemSIMData = enemySystem.GetComponent <SystemSIMData>(); //Get a reference to the SI output data float temp = systemSIMData.totalSystemPower + systemSIMData.totalSystemKnowledge; //Calculate the system power plus it's knowledge if (temp > tempSystemSI) //If the calculated value is greater than the stored value, this trade route is more valuable than the cached one { tempSystemSI = temp; //So cache this one over it! chosenEnemySystem = sys; chosenPlayerSystem = i; tempOwner = MasterScript.systemListConstructor.systemList[sys].systemOwnedBy; } } } } } if (chosenEnemySystem != -1) { TradeRoute route = new TradeRoute(); route.playerSystem = chosenPlayerSystem; route.enemySystem = chosenEnemySystem; route.connectorObject = MasterScript.uiObjects.CreateConnectionLine(MasterScript.systemListConstructor.systemList[route.playerSystem].systemObject, MasterScript.systemListConstructor.systemList[route.enemySystem].systemObject); route.enemySystemOwner = tempOwner; for (int i = 0; i < MasterScript.turnInfoScript.allPlayers.Count; ++i) { if (MasterScript.turnInfoScript.allPlayers[i].playerRace == tempOwner) { route.enemyPlayer = MasterScript.turnInfoScript.allPlayers[i]; } } allTradeRoutes.Add(route); } }
/// <summary> /// Draws the UI for the current town. /// </summary> void DrawTownUI() { Vector2 mousePos = UI.GetMousePos(); Rect rect = new Rect(Screen.width * 0.5f + 130f, Screen.height * 0.5f - 260f, 292f, 270f); // Allow the opposite town's resources to be dragged straight to this window for simplicity's sake if (mDragResource != -1 && Input.GetMouseButtonUp(0) && rect.Contains(mousePos)) { if (mDragTown == this) mDragTown = null; mSelectedRoute.SetExportedResource(mDragTown, mDragResource); CancelDrag(); } // Draw the resources Rect inner = UI.DrawWindow(rect, name); DrawResources(this, inner); inner.y += inner.height - 40f; inner.height = 40f; if (GUI.Button(inner, "Establish a New Trade Route", Config.Instance.skin.button)) { showInfo = false; TradeRouteCreator.Instance.StartNewTradeRoute(this); } if (mSelectedRoute != null) { rect = new Rect(rect.x, Screen.height * 0.5f + 40f, 292f, 225f); // Allow main town's resources to be dragged straight to this window for simplicity's sake if (mDragResource != -1 && Input.GetMouseButtonUp(0) && rect.Contains(mousePos)) { if (mDragTown != this) mDragTown = null; mSelectedRoute.SetExportedResource(mDragTown, mDragResource); CancelDrag(); } Town town = mSelectedRoute.GetConnectedTown(this); inner = UI.DrawWindow(rect, town.name); // See if we have more than one trade route TradeRoute next = TradeRoute.FindNext(mSelectedRoute, this, true); // Draw trade route navigation buttons if (next != mSelectedRoute) { if (GUI.Button(new Rect(rect.x + 20f, rect.y - 18f, 40f, 40f), "<<", Config.Instance.skin.button)) { mSelectedRoute = next; } else if (GUI.Button(new Rect(rect.x + rect.width - 60f, rect.y - 18f, 40f, 40f), ">>", Config.Instance.skin.button)) { mSelectedRoute = TradeRoute.FindNext(mSelectedRoute, this, false); } } DrawResources(town, inner); } }
public void UnregisterTradeRoute(TradeRoute tradeRoute) { TradeRoutes.Remove(tradeRoute); }
public TradeEditView() { Route = new TradeRoute(); }
public void GenerateTradeRoutePath(TradeRoute tradeRoute) { var city = tradeRoute.City; var oilSlick = tradeRoute.OilExtractor.ExtractedOilSlick; Debug.Log("(" + gameObject.tag + ") Find path between " + city + " <-> " + oilSlick); Node startNode = _cityNodes[city]; Node endNode = _oilSlickNodes[oilSlick]; Queue <Node> candidateNodes = new Queue <Node>(); Dictionary <Node, Node> visitedFrom = new Dictionary <Node, Node> { [startNode] = null }; candidateNodes.Enqueue(startNode); bool foundPath = false; int currentIterations = 0; while (candidateNodes.Count > 0) { currentIterations += 1; Node currentNode = candidateNodes.Dequeue(); if (currentNode.Equals(endNode)) { foundPath = true; break; } foreach (var n in currentNode.Neighbors) { if (!visitedFrom.ContainsKey(n)) { visitedFrom[n] = currentNode; candidateNodes.Enqueue(n); } } } if (!foundPath) { return; } // build the path List <Node> path = new List <Node>(); Node currentPathNode = endNode; currentIterations = 0; while (currentPathNode != null) { currentIterations += 1; path.Add(currentPathNode); currentPathNode = visitedFrom[currentPathNode]; Debug.Log(currentPathNode); } Debug.Log("Found path!"); List <PathManagerEdge> pathManagerEdges = new List <PathManagerEdge>(); GameObject entryWaypoint = null; for (int i = 0; i < path.Count; i++) { var curPathNode = path[i]; var nextPathNode = i < path.Count - 1 ? path[i + 1] : null; if (entryWaypoint == null) { entryWaypoint = curPathNode.Waypoint; } if (nextPathNode == null || curPathNode.PathManager != nextPathNode.PathManager || (curPathNode.PathManager == nextPathNode.PathManager && curPathNode.isLoop && nextPathNode.isLoop)) { pathManagerEdges.Add(new PathManagerEdge() { PathManager = curPathNode.PathManager, EntryWaypoint = entryWaypoint, ExitWaypoint = curPathNode.Waypoint }); entryWaypoint = null; Debug.Log(pathManagerEdges[pathManagerEdges.Count - 1]); } } for (int i = 0; i < pathManagerEdges.Count; i++) { var currentEdge = pathManagerEdges[i]; if (i > 0) { currentEdge.PreviousEdge = pathManagerEdges[i - 1]; } if (i < pathManagerEdges.Count - 1) { currentEdge.NextEdge = pathManagerEdges[i + 1]; } } var tradeRoutePath = tradeRoute.gameObject.AddComponent <TradeRoutePath>(); tradeRoutePath.PathManagerEdges = pathManagerEdges; }