Verification simulator changes

This commit is contained in:
Michael Schmatz 2014-05-19 10:11:20 -07:00
parent 5dffca7a9c
commit 6f2fd8e293
5 changed files with 116 additions and 16 deletions

View file

@ -23,7 +23,78 @@ module.exports = class Simulator extends CocoClass
@cleanupSimulation()
@god?.destroy()
super()
fetchAndSimulateOneGame: (humanGameID, ogresGameID) =>
return if @destroyed
$.ajax
url: "/queue/scoring/getTwoGames"
type: "POST"
parse: true
data:
"humansGameID": humanGameID
"ogresGameID": ogresGameID
error: (errorData) ->
console.log "There was an error fetching two games! #{JSON.stringify errorData}"
success: (taskData) =>
#refactor this
@task = new SimulationTask(taskData)
@supermodel ?= new SuperModel()
@supermodel.resetProgress()
@levelLoader = new LevelLoader supermodel: @supermodel, levelID: @task.getLevelName(), sessionID: @task.getFirstSessionID(), headless: true
if @supermodel.finished()
@simulateSingleGame()
else
@listenToOnce @supermodel, 'loaded-all', @simulateSingleGame
simulateSingleGame: ->
return if @destroyed
console.log "Commencing simulation!"
@assignWorldAndLevelFromLevelLoaderAndDestroyIt()
@setupGod()
try
@commenceSingleSimulation()
catch err
console.log err
@handleSingleSimulationError()
commenceSingleSimulation: ->
@god.createWorld @generateSpellsObject()
Backbone.Mediator.subscribeOnce 'god:infinite-loop', @handleSingleSimulationInfiniteLoop, @
Backbone.Mediator.subscribeOnce 'god:goals-calculated', @processSingleGameResults, @
handleSingleSimulationError: ->
console.log "There was an error simulating a single game!"
if @options.headlessClient
console.log "GAMERESULT:tie"
process.exit(0)
@cleanupSimulation()
handleSingleSimulationInfiniteLoop: ->
console.log "There was an infinite loop in the single game!"
if @options.headlessClient
console.log "GAMERESULT:tie"
process.exit(0)
@cleanupSimulation()
processSingleGameResults: (simulationResults) ->
console.log "Processing results!"
taskResults = @formTaskResultsObject simulationResults
humanSessionRank = taskResults.sessions[0].metrics.rank
ogreSessionRank = taskResults.sessions[1].metrics.rank
if @options.headlessClient
if humanSessionRank is ogreSessionRank
console.log "GAMERESULT:tie"
else if humanSessionRank < ogreSessionRank
console.log "GAMERESULT:humans"
else if ogreSessionRank < humanSessionRank
console.log "GAMERESULT:ogres"
process.exit(0)
@cleanupSimulation()
fetchAndSimulateTask: =>
return if @destroyed

View file

@ -1,14 +1,11 @@
###
This file will simulate games on node.js by emulating the browser environment.
###
simulateOneGame = false
if process.argv[2] is "one-game"
#calculate result of one game here
if Math.random() > 0.5
process.stdout.write "ogres"
else
process.stdout.write "humans"
process.exit(0)
simulateOneGame = true
console.log "Simulating #{process.argv[3]} vs #{process.argv[4]}"
bowerComponentsPath = "./bower_components/"
headlessClientPath = "./headless_client/"
@ -16,7 +13,7 @@ headlessClientPath = "./headless_client/"
options =
workerCode: require headlessClientPath + 'worker_world'
debug: false # Enable logging of ajax calls mainly
testing: false # Instead of simulating 'real' games, use the same one over and over again. Good for leak hunting.
testing: true # Instead of simulating 'real' games, use the same one over and over again. Good for leak hunting.
testFile: require headlessClientPath + 'test.js'
leakTest: false # Install callback that tries to find leaks automatically
exitOnLeak: false # Exit if leak is found. Only useful if leaktest is set to true, obviously.
@ -188,7 +185,6 @@ hook()
login = require './login.coffee' #should contain an object containing they keys 'username' and 'password'
#Login user and start the code.
$.ajax
url: '/auth/login'
@ -197,7 +193,7 @@ $.ajax
parse: true
error: (error) -> "Bad Error. Can't connect to server or something. " + error
success: (response) ->
console.log "User: " + response
console.log "User: " + JSON.stringify response
GLOBAL.window.userObject = response # JSON.parse response
User = require 'models/User'
@ -213,7 +209,9 @@ $.ajax
CocoClass = require 'lib/CocoClass'
Simulator = require 'lib/simulator/Simulator'
sim = new Simulator options
sim.fetchAndSimulateTask()
if simulateOneGame
sim.fetchAndSimulateOneGame(process.argv[3],process.argv[4])
else
sim.fetchAndSimulateTask()

View file

@ -5,16 +5,19 @@ spawn = require("child_process").spawn
unless sessionOne and sessionTwo and sessionOne.length is 24 and sessionTwo.length is 24
console.log "Not enough games to continue!"
process.exit(1)
command = "coffee ../headless_client.coffee one-game"
run = (cb) ->
command = spawn("coffee",["headless_client.coffee","one-game"],{cwd:"/Users/schmatz/codecombat/"})
command = spawn("coffee",["headless_client.coffee","one-game",sessionOne,sessionTwo],{cwd:"/Users/schmatz/codecombat/"})
result = ""
command.stdout.on 'data', (data) ->
result += data.toString()
command.stdout.on 'close', ->
return cb(result)
run (result) ->
process.stdout.write result
lines = result.split("\n")
for line in lines
if line.slice(0, 10) is "GAMERESULT"
process.stdout.write line.slice(11)
process.exit(0)
process.exit(0)

View file

@ -99,7 +99,32 @@ resimulateSession = (originalLevelID, levelMajorVersion, session, cb) =>
if taskPairError? then return cb taskPairError, null
cb null
module.exports.getTwoGames = (req, res) ->
#if userIsAnonymous req then return errors.unauthorized(res, "You need to be logged in to get games.")
humansGameID = req.body.humansGameID
ogresGameID = req.body.ogresGameID
unless ogresGameID and humansGameID
#fetch random games here
return errors.badInput(res, "You need to supply two games(for now)")
LevelSession.findOne(_id: humansGameID).lean().exec (err, humanSession) =>
if err? then return errors.serverError(res, "Couldn't find the human game")
LevelSession.findOne(_id: ogresGameID).lean().exec (err, ogreSession) =>
if err? then return errors.serverError(res, "Couldn't find the ogre game")
taskObject =
"messageGenerated": Date.now()
"sessions": []
for session in [humanSession, ogreSession]
sessionInformation =
"sessionID": session._id
"team": session.team ? "No team"
"transpiledCode": session.transpiledCode
"teamSpells": session.teamSpells ? {}
"levelID": session.levelID
taskObject.sessions.push sessionInformation
sendResponseObject req, res, taskObject
module.exports.createNewTask = (req, res) ->
requestSessionID = req.body.session
originalLevelID = req.body.originalLevelID

View file

@ -18,6 +18,9 @@ module.exports.setup = (app) ->
handler = loadQueueHandler 'scoring'
handler.resimulateAllSessions req, res
app.post '/queue/scoring/getTwoGames', (req, res) ->
handler = loadQueueHandler 'scoring'
handler.getTwoGames req, res
app.all '/queue/*', (req, res) ->
setResponseHeaderToJSONContentType res