codecombat/app/lib/simulator/Simulator.coffee

293 lines
9.9 KiB
CoffeeScript
Raw Normal View History

2014-02-14 13:49:16 -05:00
SuperModel = require 'models/SuperModel'
CocoClass = require 'lib/CocoClass'
2014-02-14 13:49:16 -05:00
LevelLoader = require 'lib/LevelLoader'
GoalManager = require 'lib/world/GoalManager'
God = require 'lib/God'
2014-02-14 13:49:16 -05:00
module.exports = class Simulator extends CocoClass
2014-02-14 13:49:16 -05:00
constructor: ->
_.extend @, Backbone.Events
@trigger 'statusUpdate', 'Starting simulation!'
2014-02-14 13:49:16 -05:00
@retryDelayInSeconds = 10
@taskURL = '/queue/scoring'
destroy: ->
@off()
@cleanupSimulation()
super()
2014-02-14 13:49:16 -05:00
fetchAndSimulateTask: =>
2014-03-16 23:36:02 -04:00
return if @destroyed
@trigger 'statusUpdate', 'Fetching simulation data!'
2014-02-14 13:49:16 -05:00
$.ajax
url: @taskURL
type: "GET"
error: @handleFetchTaskError
success: @setupSimulationAndLoadLevel
handleFetchTaskError: (errorData) =>
console.error "There was a horrible Error: #{JSON.stringify errorData}"
@trigger 'statusUpdate', 'There was an error fetching games to simulate. Retrying in 10 seconds.'
@simulateAnotherTaskAfterDelay()
2014-02-14 13:49:16 -05:00
handleNoGamesResponse: ->
@trigger 'statusUpdate', 'There were no games to simulate--nice. Retrying in 10 seconds.'
@simulateAnotherTaskAfterDelay()
simulateAnotherTaskAfterDelay: =>
console.log "Retrying in #{@retryDelayInSeconds}"
retryDelayInMilliseconds = @retryDelayInSeconds * 1000
_.delay @fetchAndSimulateTask, retryDelayInMilliseconds
2014-02-14 13:49:16 -05:00
setupSimulationAndLoadLevel: (taskData, textStatus, jqXHR) =>
return @handleNoGamesResponse() if jqXHR.status is 204
@trigger 'statusUpdate', 'Setting up simulation!'
2014-02-14 13:49:16 -05:00
@task = new SimulationTask(taskData)
@supermodel ?= new SuperModel()
@god = new God maxWorkerPoolSize: 1, maxAngels: 1 # Start loading worker.
2014-02-14 13:49:16 -05:00
2014-02-15 18:44:45 -05:00
@levelLoader = new LevelLoader supermodel: @supermodel, levelID: @task.getLevelName(), sessionID: @task.getFirstSessionID(), headless: true
2014-02-14 13:49:16 -05:00
@levelLoader.once 'loaded-all', @simulateGame
simulateGame: =>
return if @destroyed
@trigger 'statusUpdate', 'All resources loaded, simulating!', @task.getSessions()
2014-02-14 13:49:16 -05:00
@assignWorldAndLevelFromLevelLoaderAndDestroyIt()
@setupGod()
2014-02-14 13:49:16 -05:00
try
@commenceSimulationAndSetupCallback()
catch err
2014-02-15 18:45:53 -05:00
console.log "There was an error in simulation(#{err}). Trying again in #{@retryDelayInSeconds} seconds"
@simulateAnotherTaskAfterDelay()
2014-02-14 13:49:16 -05:00
assignWorldAndLevelFromLevelLoaderAndDestroyIt: ->
@world = @levelLoader.world
@level = @levelLoader.level
@levelLoader.destroy()
2014-02-15 18:44:45 -05:00
@levelLoader = null
2014-02-14 13:49:16 -05:00
setupGod: ->
@god.level = @level.serialize @supermodel
@god.worldClassMap = @world.classMap
2014-02-14 13:49:16 -05:00
@setupGoalManager()
@setupGodSpells()
setupGoalManager: ->
@god.goalManager = new GoalManager @world
2014-02-26 20:45:08 -05:00
@god.goalManager.goals = @god.level.goals
2014-02-14 13:49:16 -05:00
@god.goalManager.goalStates = @manuallyGenerateGoalStates()
commenceSimulationAndSetupCallback: ->
@god.createWorld()
Backbone.Mediator.subscribeOnce 'god:new-world-created', @processResults, @
processResults: (simulationResults) ->
taskResults = @formTaskResultsObject simulationResults
@sendResultsBackToServer taskResults
2014-02-14 13:49:16 -05:00
sendResultsBackToServer: (results) =>
@trigger 'statusUpdate', 'Simulation completed, sending results back to server!'
2014-02-18 14:46:14 -05:00
console.log "Sending result back to server!"
2014-02-14 13:49:16 -05:00
$.ajax
2014-02-18 14:46:14 -05:00
url: "/queue/scoring"
2014-02-14 13:49:16 -05:00
data: results
type: "PUT"
success: @handleTaskResultsTransferSuccess
error: @handleTaskResultsTransferError
2014-02-14 19:53:34 -05:00
complete: @cleanupAndSimulateAnotherTask
2014-02-14 13:49:16 -05:00
handleTaskResultsTransferSuccess: (result) =>
2014-02-14 13:49:16 -05:00
console.log "Task registration result: #{JSON.stringify result}"
@trigger 'statusUpdate', 'Results were successfully sent back to server!'
2014-03-20 22:18:46 -04:00
simulatedBy = parseInt($('#simulated-by-you').text(), 10) + 1
$('#simulated-by-you').text(simulatedBy)
2014-02-14 13:49:16 -05:00
handleTaskResultsTransferError: (error) =>
@trigger 'statusUpdate', 'There was an error sending the results back to the server.'
2014-02-14 13:49:16 -05:00
console.log "Task registration error: #{JSON.stringify error}"
cleanupAndSimulateAnotherTask: =>
@cleanupSimulation()
@fetchAndSimulateTask()
cleanupSimulation: ->
@god?.destroy()
2014-02-15 18:44:45 -05:00
@god = null
@world = null
@level = null
2014-02-14 13:49:16 -05:00
formTaskResultsObject: (simulationResults) ->
taskResults =
taskID: @task.getTaskID()
receiptHandle: @task.getReceiptHandle()
2014-02-26 15:14:02 -05:00
originalSessionID: @task.getFirstSessionID()
originalSessionRank: -1
2014-02-14 13:49:16 -05:00
calculationTime: 500
sessions: []
for session in @task.getSessions()
2014-02-26 20:45:08 -05:00
2014-02-14 13:49:16 -05:00
sessionResult =
sessionID: session.sessionID
2014-02-18 14:46:14 -05:00
submitDate: session.submitDate
creator: session.creator
2014-02-14 13:49:16 -05:00
metrics:
rank: @calculateSessionRank session.sessionID, simulationResults.goalStates, @task.generateTeamToSessionMap()
2014-02-26 15:14:02 -05:00
if session.sessionID is taskResults.originalSessionID
taskResults.originalSessionRank = sessionResult.metrics.rank
taskResults.originalSessionTeam = session.team
2014-02-14 13:49:16 -05:00
taskResults.sessions.push sessionResult
return taskResults
calculateSessionRank: (sessionID, goalStates, teamSessionMap) ->
2014-02-14 13:49:16 -05:00
humansDestroyed = goalStates["destroy-humans"].status is "success"
ogresDestroyed = goalStates["destroy-ogres"].status is "success"
if humansDestroyed is ogresDestroyed
return 0
else if humansDestroyed and teamSessionMap["ogres"] is sessionID
2014-02-14 13:49:16 -05:00
return 0
else if humansDestroyed and teamSessionMap["ogres"] isnt sessionID
2014-02-14 13:49:16 -05:00
return 1
else if ogresDestroyed and teamSessionMap["humans"] is sessionID
2014-02-14 13:49:16 -05:00
return 0
else
return 1
manuallyGenerateGoalStates: ->
goalStates =
"destroy-humans":
keyFrame: 0
killed:
"Human Base": false
status: "incomplete"
"destroy-ogres":
keyFrame:0
killed:
"Ogre Base": false
status: "incomplete"
setupGodSpells: ->
@generateSpellsObject()
@god.spells = @spells
generateSpellsObject: ->
@currentUserCodeMap = @task.generateSpellKeyToSourceMap()
2014-02-14 13:49:16 -05:00
@spells = {}
for thang in @level.attributes.thangs
continue if @thangIsATemplate thang
@generateSpellKeyToSourceMapPropertiesFromThang thang
thangIsATemplate: (thang) ->
for component in thang.components
continue unless @componentHasProgrammableMethods component
for methodName, method of component.config.programmableMethods
return true if @methodBelongsToTemplateThang method
2014-02-14 13:49:16 -05:00
return false
componentHasProgrammableMethods: (component) -> component.config? and _.has component.config, 'programmableMethods'
methodBelongsToTemplateThang: (method) -> typeof method is 'string'
generateSpellKeyToSourceMapPropertiesFromThang: (thang) =>
for component in thang.components
continue unless @componentHasProgrammableMethods component
for methodName, method of component.config.programmableMethods
spellKey = @generateSpellKeyFromThangIDAndMethodName thang.id, methodName
@createSpellAndAssignName spellKey, methodName
@createSpellThang thang, method, spellKey
@transpileSpell thang, spellKey, methodName
generateSpellKeyFromThangIDAndMethodName: (thang, methodName) ->
spellKeyComponents = [thang, methodName]
spellKeyComponents[0] = _.string.slugify spellKeyComponents[0]
spellKey = spellKeyComponents.join '/'
spellKey
2014-02-26 20:45:08 -05:00
2014-02-14 13:49:16 -05:00
createSpellAndAssignName: (spellKey, spellName) ->
@spells[spellKey] ?= {}
@spells[spellKey].name = spellName
2014-02-14 13:49:16 -05:00
createSpellThang: (thang, method, spellKey) ->
@spells[spellKey].thangs ?= {}
@spells[spellKey].thangs[thang.id] ?= {}
@spells[spellKey].thangs[thang.id].aether = @createAether @spells[spellKey].name, method
transpileSpell: (thang, spellKey, methodName) ->
slugifiedThangID = _.string.slugify thang.id
source = @currentUserCodeMap[[slugifiedThangID,methodName].join '/'] ? ""
aether = @spells[spellKey].thangs[thang.id].aether
try
aether.transpile source
catch e
console.log "Couldn't transpile #{spellKey}:\n#{source}\n", e
aether.transpile ''
2014-02-14 13:49:16 -05:00
createAether: (methodName, method) ->
aetherOptions =
functionName: methodName
protectAPI: true
2014-02-14 13:49:16 -05:00
includeFlow: false
requiresThis: true
yieldConditionally: false
problems:
jshint_W040: {level: "ignore"}
jshint_W030: {level: "ignore"} # aether_NoEffect instead
aether_MissingThis: {level: 'error'}
#functionParameters: # TODOOOOO
if methodName is 'hear'
aetherOptions.functionParameters = ['speaker', 'message', 'data']
#console.log "creating aether with options", aetherOptions
2014-02-14 13:49:16 -05:00
return new Aether aetherOptions
class SimulationTask
constructor: (@rawData) ->
console.log 'Simulating sessions', (session for session in @getSessions())
2014-02-14 13:49:16 -05:00
getLevelName: ->
levelName = @rawData.sessions?[0]?.levelID
return levelName if levelName?
@throwMalformedTaskError "The level name couldn't be deduced from the task."
generateTeamToSessionMap: ->
teamSessionMap = {}
for session in @rawData.sessions
@throwMalformedTaskError "Two players share the same team" if teamSessionMap[session.team]?
teamSessionMap[session.team] = session.sessionID
teamSessionMap
throwMalformedTaskError: (errorString) ->
throw new Error "The task was malformed, reason: #{errorString}"
getFirstSessionID: -> @rawData.sessions[0].sessionID
getTaskID: -> @rawData.taskID
getReceiptHandle: -> @rawData.receiptHandle
getSessions: -> @rawData.sessions
generateSpellKeyToSourceMap: ->
spellKeyToSourceMap = {}
for session in @rawData.sessions
teamSpells = session.teamSpells[session.team]
teamCode = {}
for thangName, thangSpells of session.code
for spellName, spell of thangSpells
fullSpellName = [thangName,spellName].join '/'
if _.contains(teamSpells, fullSpellName)
teamCode[fullSpellName]=spell
2014-02-26 20:45:08 -05:00
_.merge spellKeyToSourceMap, teamCode
2014-02-14 13:49:16 -05:00
commonSpells = session.teamSpells["common"]
_.merge spellKeyToSourceMap, _.pick(session.code, commonSpells) if commonSpells?
2014-02-26 20:45:08 -05:00
2014-02-14 13:49:16 -05:00
spellKeyToSourceMap