Add CraftingPlan to compute resource requirements

This commit is contained in:
Andrew Miner
2015-09-27 13:57:21 -07:00
parent de04c79d17
commit 74e95e614b
16 changed files with 280 additions and 434 deletions
@@ -71,7 +71,7 @@ module.exports = class FullRecipeController extends BaseController
inputs.clear()
if @model?
@model.eachInputStack (stack)->
for stack in @model.input
inputs.add stack.itemSlug, stack.quantity
+42 -48
View File
@@ -32,13 +32,13 @@ module.exports = class CraftingNode
# Public Methods ###############################################################################
expand: (queue=[])->
return unless @valid
return queue if @children.length > 0
for child in @_createChildren()
child.parent = this
if child.valid
@_children.push child
queue.push child
@_children.push child
queue.push child
return queue
acceptVisitor: (visitor)->
@@ -65,52 +65,46 @@ module.exports = class CraftingNode
# Property Methods #############################################################################
getChildren: ->
return @_children
isComplete: ->
if not @_complete?
@_complete = @_checkCompleteness()
return @_complete
getCompleteText: ->
return if @complete then "" else ""
getDepth: ->
maxDepth = 1
for child in @children
maxDepth = Math.max maxDepth, child.getDepth() + 1
return maxDepth
getId: ->
return @_id
getRotations: ->
return @_rotations
getSize: ->
size = 1
for child in @children
size += child.size
return size
isValid: ->
return @_valid if @_valid?
valid = @_checkValidity()
@_valid = false if not valid
return valid
Object.defineProperties @prototype,
children: { get:@prototype.getChildren }
complete: { get:@prototype.isComplete }
completeText: { get:@prototype.getCompleteText }
depth: { get:@prototype.getDepth }
id: { get:@prototype.getId }
rotations: { get:@prototype.getRotations }
size: { get:@prototype.getSize }
valid: { get:@prototype.isValid }
children:
get: -> return @_children
complete:
get: ->
if not @_complete?
@_complete = @_checkCompleteness()
return @_complete
completeText:
get: -> if @complete then "◼︎" else "◻︎"
depth:
get: ->
maxDepth = 1
for child in @children
maxDepth = Math.max maxDepth, child.depth + 1
return maxDepth
id:
get: -> return @_id
rotations:
get: -> return @_rotations
size:
get: ->
size = 1
for child in @children
size += child.size
return size
valid:
get: -> @_checkValidity()
validText:
get: -> if @valid then "" else ""
# Virtual Methods ##############################################################################
+39 -30
View File
@@ -39,12 +39,24 @@ module.exports = class CraftingPlan
# Object Overrides #############################################################################
toString: ->
return "#{@constructor.name}{
wanted:#{@wanted},
required:#{@required},
steps:[#{(step.toString() for step in @steps).join(',')}],
produced:#{@produced}
}"
result = ["To Make:"]
@_wanted.each (stack)->
result.push " #{stack}"
result.push "Start with:"
@_required.each (stack)->
result.push " #{stack}"
result.push "Use these recipes:"
for step in @_steps
result.push " #{step}"
result.push "To produce:"
@_produced.each (stack)->
result.push " #{stack}"
return result.join '\n'
# Private Methods ##############################################################################
@@ -52,35 +64,32 @@ module.exports = class CraftingPlan
@_required.addInventory @_wanted
for i in [@_steps.length-1..0] by -1
recipe = @_steps[i]
step = @_steps[i]
for stack in recipe.output
for stack in step.recipe.output
while @_required.quantityOf(stack.itemSlug) > 0
@_executeRecipe recipe
@_executeStep step
@_produced.addInventory @_wanted
_executeRecipe: (recipe)->
#console.log "executing: #{recipe}"
_executeStep: (step)->
step.repeat += 1
recipe = step.recipe
for stack in recipe.input
@_use stack
available = @_produced.quantityOf stack.itemSlug
required = recipe.getQuantityRequired stack.itemSlug
consumed = Math.min required, available
deficit = required - consumed
@_produced.remove stack.itemSlug, consumed
@_required.add stack.itemSlug, deficit
for stack in recipe.output
@_produce stack
deficit = @_required.quantityOf stack.itemSlug
created = recipe.getQuantityProduced stack.itemSlug
replenished = Math.min deficit, created
surplus = created - replenished
_produce: (stack)->
deficit = @_required.quantityOf stack.itemSlug
replenished = Math.min deficit, stack.quantity
surplus = stack.quantity - replenished
#console.log "producing #{stack.itemSlug}, surplus: #{surplus}, replenished:#{replenished}"
@_produced.add stack.itemSlug, surplus
@_required.remove stack.itemSlug, replenished
_use: (stack)->
available = @_produced.quantityOf stack.itemSlug
consumed = Math.min stack.quantity, available
deficit = stack.quantity - consumed
#console.log "using #{stack.itemSlug}, consumed: #{consumed}, deficit:#{deficit}"
@_produced.remove stack.itemSlug, consumed
@_required.add stack.itemSlug, deficit
@_produced.add stack.itemSlug, surplus
@_required.remove stack.itemSlug, replenished
@@ -0,0 +1,29 @@
###
Crafting Guide - crafting_step.coffee
Copyright (c) 2015 by Redwood Labs
All rights reserved.
###
########################################################################################################################
module.exports = class CraftingStep
constructor: (recipe, repeat=0)->
if not recipe? then throw new Error 'recipe is required'
if repeat < 0 then throw new Error 'repeat must be at least 1'
@_recipe = recipe
@repeat = repeat
# Property Methods #############################################################################
Object.defineProperties @prototype,
recipe:
get: -> @_recipe
# Object Overrides #############################################################################
toString: ->
return "#{@repeat}x #{@recipe.slug}"
+16 -19
View File
@@ -44,26 +44,23 @@ module.exports = class GraphBuilder
# Property Methods #############################################################################
isComplete: ->
return false unless @_rootNode?
return false unless @_queue?
return false unless @_queue.length is 0
return true
getRootNode: ->
return @_rootNode
getStepCount: ->
return @_stepCount
getWanted: ->
return @_wanted
Object.defineProperties @prototype,
complete: { get:@prototype.isComplete }
rootNode: { get:@prototype.getRootNode }
stepCount: { get:@prototype.getStepCount }
wanted: { get:@prototype.getWanted }
complete:
get: ->
return false unless @_rootNode?
return false unless @_queue?
return false unless @_queue.length is 0
return true
rootNode:
get: -> @_rootNode
stepCount:
get: -> @_stepCount
wanted:
get: -> @_wanted
# Object Overrides ############################################################################
@@ -33,12 +33,12 @@ module.exports = class InventoryNode extends CraftingNode
_checkCompleteness: ->
for child in @children
return false unless child.isComplete
return false unless child.complete
return true
_checkValidity: ->
for child in @children
return false unless child.isValid
return false unless child.valid
return true
# Object Overrides #############################################################################
@@ -47,8 +47,7 @@ module.exports = class InventoryNode extends CraftingNode
options.indent ?= ''
options.recursive ?= true
completeText = if @complete then 'complete' else 'incomplete'
parts = ["#{options.indent}#{@completeText} InventoryNode for #{@inventory}"]
parts = ["#{options.indent}#{@completeText} #{@validText} InventoryNode for #{@inventory}"]
nextIndent = options.indent + ' '
if options.recursive
for child in @children
+7 -5
View File
@@ -46,7 +46,10 @@ module.exports = class ItemNode extends CraftingNode
return [] unless recipes.length > 0
for recipe in recipes
result.push new RecipeNode modPack:@modPack, recipe:recipe
child = new RecipeNode modPack:@modPack, recipe:recipe
child.parent = this
if child.valid
result.push child
return result
@@ -55,13 +58,13 @@ module.exports = class ItemNode extends CraftingNode
return false unless @children?
for child in @children
return true if child.isComplete
return true if child.complete
return false
_checkValidity: ->
return true unless @children.length > 0
for child in @children
return true if child.isValid
return true if child.valid
return false
# Object Overrides #############################################################################
@@ -70,8 +73,7 @@ module.exports = class ItemNode extends CraftingNode
options.indent ?= ''
options.recursive ?= true
completeText = if @complete then 'complete' else 'incomplete'
parts = ["#{options.indent}#{@completeText} ItemNode for #{@item.name}"]
parts = ["#{options.indent}#{@completeText} #{@validText} ItemNode for #{@item.name}"]
nextIndent = options.indent + ' '
if options.recursive
for child in @children
+35 -20
View File
@@ -7,6 +7,7 @@ All rights reserved.
CraftingNode = require './crafting_node'
CraftingPlan = require './crafting_plan'
CraftingStep = require './crafting_step'
Inventory = require '../inventory'
########################################################################################################################
@@ -30,37 +31,34 @@ module.exports = class PlanBuilder
producePlans: (maxPlans=null)->
maxPlans = if maxPlans then @plans.length + maxPlans else Number.MAX_VALUE
while @plans.length is 0 or (@plans.length < maxPlans and not @complete)
while not @complete and (@plans.length < maxPlans)
plan = @_captureCurrentPlan()
@plans.push plan
if plan?
@plans.push plan
@_incrementChoiceNodes()
return @_plans
# Property Methods #############################################################################
isComplete: ->
return @_complete
getPlans: ->
return @_plans
getWanted: ->
return @_wanted
setWanted: (wanted)->
@_wanted = wanted or new Inventory
Object.defineProperties @prototype,
complete: { get:@prototype.isComplete }
plans: { get:@prototype.getPlans }
wanted: { get:@prototype.getWanted, set:@prototype.setWanted }
complete:
get: -> @_complete
plans:
get: -> @_plans
wanted:
get: -> @_wanted
set: (wanted)-> @_wanted = wanted or new Inventory
# Private Methods ##############################################################################
_captureCurrentPlan: ->
toVisit = [@_rootNode]
steps = []
stepNodes = []
while toVisit.length > 0
node = toVisit.shift()
@@ -70,14 +68,31 @@ module.exports = class PlanBuilder
else if node.TYPE is CraftingNode::TYPES.ITEM
toVisit.push node.children[0] if node.children.length > 0
else if node.TYPE is CraftingNode::TYPES.RECIPE
steps.push node.recipe
stepNodes.push node
toVisit.push(c) for c in node.children
steps.reverse()
steps = []
seenRecipes = {}
index = stepNodes.length - 1
while index >= 0
node = stepNodes[index]
index -= 1
return null unless node.valid and node.complete
recipeSlug = node.recipe.slug
continue if seenRecipes[recipeSlug]?
seenRecipes[recipeSlug] = true
steps.push new CraftingStep node.recipe
plan = new CraftingPlan steps, @_wanted
return plan
_incrementChoiceNodes: ->
if @_choiceNodes.length is 0
@_complete = true
return
index = @_choiceNodes.length - 1
while true
if index is -1
@@ -34,14 +34,15 @@ module.exports = class RecipeNode extends CraftingNode
_checkCompleteness: ->
for child in @children
return false unless child.isComplete
return false unless child.complete
return true
_checkValidity: ->
for child in @children
return false unless child.isValid
return false if @_isRepeatedRecipe()
for child in @children
return false unless child.valid
return true
# Private Methods ##############################################################################
@@ -60,8 +61,7 @@ module.exports = class RecipeNode extends CraftingNode
options.indent ?= ''
options.recursive ?= true
completeText = if @complete then 'complete' else 'incomplete'
parts = ["#{options.indent}#{@completeText} RecipeNode for #{@recipe.slug}"]
parts = ["#{options.indent}#{@completeText} #{@validText} RecipeNode for #{@recipe.slug}"]
nextIndent = options.indent + ' '
if options.recursive
for child in @children
-233
View File
@@ -1,233 +0,0 @@
###
Crafting Guide - crafting_plan.coffee
Copyright (c) 2014-2015 by Redwood Labs
All rights reserved.
###
BaseModel = require './base_model'
Inventory = require './inventory'
ItemSlug = require './item_slug'
Step = require './step'
_ = require 'underscore'
{Event} = require '../constants'
########################################################################################################################
module.exports = class CraftingPlan extends BaseModel
constructor: (attributes={}, options={})->
if not attributes.modPack then throw new Error 'modPack is required'
attributes.includingTools ?= false
super attributes, options
@have = new Inventory modPack:@modPack
@want = new Inventory modPack:@modPack
@need = new Inventory modPack:@modPack
@result = new Inventory modPack:@modPack
recraft = _.debounce (=> @craft()), 100
for inventory in [@have, @want]
inventory.on Event.change, recraft
@on Event.change + ':includingTools', recraft
@clear()
# Public Methods ###############################################################################
clear: (options={})->
@steps = []
@need.clear()
@result.clear()
@trigger 'change', this
return this
craft: ->
toolsMessage = if @includingTools then ' (including tools)' else ''
haveMessage = if @have.isEmpty then '' else " starting with #{@have.unparse()}"
logger.info => "crafting #{@want.unparse()}#{toolsMessage}#{haveMessage}"
@clear()
@have.localize()
@want.localize()
@result.addInventory @have
@steps = {}
@want.each (stack)=>
@_findSteps stack.itemSlug, {}, ignoreGatherable:true
item = @modPack.findItem stack.itemSlug
@need.add item.slug, stack.quantity
@steps = (step for recipeSlug, step of @steps)
@_resolveNeeds()
@_removeExtraSteps()
@result.addInventory @want
@need.trigger 'change', @need
@result.trigger 'change', @result
@trigger 'change', this
removeUncraftableItems: ->
toRemove = []
@want.each (stack)=>
item = @modPack.findItem stack.itemSlug
if not item? then toRemove.push stack.itemSlug
for itemSlug in toRemove
@want.remove itemSlug
# Event Methods ################################################################################
onIncludingToolsChanged: ->
@storage.setItem 'includingTools', "#{@includingTools}"
@craft()
# Object Overrides #############################################################################
toString: ->
return "#{@constructor.name} {
have:#{@have},
want:#{@want},
need:#{@need},
result:#{@result},
steps:#{@steps}
}"
# Private Methods ##############################################################################
_findRecipes: (item)->
recipes = @modPack.findRecipes item.slug
return null unless recipes? and recipes.length > 0
recipeOptions = []
for recipe in recipes
if recipe.tools.length is 0
recipeOptions.push recipe:recipe, missingTools:0
else
missingTools = []
for tool in recipe.tools
if not @have.hasAtLeast tool.itemSlug
missingTools.push tool
recipeOptions.push recipe:recipe, missingTools:missingTools.length
recipeOptions.sort (a, b)->
return 0 if a.missingTools is b.missingTools
return if a.missingTools < b.missingTools then -1 else +1
return (option.recipe for option in recipeOptions)
_findSteps: (itemSlug, parentSteps={})->
item = @modPack.findItem itemSlug
return unless item?
return unless item.isCraftable
ignoreGatherable = @want.hasAtLeast itemSlug, 1
if (not item.isGatherable) or ignoreGatherable
recipes = @_findRecipes item
recipes ?= []
if parentSteps[item.slug]?
logger.verbose -> "found cycle at #{item.slug}"
throw new Error 'invalid recipe path'
parentSteps[item.slug] = item
logger.verbose -> "exploring: #{item.slug}"
logger.indent()
currentSteps = _.clone @steps
foundValidRecipe = false
for i in [0...recipes.length] by 1
recipe = recipes[i]
logger.verbose -> "trying recipe #{i+1} of #{recipes.length}: #{recipe.slug}"
if @steps[recipe.slug]?
logger.verbose -> "already accepted this recipe"
foundValidRecipe = true
break
try
if @includingTools
for toolStack in recipe.tools
if not @_hasStep toolStack.itemSlug
@_findSteps toolStack.itemSlug, parentSteps
for inputStack in recipe.input
@_findSteps inputStack.itemSlug, parentSteps
logger.verbose -> "adding step for: #{recipe.slug}"
@steps[recipe.slug] = new Step outputItemSlug:item.slug, recipe:recipe
foundValidRecipe = true
break
catch error
logger.verbose -> "recipe didn't work out: #{recipe.slug}"
if error.message isnt 'invalid recipe path' then throw error
@steps = _.clone currentSteps
delete parentSteps[item.slug]
logger.outdent()
if not (foundValidRecipe or item.isGatherable)
logger.verbose -> "could not find a valid recipe for #{item.slug}"
throw new Error 'invalid recipe path'
_hasStep: (itemSlug)->
for recipeSlug, step of @steps
return true if step.recipe.produces itemSlug
return false
_qualifyItemSlug: (itemSlug)->
item = @modPack.findItem itemSlug
return item.slug if item?
return itemSlug
_removeExtraSteps: ->
result = []
number = 1
for step in @steps
if step.multiplier > 0
result.push step
step.number = number
number += 1
@steps = result
_resolveNeeds: ->
for i in [@steps.length-1..0] by -1
step = @steps[i]
step.number = i + 1
recipe = step.recipe
outputQuantity = recipe.getQuantityProducedOf step.outputItemSlug
step.multiplier = Math.ceil(@need.quantityOf(step.outputItemSlug) / outputQuantity)
if @includingTools
recipe.eachToolStack (stack)=>
itemSlug = @_qualifyItemSlug stack.itemSlug
available = @result.quantityOf(itemSlug) + @need.quantityOf(itemSlug)
needed = Math.max 0, stack.quantity - available
@need.add itemSlug, needed
@result.add itemSlug, needed
recipe.eachInputStack (stack)=>
itemSlug = @_qualifyItemSlug stack.itemSlug
needed = step.multiplier * stack.quantity
consumed = Math.min needed, @result.quantityOf itemSlug
remaining = needed - consumed
@result.remove itemSlug, consumed
@need.add itemSlug, remaining
recipe.eachOutputStack (stack)=>
itemSlug = @_qualifyItemSlug stack.itemSlug
created = stack.quantity * step.multiplier
consumed = Math.min created, @need.quantityOf itemSlug
remaining = created - consumed
@result.add itemSlug, remaining
@need.remove itemSlug, consumed
+23 -49
View File
@@ -6,6 +6,7 @@ All rights reserved.
###
BaseModel = require './base_model'
ItemSlug = require './item_slug'
Stack = require './stack'
{Event} = require '../constants'
{StringBuilder} = require 'crafting-guide-common'
@@ -46,50 +47,15 @@ module.exports = class Recipe extends BaseModel
return -1 if aValue
return +1 if bValue
aValue = a.getQuantityProducedOf itemSlug
bValue = b.getQuantityProducedOf itemSlug
aValue = a.getQuantityProduced itemSlug
bValue = b.getQuantityProduced itemSlug
if aValue isnt bValue
return if aValue > bValue then -1 else +1
aValue = a.getOutputCount()
bValue = b.getOutputCount()
if aValue isnt bValue
return if aValue > bValue then -1 else +1
aValue = a.tools.length
bValue = b.tools.length
if aValue isnt bValue
return if aValue < bValue then -1 else +1
aValue = a.getInputCount()
bValue = b.getInputCount()
if aValue isnt bValue
return if aValue < bValue then -1 else +1
return 0
# Public Methods ###############################################################################
eachInputStack: (callback)->
for i in [0...@pattern.length]
stack = @getStackAtSlot(i)
continue unless stack?
callback stack
eachOutputStack: (callback)->
for stack in @output
callback stack
eachToolStack: (callback)->
for stack in @tools
callback stack
getInputCount: ->
result = 0
for stack in @input
result += stack.quantity
return result
getStackAtSlot: (patternSlot)->
trueIndex = 0:0, 1:1, 2:2, 3:4, 4:5, 5:6, 6:8, 7:9, 8:10
patternDigit = @pattern[trueIndex[patternSlot]]
@@ -101,13 +67,7 @@ module.exports = class Recipe extends BaseModel
return stack
getOutputCount: ->
result = 0
for stack in @output
result += stack.quantity
return result
getQuantityProducedOf: (itemSlug)->
getQuantityProduced: (itemSlug)->
total = 0
for stack in @output
if stack.itemSlug.matches itemSlug
@@ -115,6 +75,16 @@ module.exports = class Recipe extends BaseModel
return total
getQuantityRequired: (itemSlug)->
total = 0
for i in [0...@pattern.length]
stack = @getStackAtSlot i
continue unless stack?
if ItemSlug.equal stack.itemSlug, itemSlug
total += stack.quantity
return total
hasAllTools: (modPack)->
modPack ?= @modVersion?.mod?.modPack
return true unless modPack
@@ -179,7 +149,7 @@ module.exports = class Recipe extends BaseModel
if not @_slug?
builder = new StringBuilder
delimiterNeeded = false
@eachInputStack (stack)->
for stack in @input
if delimiterNeeded then builder.push ','
delimiterNeeded = true
@@ -187,12 +157,12 @@ module.exports = class Recipe extends BaseModel
builder.push stack.itemSlug.qualified
builder.push '>'
@eachToolStack (stack)->
for stack in @tools
builder.push stack.itemSlug.qualified
builder.push '>'
delimiterNeeded = false
@eachOutputStack (stack)->
for stack in @output
if delimiterNeeded then builder.push ','
delimiterNeeded = true
@@ -215,7 +185,9 @@ module.exports = class Recipe extends BaseModel
needsDelimiter = false
for stack in @input
if needsDelimiter then result.push ', '
result.push stack.toString()
result.push @getQuantityRequired stack.itemSlug
result.push ' '
result.push stack.itemSlug
needsDelimiter = true
result.push ']'
@@ -223,7 +195,9 @@ module.exports = class Recipe extends BaseModel
needsDelimiter = false
for stack in @output
if needsDelimiter then result.push ', '
result.push stack.toString()
result.push @getQuantityProduced stack.itemSlug
result.push ' '
result.push stack.itemSlug
needsDelimiter = true
result.push ']'
+1 -1
View File
@@ -31,5 +31,5 @@ module.exports = class Step extends BaseModel
_computeInventory: ->
@inventory.clear()
@recipe.eachInputStack (stack)=>
for stack in @recipe.input
@inventory.add stack.itemSlug, stack.quantity * @multiplier