This commit is contained in:
Nick Winter 2014-04-17 10:12:26 -07:00
commit 40367e701c
6 changed files with 201 additions and 167 deletions

View file

@ -38,52 +38,4 @@ block content
.tab-pane.well#my-matches
#my-matches-tab-view
.tab-pane.well#simulate
p(id="simulation-status-text")
if simulationStatus
| #{simulationStatus}
else
span(data-i18n="ladder.simulation_explanation") By simulating games you can get your game ranked faster!
p
button(data-i18n="ladder.simulate_games").btn.btn-warning.btn-lg.highlight#simulate-button Simulate Games!
if false && me.isAdmin()
p
button(data-i18n="ladder.simulate_all").btn.btn-danger.btn-lg.highlight#simulate-all-button RESET AND SIMULATE GAMES
p.simulation-count
span(data-i18n="ladder.games_simulated_by") Games simulated by you:
|
span#simulated-by-you= me.get('simulatedBy') || 0
p.simulation-count
span(data-i18n="ladder.games_simulated_for") Games simulated for you:
|
span#simulated-for-you= me.get('simulatedFor') || 0
table.table.table-bordered.table-condensed.table-hover
tr
th(data-i18n="general.player").name-col-cell Player
th(data-i18n="ladder.games_simulated") Games simulated
th(data-i18n="ladder.games_played") Games played
th(data-i18n="ladder.ratio") Ratio
- var topSimulators = simulatorsLeaderboardData.topSimulators.models;
- var showJustTop = simulatorsLeaderboardData.inTopSimulators() || me.get('anonymous');
- if(!showJustTop) topSimulators = topSimulators.slice(0, 10);
for user in topSimulators
- var myRow = user.id == me.id
tr(class=myRow ? "success" : "")
td.name-col-cell= user.get('name') || "Anonymous"
td.simulator-leaderboard-cell= user.get('simulatedBy')
td.simulator-leaderboard-cell= user.get('simulatedFor')
td.simulator-leaderboard-cell= Math.round((user.get('simulatedBy') / user.get('simulatedFor')) * 10) / 10
if !showJustTop && simulatorsLeaderboardData.nearbySimulators().length
tr(class="active")
td(colspan=4).ellipsis-row ...
for user in simulatorsLeaderboardData.nearbySimulators()
- var myRow = user.id == me.id
- var ratio = user.get('simulatedBy') / user.get('simulatedFor');
tr(class=myRow ? "success" : "")
td.name-col-cell= user.get('name') || "Anonymous"
td.simulator-leaderboard-cell= user.get('simulatedBy')
td.simulator-leaderboard-cell= user.get('simulatedFor')
td.simulator-leaderboard-cell= _.isNaN(ratio) || ratio == Infinity ? '' : ratio.toFixed(1)
#simulate-tab-view

View file

@ -0,0 +1,49 @@
p(id="simulation-status-text")
if simulationStatus
| #{simulationStatus}
else
span(data-i18n="ladder.simulation_explanation") By simulating games you can get your game ranked faster!
p
button(data-i18n="ladder.simulate_games").btn.btn-warning.btn-lg.highlight#simulate-button Simulate Games!
p.simulation-count
span(data-i18n="ladder.games_simulated_by") Games simulated by you:
|
span#simulated-by-you= me.get('simulatedBy') || 0
p.simulation-count
span(data-i18n="ladder.games_simulated_for") Games simulated for you:
|
span#simulated-for-you= me.get('simulatedFor') || 0
table.table.table-bordered.table-condensed.table-hover
tr
th
th(data-i18n="general.player").name-col-cell Player
th(data-i18n="ladder.games_simulated") Games simulated
th(data-i18n="ladder.games_played") Games played
th(data-i18n="ladder.ratio") Ratio
- var topSimulators = simulatorsLeaderboardData.topSimulators.models;
- var showJustTop = simulatorsLeaderboardData.inTopSimulators() || me.get('anonymous');
- if(!showJustTop) topSimulators = topSimulators.slice(0, 10);
for user, rank in topSimulators
- var myRow = user.id == me.id
tr(class=myRow ? "success" : "")
td.simulator-leaderboard-cell= rank + 1
td.name-col-cell= user.get('name') || "Anonymous"
td.simulator-leaderboard-cell= user.get('simulatedBy')
td.simulator-leaderboard-cell= user.get('simulatedFor')
td.simulator-leaderboard-cell= Math.round((user.get('simulatedBy') / user.get('simulatedFor')) * 10) / 10
if !showJustTop && simulatorsLeaderboardData.nearbySimulators().length
tr(class="active")
td(colspan=5).ellipsis-row ...
for user in simulatorsLeaderboardData.nearbySimulators()
- var myRow = user.id == me.id
- var ratio = user.get('simulatedBy') / user.get('simulatedFor');
tr(class=myRow ? "success" : "")
td.simulator-leaderboard-cell= user.rank
td.name-col-cell= user.get('name') || "Anonymous"
td.simulator-leaderboard-cell= user.get('simulatedBy')
td.simulator-leaderboard-cell= user.get('simulatedFor')
td.simulator-leaderboard-cell= _.isNaN(ratio) || ratio == Infinity ? '' : ratio.toFixed(1)

