Refactor crafting logic in Inventory class; improve resource checks and fit calculations
This commit is contained in:
+17
-11
@@ -113,24 +113,30 @@ class Inventory
|
|||||||
|
|
||||||
recipe = CRAFT_RECIPES[type]
|
recipe = CRAFT_RECIPES[type]
|
||||||
|
|
||||||
# How many we can craft
|
# How many we can craft based on resources
|
||||||
possible_counts = recipe.map { |res, req| grid_value(res) / req }
|
resource_max = recipe.map { |res, req| grid_value(res) / req }.min
|
||||||
max_possible = possible_counts.min
|
return if resource_max == 0
|
||||||
return if max_possible == 0
|
|
||||||
|
|
||||||
craft_amount = ctrl ? max_possible : 1
|
# How many we can fit in inventory slot
|
||||||
|
row, col = find_slot(type)
|
||||||
|
return unless row # sanity check
|
||||||
|
|
||||||
|
slot_amount, slot_max = @grid[row][col][1]
|
||||||
|
fit_max = slot_max - slot_amount
|
||||||
|
return if fit_max == 0 # can't fit anything
|
||||||
|
|
||||||
|
# Determine craft amount (1 or as many as possible)
|
||||||
|
craft_amount = ctrl ? [resource_max, fit_max].min : 1
|
||||||
|
return if craft_amount == 0 # nothing to craft
|
||||||
|
|
||||||
# Subtract resources
|
# Subtract resources
|
||||||
recipe.each do |res, req|
|
recipe.each do |res, req|
|
||||||
row, col = find_slot(res)
|
r, c = find_slot(res)
|
||||||
@grid[row][col][1][0] -= req * craft_amount
|
@grid[r][c][1][0] -= req * craft_amount
|
||||||
end
|
end
|
||||||
|
|
||||||
# Add crafted item
|
# Add crafted items
|
||||||
row, col = find_slot(type)
|
|
||||||
@grid[row][col][1][0] += craft_amount
|
@grid[row][col][1][0] += craft_amount
|
||||||
# Clamp to max
|
|
||||||
@grid[row][col][1][0] = @grid[row][col][1][1] if @grid[row][col][1][0] > @grid[row][col][1][1]
|
|
||||||
end
|
end
|
||||||
|
|
||||||
# Helper to get amount of resource
|
# Helper to get amount of resource
|
||||||
|
|||||||
Reference in New Issue
Block a user