void Awake() { this.inventory = GameManager.GetMainGame().GetComponent <GameInventory>(); this.spriteRenderer = this.GetComponent <SpriteRenderer>(); this.spriteRenderer.sprite = SpriteNormal; this.Rect = this.spriteRenderer.sprite.rect; }
public override void Update(float deltaTime) { GameInventory tileInventory = character.Tile.Inventory; // Current tile is empty if (tileInventory == null) { DebugLog(" - Dumping"); World.Current.InventoryManager.PlaceInventory(character.Tile, character.Inventory); Finished(); return; } // Current tile contains the same type and there is room if (tileInventory.Type == character.Inventory.Type && (tileInventory.StackSize + character.Inventory.StackSize) <= tileInventory.MaxStackSize) { DebugLog(" - Dumping"); World.Current.InventoryManager.PlaceInventory(character.Tile, character.Inventory); Finished(); return; } List <Tile> path = Pathfinder.FindPathToDumpInventory(character.Tile, character.Inventory.Type, character.Inventory.StackSize); if (path != null && path.Count > 0) { character.SetState(new MoveState(character, Pathfinder.GoalTileEvaluator(path.Last(), false), path, this)); } else { DebugLog(" - Can't find any place to dump inventory!"); Finished(); } }
public bool PlaceInventory(Tile tile, GameInventory inventory) { bool tileWasEmpty = tile.Inventory == null; if (tile.PlaceInventory(inventory) == false) { // The tile did not accept the inventory for whatever reason, therefore stop. return(false); // TODO: Geoffrotism. Is this where we would hook in to handle inventory not being able to be placed in a tile. } CleanupInventory(inventory); // We may also have to create a new stack on the tile, if the startTile was previously empty. if (tileWasEmpty) { if (Inventories.ContainsKey(tile.Inventory.Type) == false) { Inventories[tile.Inventory.Type] = new List <GameInventory>(); } Inventories[tile.Inventory.Type].Add(tile.Inventory); InvokeInventoryCreated(tile.Inventory); } return(true); }
private void CreateButtonComponents(GameObject go, GameInventory inventory, int[] amounts) { foreach (int amount in amounts) { GameObject button_go = new GameObject(); button_go.name = "Button"; button_go.layer = LayerMask.NameToLayer("UI"); button_go.AddComponent <Image>(); RectTransform rectTransform = button_go.GetComponent <RectTransform>(); rectTransform.SetParent(go.transform); Button button = button_go.AddComponent <Button>(); CreateTextComponent(button_go, amount.ToString(), TextAnchor.MiddleCenter); LayoutElement layoutElement = button_go.AddComponent <LayoutElement>(); layoutElement.minWidth = 20; layoutElement.minHeight = 20; int localAmount = amount; button.onClick.AddListener( () => OnButtonClick(inventory.Type, localAmount)); } }
public void ReevaluateWaitingQueue(GameInventory inv) { DebugLog("ReevaluateWaitingQueue() new resource: {0}, count: {1}", inv.Type, inv.StackSize); List <Job> waitingJobs = null; // Check that there is a job waiting for this inventory. if (jobsWaitingForInventory.ContainsKey(inv.Type) && jobsWaitingForInventory[inv.Type].Count > 0) { // Get the current list of jobs waitingJobs = jobsWaitingForInventory[inv.Type]; // Replace it with an empty list jobsWaitingForInventory[inv.Type] = new List <Job>(); foreach (Job job in waitingJobs) { // Enqueue will put them in the new waiting list we created if they still have unmet needs Enqueue(job); } } // Do the same thing for the AnyMaterial jobs if (jobsWaitingForInventory.ContainsKey("*")) { waitingJobs = jobsWaitingForInventory["*"]; jobsWaitingForInventory["*"] = new List <Job>(); foreach (Job job in waitingJobs) { Enqueue(job); } } }
public bool PlaceInventory(Job job, GameCharacter character) { GameInventory sourceInventory = character.Inventory; // Check that it's wanted by the job if (job.RequestedItems.ContainsKey(sourceInventory.Type) == false) { UnityDebugger.Debugger.LogError(InventoryManagerLogChanel, "Trying to add inventory to a job that it doesn't want."); return(false); } // Check that there is a target to transfer to if (job.DeliveredItems.ContainsKey(sourceInventory.Type) == false) { job.DeliveredItems[sourceInventory.Type] = new GameInventory(sourceInventory.Type, 0, sourceInventory.MaxStackSize); } GameInventory targetInventory = job.DeliveredItems[sourceInventory.Type]; int transferAmount = Mathf.Min(targetInventory.MaxStackSize - targetInventory.StackSize, sourceInventory.StackSize); sourceInventory.StackSize -= transferAmount; targetInventory.StackSize += transferAmount; CleanupInventory(character); return(true); }
// // METHODS // void Awake() { controller = GetComponent <GameController>(); audioController = GetComponent <AudioController>(); gameInventory = GetComponent <GameInventory>(); }
// Use this for initialization void Start() { #if UNITY_ANDROID //this.IsMouseEnabled = false; #endif this.gameManager = GameManager.GetMainGame().GetComponent <GameManager>(); this.inventory = gameManager.GetComponent <GameInventory>(); }
public int AmountNeeded(GameInventory inventory = null) { if (inventory == null || inventory.Type != Type) { return(MinAmountRequested); } return(Mathf.Max(MinAmountRequested - inventory.StackSize, 0)); }
void Start() { this.game = GameManager.GetMainGame(); this.controls = game.GetComponent <ControlsManager>(); this.inventory = game.GetComponent <GameInventory>(); this.render = this.GetComponent <ItemRender>(); this.itemCountManager = this.GetComponent <ItemCount>(); }
public int AmountDesired(GameInventory inventory = null) { if (inventory == null || inventory.Type != Type) { return(MaxAmountRequested); } return(MaxAmountRequested - inventory.StackSize); }
public bool PlaceInventoryAround(Tile tile, GameInventory inventory, int radius = 3) { tile = GetFirstTileWithValidInventoryPlacement(radius, tile, inventory); if (tile == null) { return(false); } return(PlaceInventory(tile, inventory)); }
public int AmountDesiredOfInventoryType(string type) { if (RequestedItems.ContainsKey(type) == false) { return(0); } GameInventory inventory = DeliveredItems.ContainsKey(type) ? DeliveredItems[type] : null; return(RequestedItems[type].AmountDesired(inventory)); }
private void InvokeInventoryCreated(GameInventory inventory) { Action <GameInventory> handler = InventoryCreated; if (handler != null) { handler(inventory); // Let the JobQueue know there is new inventory available. World.Current.jobQueue.ReevaluateReachability(); } }
public static bool CanBePickedUp(GameInventory inventory, bool canTakeFromStockpile) { // You can't pick up stuff that isn't on a tile or if it's locked if (inventory == null || inventory.Tile == null || inventory.Locked) { return(false); } Furniture furniture = inventory.Tile.Furniture; return(furniture == null || canTakeFromStockpile == true || furniture.HasTypeTag("Storage") == false); }
public RequestedItem GetFirstDesiredItem() { foreach (RequestedItem item in RequestedItems.Values) { GameInventory inventory = DeliveredItems.ContainsKey(item.Type) ? DeliveredItems[item.Type] : null; if (item.DesiresMore(inventory)) { return(item); } } return(null); }
public void FromJson(JToken inventoriesToken) { JArray inventoriesJArray = (JArray)inventoriesToken; foreach (JToken inventoryToken in inventoriesJArray) { int x = (int)inventoryToken["X"]; int y = (int)inventoryToken["Y"]; int z = (int)inventoryToken["Z"]; GameInventory inventory = new GameInventory(); inventory.FromJson(inventoryToken); PlaceInventory(World.Current.GetTileAt(x, y, z), inventory); } }
/// <summary> /// Create a random Trader out of this TraderPrototype. /// </summary> public Trader CreateTrader() { Currency curency = PrototypeManager.Currency.Get(CurrencyName).Clone(); curency.Balance = Random.Range(MinCurrencyBalance, MaxCurrencyBalance); Trader t = new Trader { Currency = curency, Name = PotentialNames[Random.Range(0, PotentialNames.Count - 1)], SaleMarginMultiplier = Random.Range(MinSaleMarginMultiplier, MaxSaleMarginMultiplier), Stock = new List <GameInventory>() }; foreach (TraderPotentialInventory potentialStock in PotentialStock) { bool itemIsInStock = Random.Range(0f, 1f) > potentialStock.Rarity; if (itemIsInStock) { if (!string.IsNullOrEmpty(potentialStock.Type)) { GameInventory inventory = new GameInventory( potentialStock.Type, Random.Range(potentialStock.MinQuantity, potentialStock.MaxQuantity)); t.Stock.Add(inventory); } else if (!string.IsNullOrEmpty(potentialStock.Category)) { List <GameInventory> potentialObjects = GetInventoryCommonWithCategory(potentialStock.Category); foreach (GameInventory potentialObject in potentialObjects) { GameInventory inventory = new GameInventory( potentialObject.Type, Random.Range(potentialStock.MinQuantity, potentialStock.MaxQuantity)); t.Stock.Add(inventory); } } } } return(t); }
static void OnInventoryChanged(BindableObject bindable, object oldValue, object newValue) { GameInventoryView view = bindable as GameInventoryView; GameInventory inv = newValue as GameInventory; view.mainLayout.Children.Clear(); if (inv != null && inv.Items.Count() != 0) { foreach (var item in inv.Items) { if (!view.ShowEmpty && item.Count == 0) { continue; } if (!view.ShowNoneEffect && item.EffectType == GameItem.Effect.None) { continue; } TapGestureRecognizer tgr = new TapGestureRecognizer { NumberOfTapsRequired = 1 }; tgr.Tapped += view.OnItemTapped; view.mainLayout.Children.Add( new GameItemView { Item = item, GestureRecognizers = { tgr } }); } } if (view.mainLayout.Children.Count == 0) { view.mainLayout.Children.Add( new Label { Text = "No items" }); } }
/// <summary> /// Once a trade is completed (and the trade dialog box is close): /// - spawn bougth inventory in a square of 6x6 around the tradingCoordinate (tile of the landing pad) /// - delete all sold inventory from stockpiles. /// </summary> private void TrasfertTradedItems(Trade trade, Vector3 tradingCoordinates) { trade.Player.Currency.Balance += trade.TradeCurrencyBalanceForPlayer; foreach (TradeItem tradeItem in trade.TradeItems) { if (tradeItem.TradeAmount > 0) { Tile tile = World.Current.GetTileAt((int)tradingCoordinates.x, (int)tradingCoordinates.y, (int)tradingCoordinates.z); GameInventory inv = new GameInventory(tradeItem.Type, tradeItem.TradeAmount, tradeItem.TradeAmount); World.Current.InventoryManager.PlaceInventoryAround(tile, inv, 6); } else if (tradeItem.TradeAmount < 0) { World.Current.InventoryManager.RemoveInventoryOfType(tradeItem.Type, -tradeItem.TradeAmount, true); } } }
private void CleanupInventory(GameInventory inventory) { if (inventory.StackSize != 0) { return; } if (Inventories.ContainsKey(inventory.Type)) { Inventories[inventory.Type].Remove(inventory); } if (inventory.Tile != null) { inventory.Tile.Inventory = null; inventory.Tile = null; } }
internal static void SortJob(ref Job job, CarLoader carLoader) { if (currentProfile != ProfileManager.Get().GetSelectedProfile()) { currentProfile = ProfileManager.Get().GetSelectedProfile(); sortedJobs.Clear(); } if (!sortedJobs.Contains(job.id)) { foreach (JobPart jobPart in job.jobParts) { Dictionary <string, int> partDict = new Dictionary <string, int>(); //Store the existing order for (int i = 0; i < jobPart.partsCount; i++) { partDict.Add(jobPart.partList[i], i); } List <string> sorted = new List <string>(); //Sort them by the display name if (jobPart.type != "Body") { sorted = (from p in jobPart.partList orderby GameInventory.Get().GetItemLocalizeName(p.Substring(p.LastIndexOf('/') + 1)) select p).ToList(); } else { sorted = (from p in jobPart.partList orderby GameInventory.Get().GetBodyLocalizedName(carLoader.carToLoad + "-" + carLoader.GetDefaultName(p.Substring(p.LastIndexOf('/') + 1))) select p).ToList(); } jobPart.partList = sorted; } sortedJobs.Add(job.id); } }
public void SpawnInventory(Tile t) { // If the user clicks outside the game area t may be null. if (t == null) { return; } GameInventory inventoryChange = new GameInventory(InventoryToBuild, AmountToCreate); // You can't spawn on occupied tiles if (t.Furniture != null) { return; } if (t.Inventory == null || t.Inventory.Type == InventoryToBuild) { World.Current.InventoryManager.PlaceInventory(t, inventoryChange); } }
public bool PlaceInventory(GameInventory inventory) { if (inventory == null) { Inventory = null; return(true); } if (Inventory != null) { // There's already inventory here. Maybe we can combine a stack? if (Inventory.Type != inventory.Type) { UnityDebugger.Debugger.LogError("Tile", "Trying to assign inventory to a tile that already has some of a different type."); return(false); } int numToMove = inventory.StackSize; if (Inventory.StackSize + numToMove > Inventory.MaxStackSize) { numToMove = Inventory.MaxStackSize - Inventory.StackSize; } Inventory.StackSize += numToMove; inventory.StackSize -= numToMove; return(true); } // At this point, we know that our current inventory is actually // null. Now we can't just do a direct assignment, because // the inventory manager needs to know that the old stack is now // empty and has to be removed from the previous lists. Inventory = inventory.Clone(); Inventory.Tile = this; inventory.StackSize = 0; return(true); }
public bool PlaceInventory(GameCharacter character, GameInventory sourceInventory, int amount = -1) { amount = amount < 0 ? sourceInventory.StackSize : Math.Min(amount, sourceInventory.StackSize); sourceInventory.ReleaseClaim(character); if (character.Inventory == null) { character.Inventory = sourceInventory.Clone(); character.Inventory.StackSize = 0; if (Inventories.ContainsKey(character.Inventory.Type) == false) { Inventories[character.Inventory.Type] = new List <GameInventory>(); } Inventories[character.Inventory.Type].Add(character.Inventory); } else if (character.Inventory.Type != sourceInventory.Type) { UnityDebugger.Debugger.LogError(InventoryManagerLogChanel, "Character is trying to pick up a mismatched inventory object type."); return(false); } character.Inventory.StackSize += amount; if (character.Inventory.MaxStackSize < character.Inventory.StackSize) { sourceInventory.StackSize = character.Inventory.StackSize - character.Inventory.MaxStackSize; character.Inventory.StackSize = character.Inventory.MaxStackSize; } else { sourceInventory.StackSize -= amount; } CleanupInventory(sourceInventory); return(true); }
private HaulAction NextAction() { GameInventory tileInventory = character.Tile.Inventory; bool jobWantsTileInventory = InventoryManager.CanBePickedUp(tileInventory, Job.canTakeFromStockpile) && Job.AmountDesiredOfInventoryType(tileInventory.Type) > 0; if (noMoreMaterialFound && character.Inventory != null) { return(Job.IsTileAtJobSite(character.Tile) ? HaulAction.DropOffmaterial : HaulAction.DeliverMaterial); } else if (character.Inventory != null && Job.AmountDesiredOfInventoryType(character.Inventory.Type) == 0) { return(HaulAction.DumpMaterial); } else if (character.Inventory == null) { return(jobWantsTileInventory ? HaulAction.PickupMaterial : HaulAction.FindMaterial); } else { int amountWanted = Job.AmountDesiredOfInventoryType(character.Inventory.Type); int currentlyCarrying = character.Inventory.StackSize; int spaceAvailable = character.Inventory.MaxStackSize - currentlyCarrying; // Already carrying it if (amountWanted <= currentlyCarrying || spaceAvailable == 0) { return(Job.IsTileAtJobSite(character.Tile) ? HaulAction.DropOffmaterial : HaulAction.DeliverMaterial); } else { // Can carry more and want more return(jobWantsTileInventory ? HaulAction.PickupMaterial : HaulAction.FindMaterial); } } }
private void Start() { this.Inventory = GetComponent <GameInventory>(); }
/// <summary> /// Reads the prototype furniture from XML. /// </summary> /// <param name="readerParent">The XML reader to read from.</param> public void ReadXmlPrototype(XmlReader readerParent) { Type = readerParent.GetAttribute("type"); XmlReader reader = readerParent.ReadSubtree(); while (reader.Read()) { switch (reader.Name) { case "TypeTag": reader.Read(); typeTags.Add(reader.ReadContentAsString()); break; case "MovementCost": reader.Read(); MovementCost = reader.ReadContentAsFloat(); break; case "PathfindingModifier": reader.Read(); PathfindingModifier = reader.ReadContentAsFloat(); break; case "PathfindingWeight": reader.Read(); PathfindingWeight = reader.ReadContentAsFloat(); break; case "Width": reader.Read(); Width = reader.ReadContentAsInt(); break; case "Height": reader.Read(); Height = reader.ReadContentAsInt(); break; case "Health": reader.Read(); health = new HealthSystem(reader.ReadContentAsFloat(), false, true, false, false); break; case "LinksToNeighbours": reader.Read(); LinksToNeighbour = reader.ReadContentAsString(); break; case "EnclosesRooms": reader.Read(); RoomEnclosure = reader.ReadContentAsBoolean(); break; case "CanReplaceFurniture": replaceableFurniture.Add(reader.GetAttribute("typeTag").ToString()); break; case "CanRotate": reader.Read(); CanRotate = reader.ReadContentAsBoolean(); break; case "DragType": reader.Read(); DragType = reader.ReadContentAsString(); break; case "CanBeBuiltOn": tileTypeBuildPermissions.Add(reader.GetAttribute("tileType")); break; case "Animations": XmlReader animationReader = reader.ReadSubtree(); ReadAnimationXml(animationReader); break; case "Action": XmlReader subtree = reader.ReadSubtree(); EventActions.ReadXml(subtree); subtree.Close(); break; case "ContextMenuAction": contextMenuLuaActions.Add(new ContextMenuLuaAction { LuaFunction = reader.GetAttribute("FunctionName"), LocalizationKey = reader.GetAttribute("LocalizationKey"), RequireCharacterSelected = bool.Parse(reader.GetAttribute("RequireCharacterSelected")), DevModeOnly = bool.Parse(reader.GetAttribute("DevModeOnly") ?? "false") }); break; case "IsEnterable": isEnterableAction = reader.GetAttribute("FunctionName"); break; case "GetProgressInfo": getProgressInfoNameAction = reader.GetAttribute("functionName"); break; case "JobWorkSpotOffset": Jobs.ReadWorkSpotOffset(reader); break; case "JobInputSpotOffset": Jobs.ReadInputSpotOffset(reader); break; case "JobOutputSpotOffset": Jobs.ReadOutputSpotOffset(reader); break; case "Params": ReadXmlParams(reader); // Read in the Param tag break; case "LocalizationCode": reader.Read(); LocalizationCode = reader.ReadContentAsString(); break; case "UnlocalizedDescription": reader.Read(); UnlocalizedDescription = reader.ReadContentAsString(); break; case "Component": BuildableComponent component = BuildableComponent.Deserialize(reader); if (component != null) { component.InitializePrototype(this); buildComponents.Add(component); } break; case "OrderAction": OrderAction orderAction = OrderAction.Deserialize(reader); if (orderAction != null) { orderActions[orderAction.Type] = orderAction; } break; } } if (orderActions.ContainsKey("Uninstall")) { GameInventory asInventory = GameInventory.CreatePrototype(Type, 1, 0f, "crated_furniture", LocalizationCode, UnlocalizedDescription); PrototypeManager.Inventory.Add(asInventory); } }
public override void Update(float deltaTime) { List <Tile> path = null; HaulAction nextAction = NextAction(); DebugLog(" - next action: {0}", nextAction); switch (nextAction) { case HaulAction.DumpMaterial: character.SetState(new DumpState(character, this)); break; case HaulAction.FindMaterial: // Find material somewhere string[] inventoryTypes = character.Inventory != null ? new string[] { character.Inventory.Type } : Job.RequestedItems.Keys.ToArray(); path = World.Current.InventoryManager.GetPathToClosestInventoryOfType(inventoryTypes, character.Tile, Job.canTakeFromStockpile); if (path != null && path.Count > 0) { GameInventory inv = path.Last().Inventory; inv.Claim(character, (inv.AvailableInventory < Job.RequestedItems[inv.Type].AmountDesired()) ? inv.AvailableInventory : Job.RequestedItems[inv.Type].AmountDesired()); character.SetState(new MoveState(character, Pathfinder.GoalTileEvaluator(path.Last(), false), path, this)); } else if (character.Inventory == null) { // The character has no inventory and can't find anything to haul. Interrupt(); DebugLog(" - Nothing to haul"); Finished(); } else { noMoreMaterialFound = true; } break; case HaulAction.PickupMaterial: GameInventory tileInventory = character.Tile.Inventory; int amountCarried = character.Inventory != null ? character.Inventory.StackSize : 0; int amount = Mathf.Min(Job.AmountDesiredOfInventoryType(tileInventory.Type) - amountCarried, tileInventory.StackSize); DebugLog(" - Picked up {0} {1}", amount, tileInventory.Type); World.Current.InventoryManager.PlaceInventory(character, tileInventory, amount); break; case HaulAction.DeliverMaterial: path = Pathfinder.FindPath(character.Tile, Job.IsTileAtJobSite, Pathfinder.DefaultDistanceHeuristic(Job.tile)); if (path != null && path.Count > 0) { character.SetState(new MoveState(character, Pathfinder.GoalTileEvaluator(path.Last(), false), path, this)); } else { Job.AddCharCantReach(character); character.InterruptState(); } break; case HaulAction.DropOffmaterial: DebugLog(" - Delivering {0} {1}", character.Inventory.StackSize, character.Inventory.Type); World.Current.InventoryManager.PlaceInventory(Job, character); // Ping the Job system Job.DoWork(0); Finished(); break; } }
public Tile GetFirstTileWithValidInventoryPlacement(int maxOffset, Tile inTile, GameInventory inv) { for (int offset = 0; offset <= maxOffset; offset++) { int offsetX = 0; int offsetY = 0; Tile tile; // searching top & bottom line of the square for (offsetX = -offset; offsetX <= offset; offsetX++) { offsetY = offset; tile = World.Current.GetTileAt(inTile.X + offsetX, inTile.Y + offsetY, inTile.Z); if (CanPlaceInventoryAt(tile, inv)) { return(tile); } offsetY = -offset; tile = World.Current.GetTileAt(inTile.X + offsetX, inTile.Y + offsetY, inTile.Z); if (CanPlaceInventoryAt(tile, inv)) { return(tile); } } // searching left & right line of the square for (offsetY = -offset; offsetY <= offset; offsetY++) { offsetX = offset; tile = World.Current.GetTileAt(inTile.X + offsetX, inTile.Y + offsetY, inTile.Z); if (CanPlaceInventoryAt(tile, inv)) { return(tile); } offsetX = -offset; tile = World.Current.GetTileAt(inTile.X + offsetX, inTile.Y + offsetY, inTile.Z); if (CanPlaceInventoryAt(tile, inv)) { return(tile); } } } return(null); }