View file

@ -309,8 +309,8 @@ class LeaderboardData extends CocoClass
return [] unless @session?.get('totalScore')
l = []
above = @playersAbove.models
above.reverse()
l = l.concat(above)
l.reverse()
l.push @session
l = l.concat(@playersBelow.models)
if @myRank

View file

@ -0,0 +1,130 @@
CocoView = require 'views/kinds/CocoView'
CocoClass = require 'lib/CocoClass'
SimulatorsLeaderboardCollection = require 'collections/SimulatorsLeaderboardCollection'
Simulator = require 'lib/simulator/Simulator'
{me} = require 'lib/auth'
module.exports = class SimulateTabView extends CocoView
id: 'simulate-tab-view'
template: require 'templates/play/ladder/simulate_tab'
events:
'click #simulate-button': 'onSimulateButtonClick'
'click #simulate-all-button': 'onSimulateAllButtonClick'
constructor: (options) ->
super(options)
@simulatorsLeaderboardData = new SimulatorsLeaderboardData(me)
@addResourceToLoad(@simulatorsLeaderboardData, 'top_simulators')
@simulator = new Simulator()
@listenTo(@simulator, 'statusUpdate', @updateSimulationStatus)
onLoaded: ->
super()
getRenderData: ->
ctx = super()
ctx.simulationStatus = @simulationStatus
ctx.simulatorsLeaderboardData = @simulatorsLeaderboardData
ctx._ = _
ctx
afterRender: ->
super()
# Simulations
onSimulateButtonClick: (e) ->
$("#simulate-button").prop "disabled",true
$("#simulate-button").text "Simulating..."
@simulator.fetchAndSimulateTask()
updateSimulationStatus: (simulationStatus, sessions) ->
@simulationStatus = simulationStatus
try
if sessions?
#TODO: Fetch names from Redis, the creatorName is denormalized
creatorNames = (session.creatorName for session in sessions)
@simulationStatus = "Simulating game between "
for index in [0...creatorNames.length]
unless creatorNames[index]
creatorNames[index] = "Anonymous"
@simulationStatus += (if index != 0 then " and " else "") + creatorNames[index]
@simulationStatus += "..."
catch e
console.log "There was a problem with the named simulation status: #{e}"
$("#simulation-status-text").text @simulationStatus
resimulateAllSessions: ->
postData =
originalLevelID: @level.get('original')
levelMajorVersion: @level.get('version').major
console.log postData
$.ajax
url: '/queue/scoring/resimulateAllSessions'
method: 'POST'
data: postData
complete: (jqxhr) ->
console.log jqxhr.responseText
destroy: ->
clearInterval @refreshInterval
@simulator.destroy()
super()
class SimulatorsLeaderboardData extends CocoClass
###
Consolidates what you need to load for a leaderboard into a single Backbone Model-like object.
###
constructor: (@me) ->
super()
@fetch()
fetch: ->
@topSimulators = new SimulatorsLeaderboardCollection({order:-1, scoreOffset: -1, limit: 20})
promises = []
promises.push @topSimulators.fetch()
unless @me.get('anonymous')
score = @me.get('simulatedBy') or 0
@playersAbove = new SimulatorsLeaderboardCollection({order:1, scoreOffset: score, limit: 4})
promises.push @playersAbove.fetch()
if score
@playersBelow = new SimulatorsLeaderboardCollection({order:-1, scoreOffset: score, limit: 4})
promises.push @playersBelow.fetch()
success = (@myRank) =>
promises.push $.ajax "/db/user/me/simulator_leaderboard_rank?scoreOffset=#{score}", {success}
@promise = $.when(promises...)
@promise.then @onLoad
@promise.fail @onFail
@promise
onLoad: =>
return if @destroyed
@loaded = true
@trigger 'sync', @
onFail: (resource, jqxhr) =>
return if @destroyed
@trigger 'error', @, jqxhr
inTopSimulators: ->
return me.id in (user.id for user in @topSimulators.models)
nearbySimulators: ->
l = []
above = @playersAbove.models
l = l.concat(above)
l.reverse()
l.push @me
l = l.concat(@playersBelow.models) if @playersBelow
if @myRank
startRank = @myRank - 4
user.rank = startRank + i for user, i in l
l
allResources: ->
resources = [@topSimulators, @playersAbove, @playersBelow]
return (r for r in resources when r)

