codecombat/app/lib/world/GoalManager.coffee

289 lines
12 KiB
CoffeeScript
Raw Normal View History

2014-01-03 13:32:13 -05:00
CocoClass = require 'lib/CocoClass'
utils = require 'lib/utils'
2014-01-03 13:32:13 -05:00
module.exports = class GoalManager extends CocoClass
# The Goal Manager is created both on the main thread and
# each time the world is generated. The one in world generation
# records which code and world related goals
# are completed or failed, and then the results are sent back
# and saved to the main thread instance.
# The main instance handles goals based on UI notifications,
# and keeps track of what the goals are at any given point.
# Goals can only have only one goal property. Otherwise who knows what will happen.
# If you want weird goals or hybrid goals, make a custom goal.
nextGoalID: 0
nicks: ["GoalManager"]
2014-01-03 13:32:13 -05:00
2014-05-19 23:50:05 -04:00
constructor: (@world, @initialGoals, @team) ->
2014-01-03 13:32:13 -05:00
super()
@init()
init: ->
@goals = []
@goalStates = {} # goalID -> object (complete, frameCompleted)
@userCodeMap = {} # @userCodeMap.thangID.methodName.aether.raw = codeString
@thangTeams = {}
@initThangTeams()
@addGoal goal for goal in @initialGoals if @initialGoals
2014-01-03 13:32:13 -05:00
initThangTeams: ->
return unless @world
for thang in @world.thangs when thang.team and thang.isAttackable
continue unless thang.team
@thangTeams[thang.team] = [] unless @thangTeams[thang.team]
@thangTeams[thang.team].push(thang.id)
subscriptions:
'god:new-world-created': 'onNewWorldCreated'
'level:restarted': 'onLevelRestarted'
backgroundSubscriptions:
'world:thang-died': 'onThangDied'
'world:thang-touched-goal': 'onThangTouchedGoal'
'world:thang-left-map': 'onThangLeftMap'
'world:thang-collected-item': 'onThangCollectedItem'
'world:ended': 'onWorldEnded'
2014-02-11 15:32:12 -05:00
onLevelRestarted: ->
2014-01-03 13:32:13 -05:00
@goals = []
@goalStates = {}
@userCodeMap = {}
@notifyGoalChanges()
@addGoal goal for goal in @initialGoals if @initialGoals
2014-01-03 13:32:13 -05:00
# INTERFACE AND LIFETIME OVERVIEW
# world generator gets current goals from the main instance
getGoals: -> @goals
# background instance created by world generator,
# gets these goals and code, and is told to be all ears during world gen
setGoals: (@goals) ->
setCode: (@userCodeMap) -> @updateCodeGoalStates()
worldGenerationWillBegin: -> @initGoalStates()
# World generator feeds world events to the goal manager to keep track
submitWorldGenerationEvent: (channel, event, frameNumber) ->
func = @backgroundSubscriptions[channel]
func = utils.normalizeFunc(func, @)
return unless func
2014-02-11 15:54:08 -05:00
func.call(@, event, frameNumber)
2014-01-03 13:32:13 -05:00
# after world generation, generated goal states
# are grabbed to send back to main instance
worldGenerationEnded: (finalFrame) -> @wrapUpGoalStates(finalFrame)
getGoalStates: -> @goalStates
# main instance gets them and updates their existing goal states,
# passes the word along
2014-02-11 15:32:12 -05:00
onNewWorldCreated: (e) ->
@world = e.world
2014-05-19 23:10:51 -04:00
@updateGoalStates(e.goalStates) if e.goalStates?
2014-01-03 13:32:13 -05:00
updateGoalStates: (newGoalStates) ->
for goalID, goalState of newGoalStates
continue unless @goalStates[goalID]?
@goalStates[goalID] = goalState
@notifyGoalChanges()
# IMPLEMENTATION DETAILS
addGoal: (goal) ->
goal = $.extend(true, {}, goal)
2014-01-03 13:32:13 -05:00
goal.id = @nextGoalID++ if not goal.id
return if @goalStates[goal.id]?
@goals.push(goal)
goal.isPositive = @goalIsPositive goal.id
2014-04-08 17:58:34 -04:00
@goalStates[goal.id] = {status: 'incomplete', keyFrame: 0, team: goal.team}
2014-01-03 13:32:13 -05:00
@notifyGoalChanges()
return unless goal.notificationGoal
f = (channel) => (event) => @onNote(channel, event)
channel = goal.notificationGoal.channel
@addNewSubscription(channel, f(channel))
notifyGoalChanges: ->
overallStatus = @checkOverallStatus()
event =
goalStates: @goalStates
goals: @goals
overallStatus: overallStatus
timedOut: @world.totalFrames is @world.maxTotalFrames
2014-01-03 13:32:13 -05:00
Backbone.Mediator.publish('goal-manager:new-goal-states', event)
checkOverallStatus: (ignoreIncomplete=false) ->
overallStatus = null
2014-05-19 23:50:05 -04:00
goals = if @goalStates then _.values @goalStates else []
goals = (g for g in goals when g.team in [undefined, @team]) if @team
statuses = if @goalStates then (goal.status for goal in goals) else []
2014-01-03 13:32:13 -05:00
overallStatus = 'success' if statuses.length > 0 and _.every(statuses, (s) -> s is 'success' or (ignoreIncomplete and s is null))
overallStatus = 'failure' if statuses.length > 0 and 'failure' in statuses
overallStatus
# WORLD GOAL TRACKING
initGoalStates: ->
@goalStates = {}
return unless @goals
for goal in @goals
state = {
status: null # should eventually be either 'success', 'failure', or 'incomplete'
keyFrame: 0 # when it became a 'success' or 'failure'
2014-04-08 17:58:34 -04:00
team: goal.team
2014-01-03 13:32:13 -05:00
}
@initGoalState(state, [goal.killThangs, goal.saveThangs], 'killed')
2014-03-30 20:24:07 -04:00
for getTo in goal.getAllToLocations ? []
@initGoalState(state,[ getTo.getToLocation?.who , [] ], 'arrived')
2014-03-30 20:24:07 -04:00
for keepFrom in goal.keepAllFromLocations ? []
@initGoalState(state,[ [] , keepFrom.keepFromLocation?.who], 'arrived')
2014-01-03 13:32:13 -05:00
@initGoalState(state, [goal.getToLocations?.who, goal.keepFromLocations?.who], 'arrived')
@initGoalState(state, [goal.leaveOffSides?.who, goal.keepFromLeavingOffSides?.who], 'left')
@initGoalState(state, [goal.collectThangs?.who, goal.keepFromCollectingThangs?.who], 'collected')
@goalStates[goal.id] = state
2014-02-11 15:54:08 -05:00
onThangDied: (e, frameNumber) ->
2014-01-03 13:32:13 -05:00
for goal in @goals ? []
@checkKillThangs(goal.id, goal.killThangs, e.thang, frameNumber) if goal.killThangs?
@checkKillThangs(goal.id, goal.saveThangs, e.thang, frameNumber) if goal.saveThangs?
2014-02-11 15:54:08 -05:00
checkKillThangs: (goalID, targets, thang, frameNumber) ->
2014-01-03 13:32:13 -05:00
return unless thang.id in targets or thang.team in targets
@updateGoalState(goalID, thang.id, 'killed', frameNumber)
2014-02-11 15:54:08 -05:00
onThangTouchedGoal: (e, frameNumber) ->
2014-01-03 13:32:13 -05:00
for goal in @goals ? []
@checkArrived(goal.id, goal.getToLocations.who, goal.getToLocations.targets, e.actor, e.touched.id, frameNumber) if goal.getToLocations?
2014-03-30 20:24:07 -04:00
if goal.getAllToLocations?
for getTo in goal.getAllToLocations
@checkArrived(goal.id, getTo.getToLocation.who, getTo.getToLocation.targets, e.actor, e.touched.id, frameNumber)
@checkArrived(goal.id, goal.keepFromLocations.who, goal.keepFromLocations.targets, e.actor, e.touched.id, frameNumber) if goal.keepFromLocations?
2014-03-30 20:24:07 -04:00
if goal.keepAllFromLocations?
for keepFrom in goal.keepAllFromLocations
@checkArrived(goal.id, keepFrom.keepFromLocation.who , keepFrom.keepFromLocation.targets, e.actor, e.touched.id, frameNumber )
2014-01-03 13:32:13 -05:00
checkArrived: (goalID, who, targets, thang, touchedID, frameNumber) ->
2014-01-03 13:32:13 -05:00
return unless touchedID in targets
return unless thang.id in who or thang.team in who
@updateGoalState(goalID, thang.id, 'arrived', frameNumber)
2014-01-03 13:32:13 -05:00
2014-02-11 15:54:08 -05:00
onThangLeftMap: (e, frameNumber) ->
2014-01-03 13:32:13 -05:00
for goal in @goals ? []
@checkLeft(goal.id, goal.leaveOffSides.who, goal.leaveOffSides.sides, e.thang.id, e.side, frameNumber) if goal.leaveOffSides?
@checkLeft(goal.id, goal.keepFromLeavingOffSides.who, goal.keepFromLeavingOffSides.sides, e.thang.id, e.side, frameNumber) if goal.keepFromLeavingOffSides?
2014-02-11 15:54:08 -05:00
checkLeft: (goalID, who, sides, thangID, side, frameNumber) ->
2014-01-03 13:32:13 -05:00
return if sides and side and not (side in sides)
return unless thangID in who
@updateGoalState(goalID, thangID, 'left', frameNumber)
2014-02-11 15:54:08 -05:00
onThangCollectedItem: (e, frameNumber) ->
2014-01-03 13:32:13 -05:00
for goal in @goals ? []
@checkCollected(goal.id, goal.collectThangs.who, goal.collectThangs.targets, e.actor.id, e.item.id, frameNumber) if goal.collectThangs?
@checkCollected(goal.id, goal.keepFromCollectingThangs.who, goal.keepFromCollectingThangs.targets, e.actor.id, e.item.id, frameNumber) if goal.keepFromCollectingThangs?
2014-02-11 15:54:08 -05:00
checkCollected: (goalID, who, targets, thangID, itemID, frameNumber) ->
2014-01-03 13:32:13 -05:00
return unless itemID in targets
return unless thangID in who
@updateGoalState(goalID, thangID, 'collected', frameNumber)
wrapUpGoalStates: (finalFrame) ->
for goalID, state of @goalStates
if state.status is null
if @goalIsPositive(goalID)
state.status = 'incomplete'
else
state.status = 'success'
state.keyFrame = 'end' # special case for objective UI to handle
# UI EVENT GOAL TRACKING
onNote: (channel, e) ->
# TODO for UI event related goals
# HELPER FUNCTIONS
# It's a pretty similar pattern for each of the above goals.
# Once you determine a thang has done the thing, you mark it done in the progress object.
initGoalState: (state, whos, progressObjectName) ->
# 'whos' is an array of goal 'who' values.
# This inits the progress object for the goal tracking.
2014-03-30 20:24:07 -04:00
2014-01-03 13:32:13 -05:00
arrays = (prop for prop in whos when prop?.length)
return unless arrays.length
2014-05-06 10:22:09 -04:00
state[progressObjectName] ?= {}
2014-01-03 13:32:13 -05:00
for array in arrays
for thang in array
if @thangTeams[thang]?
for t in @thangTeams[thang]
state[progressObjectName][t] = false
else
state[progressObjectName][thang] = false
getGoalState: (goalID) ->
@goalStates[goalID].status
2014-03-28 21:52:02 -04:00
setGoalState: (goalID, status) ->
state = @goalStates[goalID]
state.status = status
if overallStatus = @checkOverallStatus true
matchedGoals = (_.find(@goals, {id: goalID}) for goalID, goalState of @goalStates when goalState.status is overallStatus)
mostEagerGoal = _.min matchedGoals, 'worldEndsAfter'
victory = overallStatus is "success"
tentative = overallStatus is "success"
@world.endWorld victory, mostEagerGoal.worldEndsAfter, tentative if mostEagerGoal isnt Infinity
2014-03-30 20:24:07 -04:00
2014-01-03 13:32:13 -05:00
updateGoalState: (goalID, thangID, progressObjectName, frameNumber) ->
# A thang has done something related to the goal!
# Mark it down and update the goal state.
goal = _.find @goals, {id: goalID}
state = @goalStates[goalID]
stateThangs = state[progressObjectName]
stateThangs[thangID] = true
success = @goalIsPositive goalID
if success
numNeeded = goal.howMany ? Math.max(1, _.size stateThangs)
2014-01-03 13:32:13 -05:00
else
# saveThangs: by default we would want to save all the Thangs, which means that we would want none of them to be "done"
numNeeded = _.size(stateThangs) - Math.max((goal.howMany ? 1), _.size stateThangs) + 1
2014-01-03 13:32:13 -05:00
numDone = _.filter(stateThangs).length
2014-05-12 16:28:46 -04:00
#console.log "needed", numNeeded, "done", numDone, "of total", _.size(stateThangs), "with how many", goal.howMany, "and stateThangs", stateThangs
2014-01-03 13:32:13 -05:00
return unless numDone >= numNeeded
return if state.status and not success # already failed it; don't wipe keyframe
state.status = if success then "success" else "failure"
state.keyFrame = frameNumber
2014-05-12 16:28:46 -04:00
#console.log goalID, "became", success, "on frame", frameNumber, "with overallStatus", @checkOverallStatus true
2014-01-03 13:32:13 -05:00
if overallStatus = @checkOverallStatus true
matchedGoals = (_.find(@goals, {id: goalID}) for goalID, goalState of @goalStates when goalState.status is overallStatus)
mostEagerGoal = _.min matchedGoals, 'worldEndsAfter'
victory = overallStatus is "success"
tentative = overallStatus is "success"
@world.endWorld victory, mostEagerGoal.worldEndsAfter, tentative if mostEagerGoal isnt Infinity
goalIsPositive: (goalID) ->
# Positive goals are completed when all conditions are true (kill all these thangs)
# Negative goals fail when any are true (keep all these thangs from being killed)
goal = _.find(@goals, {id: goalID}) ? {}
return false for prop of goal when @positiveGoalMap[prop] is 0
true
positiveGoalMap:
killThangs: 1
saveThangs: 0
getToLocations: 1
getAllToLocations: 1
2014-01-03 13:32:13 -05:00
keepFromLocations: 0
keepAllFromLocations: 0
2014-01-03 13:32:13 -05:00
leaveOffSides: 1
keepFromLeavingOffSides: 0
collectThangs: 1
keepFromCollectingThangs: 0
updateCodeGoalStates: ->
# TODO
# teardown
destroy: ->
super()