View file

@ -1,6 +1,5 @@
RootView = require 'views/kinds/RootView'
Level = require 'models/Level'
Simulator = require 'lib/simulator/Simulator'
LevelSession = require 'models/LevelSession'
CocoCollection = require 'models/CocoCollection'
{teamDataFromLevel} = require './ladder/utils'
@ -9,8 +8,8 @@ application = require 'application'
LadderTabView = require './ladder/ladder_tab'
MyMatchesTabView = require './ladder/my_matches_tab'
SimulateTabView = require './ladder/simulate_tab'
LadderPlayModal = require './ladder/play_modal'
SimulatorsLeaderboardCollection = require 'collections/SimulatorsLeaderboardCollection'
CocoClass = require 'lib/CocoClass'
HIGHEST_SCORE = 1000000
@ -31,8 +30,6 @@ module.exports = class LadderView extends RootView
'application:idle-changed': 'onIdleChanged'
events:
'click #simulate-button': 'onSimulateButtonClick'
'click #simulate-all-button': 'onSimulateAllButtonClick'
'click .play-button': 'onClickPlayButton'
'click a': 'onClickedLink'
@ -44,10 +41,6 @@ module.exports = class LadderView extends RootView
@sessions.fetch({})
@addResourceToLoad(@sessions, 'your_sessions')
@addResourceToLoad(@level, 'level')
@simulatorsLeaderboardData = new SimulatorsLeaderboardData(me)
@addResourceToLoad(@simulatorsLeaderboardData, 'top_simulators')
@simulator = new Simulator()
@listenTo(@simulator, 'statusUpdate', @updateSimulationStatus)
@teams = []
onLoaded: ->
@ -58,11 +51,9 @@ module.exports = class LadderView extends RootView
ctx = super()
ctx.level = @level
ctx.link = "/play/level/#{@level.get('name')}"
ctx.simulationStatus = @simulationStatus
ctx.teams = @teams
ctx.levelID = @levelID
ctx.levelDescription = marked(@level.get('description')) if @level.get('description')
ctx.simulatorsLeaderboardData = @simulatorsLeaderboardData
ctx._ = _
ctx
@ -71,6 +62,7 @@ module.exports = class LadderView extends RootView
return if @loading()
@insertSubView(@ladderTab = new LadderTabView({}, @level, @sessions))
@insertSubView(@myMatchesTab = new MyMatchesTabView({}, @level, @sessions))
@insertSubView(@simulateTab = new SimulateTabView())
@refreshInterval = setInterval(@fetchSessionsAndRefreshViews.bind(@), 20 * 1000)
hash = document.location.hash[1..] if document.location.hash
if hash and not (hash in ['my-matches', 'simulate', 'ladder'])
@ -90,57 +82,9 @@ module.exports = class LadderView extends RootView
onIdleChanged: (e) ->
@fetchSessionsAndRefreshViews() unless e.idle
# Simulations
onSimulateAllButtonClick: (e) ->
submitIDs = _.pluck @leaderboards[@teams[0].id].topPlayers.models, "id"
for ID in submitIDs
$.ajax
url: '/queue/scoring'
method: 'POST'
data:
session: ID
$("#simulate-all-button").prop "disabled", true
$("#simulate-all-button").text "Submitted all!"
onSimulateButtonClick: (e) ->
$("#simulate-button").prop "disabled",true
$("#simulate-button").text "Simulating..."
@simulator.fetchAndSimulateTask()
updateSimulationStatus: (simulationStatus, sessions) ->
@simulationStatus = simulationStatus
try
if sessions?
#TODO: Fetch names from Redis, the creatorName is denormalized
creatorNames = (session.creatorName for session in sessions)
@simulationStatus = "Simulating game between "
for index in [0...creatorNames.length]
unless creatorNames[index]
creatorNames[index] = "Anonymous"
@simulationStatus += (if index != 0 then " and " else "") + creatorNames[index]
@simulationStatus += "..."
catch e
console.log "There was a problem with the named simulation status: #{e}"
$("#simulation-status-text").text @simulationStatus
onClickPlayButton: (e) ->
@showPlayModal($(e.target).closest('.play-button').data('team'))
resimulateAllSessions: ->
postData =
originalLevelID: @level.get('original')
levelMajorVersion: @level.get('version').major
console.log postData
$.ajax
url: '/queue/scoring/resimulateAllSessions'
method: 'POST'
data: postData
complete: (jqxhr) ->
console.log jqxhr.responseText
showPlayModal: (teamID) ->
return @showApologeticSignupModal() if me.get('anonymous')
session = (s for s in @sessions.models when s.get('team') is teamID)[0]
@ -160,55 +104,4 @@ module.exports = class LadderView extends RootView
destroy: ->
clearInterval @refreshInterval
@simulator.destroy()
super()
class SimulatorsLeaderboardData extends CocoClass
###
Consolidates what you need to load for a leaderboard into a single Backbone Model-like object.
###
constructor: (@me) ->
super()
@fetch()
fetch: ->
@topSimulators = new SimulatorsLeaderboardCollection({order:-1, scoreOffset: -1, limit: 20})
promises = []
promises.push @topSimulators.fetch()
unless @me.get('anonymous')
score = @me.get('simulatedBy') or 0
@playersAbove = new SimulatorsLeaderboardCollection({order:1, scoreOffset: score, limit: 4})
promises.push @playersAbove.fetch()
if score
@playersBelow = new SimulatorsLeaderboardCollection({order:-1, scoreOffset: score, limit: 4})
promises.push @playersBelow.fetch()
@promise = $.when(promises...)
@promise.then @onLoad
@promise.fail @onFail
@promise
onLoad: =>
return if @destroyed
@loaded = true
@trigger 'sync', @
onFail: (resource, jqxhr) =>
return if @destroyed
@trigger 'error', @, jqxhr
inTopSimulators: ->
return me.id in (user.id for user in @topSimulators.models)
nearbySimulators: ->
l = []
above = @playersAbove.models
above.reverse()
l = l.concat(above)
l.push @me
l = l.concat(@playersBelow.models) if @playersBelow
l
allResources: ->
resources = [@topSimulators, @playersAbove, @playersBelow]
return (r for r in resources when r)

View file

@ -155,6 +155,22 @@ UserHandler = class UserHandler extends Handler
res.end()
getSimulatorLeaderboard: (req, res) ->
queryParameters = @getSimulatorLeaderboardQueryParameters(req)
leaderboardQuery = User.find(queryParameters.query).select("name simulatedBy simulatedFor").sort({"simulatedBy":queryParameters.sortOrder}).limit(queryParameters.limit)
leaderboardQuery.exec (err, otherUsers) ->
otherUsers = _.reject otherUsers, _id: req.user._id if req.query.scoreOffset isnt -1
otherUsers ?= []
res.send(otherUsers)
res.end()
getMySimulatorLeaderboardRank: (req, res) ->
req.query.order = 1
queryParameters = @getSimulatorLeaderboardQueryParameters(req)
User.count queryParameters.query, (err, count) =>
return @sendDatabaseError(res, err) if err
res.send JSON.stringify(count + 1)
getSimulatorLeaderboardQueryParameters: (req) ->
@validateSimulateLeaderboardRequestParameters(req)
query = {}
@ -167,14 +183,7 @@ UserHandler = class UserHandler extends Handler
sortOrder = 1 if req.query.order is 1
else
query.simulatedBy = {"$exists": true}
leaderboardQuery = User.find(query).select("name simulatedBy simulatedFor").sort({"simulatedBy":sortOrder}).limit(limit)
leaderboardQuery.exec (err, otherUsers) ->
otherUsers = _.reject otherUsers, _id: req.user._id if req.query.scoreOffset isnt -1
otherUsers ?= []
res.send(otherUsers)
res.end()
{query: query, sortOrder: sortOrder, limit: limit}
validateSimulateLeaderboardRequestParameters: (req) ->
req.query.order = parseInt(req.query.order) ? -1
@ -202,6 +211,7 @@ UserHandler = class UserHandler extends Handler
return @getLevelSessions(req, res, args[0]) if args[1] is 'level.sessions'
return @getCandidates(req, res) if args[1] is 'candidates'
return @getSimulatorLeaderboard(req, res, args[0]) if args[1] is 'simulatorLeaderboard'
return @getMySimulatorLeaderboardRank(req, res, args[0]) if args[1] is 'simulator_leaderboard_rank'
return @sendNotFoundError(res)
super(arguments...)