Skip to content

Commit

Permalink
more mithril play
Browse files Browse the repository at this point in the history
  • Loading branch information
ornicar committed Oct 3, 2014
1 parent 18e428c commit 51b740d
Show file tree
Hide file tree
Showing 11 changed files with 188 additions and 65 deletions.
36 changes: 10 additions & 26 deletions app/controllers/Round.scala
Original file line number Diff line number Diff line change
Expand Up @@ -142,32 +142,16 @@ object Round extends LilaController with TheftPrevention {

private def end(pov: Pov, player: Boolean)(implicit ctx: Context) = {
import templating.Environment.playerLink
negotiate(
html = pov.game.tournamentId ?? TournamentRepo.byId map { tour =>
val players = pov.game.players.collect {
case p if p.isHuman => p.color.name -> playerLink(p, withStatus = true).body
}.toMap
val table = if (player) html.round.table.end(pov, tour) else html.round.table.watch(pov)
Ok(Json.obj(
"players" -> players,
"side" -> html.game.side(pov, tour, withTourStanding = player).toString,
"table" -> table.toString)) as JSON
},
api = apiVersion => fuccess(Ok(Json.obj(
"isEnd" -> pov.game.finished
) ++ pov.game.finished.fold(Json.obj(
"winner" -> pov.game.winner.map(w =>
Json.obj(
"userId" -> w.userId,
"name" -> lila.game.Namer.playerString(w)(Env.user.lightUser),
"isMe" -> pov.player.isWinner
)),
"status" -> Json.obj(
"id" -> pov.game.status.id,
"name" -> pov.game.status.name,
"translated" -> lila.app.templating.Environment.gameEndStatus(pov.game).body)
), Json.obj())))
)
pov.game.tournamentId ?? TournamentRepo.byId map { tour =>
val players = pov.game.players.collect {
case p if p.isHuman => p.color.name -> playerLink(p, withStatus = true).body
}.toMap
val table = if (player) html.round.table.end(pov, tour) else html.round.table.watch(pov)
Ok(Json.obj(
"players" -> players,
"side" -> html.game.side(pov, tour, withTourStanding = player).toString,
"table" -> table.toString)) as JSON
}
}

def continue(id: String, mode: String) = Open { implicit ctx =>
Expand Down
15 changes: 14 additions & 1 deletion app/views/round/player.scala.html
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,20 @@
trans.takebackPropositionSent,
trans.yourOpponentProposesATakeback,
trans.youHaveNbSecondsToMakeYourFirstMove,
trans.thisPlayerUsesChessComputerAssistance
trans.thisPlayerUsesChessComputerAssistance,
trans.gameAborted,
trans.checkmate,
trans.whiteResigned,
trans.blackResigned,
trans.stalemate,
trans.whiteLeftTheGame,
trans.blackLeftTheGame,
trans.draw,
trans.timeOut,
trans.premoveEnabledClickAnywhereToCancel,
trans.playingRightNow,
trans.whiteIsVictorious,
trans.blackIsVictorious
)))
};
}
Expand Down
27 changes: 19 additions & 8 deletions modules/i18n/src/main/JsDump.scala
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,12 @@ private[i18n] final class JsDump(

def apply: Funit = Future {
pathFile.mkdir
pool.nonDefaultLangs foreach write
pool.nonDefaultLangs foreach write(jsMessages)
writeRefs
writeFullJson
} void

private val messages = List(
private val jsMessages = List(
keys.standard,
keys.rated,
keys.casual,
Expand Down Expand Up @@ -61,21 +62,21 @@ private[i18n] final class JsDump(

private val pathFile = new File(path)

private def write(lang: Lang) {
val code = dump(lang)
private def write(messages: List[I18nKey])(lang: Lang) {
val code = s"""lichess_translations = ${dump(messages, lang)};"""
val file = new File("%s/%s.js".format(pathFile.getCanonicalPath, lang.language))
val out = new PrintWriter(file)
try { out.print(code) }
finally { out.close }
}

private def dump(lang: Lang): String =
"""lichess_translations = {%s};""".format(messages map { key =>
private def dump(messages: List[I18nKey], lang: Lang): String =
messages.map { key =>
""""%s":"%s"""".format(escape(key.to(pool.default)()), escape(key.to(lang)()))
} mkString ",")
}.mkString("{", ",", "}")

private def writeRefs {
val code = pool.names.toList.sortBy (_._1).map {
val code = pool.names.toList.sortBy(_._1).map {
case (code, name) => s"""["$code","$name"]"""
}.mkString("[", ",", "]")
val file = new File("%s/refs.json".format(pathFile.getCanonicalPath))
Expand All @@ -84,5 +85,15 @@ private[i18n] final class JsDump(
finally { out.close }
}

private def writeFullJson {
pool.langs foreach { lang =>
val code = dump(keys.keys, lang)
val file = new File("%s/%s.all.json".format(pathFile.getCanonicalPath, lang.language))
val out = new PrintWriter(file)
try { out.print(code) }
finally { out.close }
}
}

private def escape(text: String) = text.replace(""""""", """\"""")
}
21 changes: 16 additions & 5 deletions modules/round/src/main/JsonView.scala
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ final class JsonView(
pov: Pov,
pref: Pref,
apiVersion: Int,
tourOption: Option[lila.tournament.Tournament],
playerUser: Option[User]): Fu[JsObject] =
getVersion(pov.game.id) zip
(pov.opponent.userId ?? UserRepo.byId) zip
Expand All @@ -34,20 +35,26 @@ final class JsonView(
Json.obj(
"game" -> Json.obj(
"id" -> gameId,
"variant" -> game.variant.key,
"variant" -> Json.obj(
"key" -> game.variant.key,
"name" -> game.variant.name,
"short" -> game.variant.shortName,
"title" -> game.variant.title),
"speed" -> game.speed.key,
"perf" -> PerfPicker.key(game),
"rated" -> game.rated,
"fen" -> (Forsyth >> game.toChess),
"moves" -> game.pgnMoves.mkString(" "),
"started" -> game.started,
"finished" -> game.finishedOrAborted,
"clock" -> game.hasClock,
"clockRunning" -> game.isClockRunning,
"player" -> game.turnColor.name,
"winner" -> game.winnerColor.map(_.name),
"turns" -> game.turns,
"startedAtTurn" -> game.startedAtTurn,
"lastMove" -> game.castleLastMoveTime.lastMoveString),
"lastMove" -> game.castleLastMoveTime.lastMoveString,
"status" -> Json.obj(
"id" -> pov.game.status.id,
"name" -> pov.game.status.lowerName)),
"clock" -> game.clock.map(clockJson),
"player" -> Json.obj(
"id" -> playerId,
Expand Down Expand Up @@ -91,8 +98,12 @@ final class JsonView(
"t" -> text)
})
},
"tournament" -> tourOption.map { tour =>
Json.obj(
"id" ->game.tournamentId
)
},
"possibleMoves" -> possibleMoves(pov),
"tournamentId" -> game.tournamentId,
"poolId" -> game.poolId,
"takebackable" -> takebackable)
}
Expand Down
3 changes: 2 additions & 1 deletion ui/round/src/ctrl.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ var throttle = require('lodash-node/modern/functions/throttle');
var chessground = require('chessground');
var data = require('./data');
var round = require('./round');
var status = require('./status');
var ground = require('./ground');
var socket = require('./socket');
var clockCtrl = require('./clock/ctrl');
Expand Down Expand Up @@ -38,7 +39,7 @@ module.exports = function(cfg, router, i18n, socketSend) {
) : false;

this.isClockRunning = function() {
return !this.data.game.finished && ((this.data.game.turns - this.data.game.startedAtTurn) > 1 || this.data.game.clockRunning);
return round.playable(this.data) && ((this.data.game.turns - this.data.game.startedAtTurn) > 1 || this.data.game.clockRunning);
}.bind(this);

this.clockTick = function() {
Expand Down
2 changes: 1 addition & 1 deletion ui/round/src/main.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
var ctrl = require('./ctrl');
var view = require('./view');
var view = require('./view/main');

module.exports = function(element, config, router, i18n, socketSend) {

Expand Down
25 changes: 14 additions & 11 deletions ui/round/src/round.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,5 @@
var mapValues = require('lodash-node/modern/objects/mapValues');

function isGamePlaying(data) {
return data.game.started && !data.game.finished;
}

function isPlayerPlaying(data) {
return isGamePlaying(data) && !data.player.spectator;
}
var status = require('./status');

function parsePossibleMoves(possibleMoves) {
return mapValues(possibleMoves, function(moves) {
Expand All @@ -15,7 +8,11 @@ function parsePossibleMoves(possibleMoves) {
}

function playable(data) {
return data.game.started && !data.game.finished;
return status.started(data) && !status.finished(data);
}

function isPlayerPlaying(data) {
return playable(data) && !data.player.spectator;
}

function mandatory(data) {
Expand All @@ -39,17 +36,23 @@ function resignable(data) {
}

function getPlayer(data, color) {
return data.player.color == color ? data.player : data.opponent;
if (data.player.color == color) return data.player;
if (data.opponent.color == color) return data.opponent;
return null;
}

function nbMoves(data, color) {
return data.turns + (color == 'white' ? 1 : 0) / 2;
}

module.exports = {
isGamePlaying: isGamePlaying,
isPlayerPlaying: isPlayerPlaying,
playable: playable,
abortable: abortable,
takebackable: takebackable,
drawable: drawable,
resignable: resignable,
mandatory: mandatory,
getPlayer: getPlayer,
parsePossibleMoves: parsePossibleMoves
};
6 changes: 2 additions & 4 deletions ui/round/src/socket.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@ module.exports = function(send, ctrl) {
xhr.reload(ctrl.data).then(ctrl.reload);
},
threefoldRepetition: function() {
// ???
// show the draw button
xhr.reload(ctrl.data).then(ctrl.reload);
},
clock: function(o) {
if (ctrl.clock) ctrl.clock.update(o.white, o.black);
Expand All @@ -78,9 +79,6 @@ module.exports = function(send, ctrl) {
m.endComputation();
},
end: function() {
m.startComputation();
ctrl.data.game.finished = true;
m.endComputation();
ground.end(ctrl.chessground);
xhr.reload(ctrl.data).then(ctrl.reload);
}
Expand Down
36 changes: 36 additions & 0 deletions ui/round/src/status.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// https://github.com/ornicar/scalachess/blob/master/src/main/scala/Status.scala

var ids = {
created: 10,
started: 20,
aborted: 25,
mate: 30,
resign: 31,
stalemate: 32,
timeout: 33,
draw: 34,
outoftime: 35,
cheat: 36,
noStart: 37,
variantEnd: 60
};

function started(data) {
return data.game.status.id >= ids.started;
}

function finished(data) {
return data.game.status.id >= ids.mate;
}

function aborted(data) {
return data.game.status.id == ids.aborted;
}


module.exports = {
ids: ids,
started: started,
finished: finished,
aborted: aborted
};
38 changes: 30 additions & 8 deletions ui/round/src/view.js → ui/round/src/view/main.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
var map = require('lodash-node/modern/collections/map');
var chessground = require('chessground');
var round = require('./round');
var round = require('../round');
var status = require('../status');
var opposite = chessground.util.opposite;
var classSet = chessground.util.classSet;
var partial = chessground.util.partial;
var clockView = require('./clock/view');
var renderClock = require('../clock/view');
var renderStatus = require('./status');
var m = require('mithril');

function renderOpponent(ctrl) {
Expand Down Expand Up @@ -38,7 +40,25 @@ function renderOpponent(ctrl) {
);
}

function renderTableEnd(ctrl) {}
function renderResult(ctrl) {
var winner = round.getPlayer(ctrl.data, ctrl.data.game.winner);
return winner ? m('div.lichess_player.' + winner.color, [
m('div.cg-piece.king.' + winner.color),
m('p', [
renderStatus(ctrl),
m('br'),
ctrl.trans(winner.color == 'white' ? 'whiteIsVictorious' : 'blackIsVictorious')
])
]) :
m('div.lichess_player', renderStatus(ctrl));
}

function renderTableEnd(ctrl) {
var d = ctrl.data;
return [
m('div.lichess_current_player', renderResult(ctrl))
];
}

function renderButton(ctrl, condition, icon, hint, socketMsg) {
return condition(ctrl.data) ? m('button', {
Expand Down Expand Up @@ -96,7 +116,9 @@ function renderTablePlay(ctrl) {
m('a.button[data-icon=L]', {
onclick: partial(ctrl.socket.send, 'takeback-no', null)
}, ctrl.trans('decline')),
]) : null,
]) : null, (round.mandatory(d) && round.nbMoves(d, d.player.color) === 0) ? m('div[data-icon=j]',
ctrl.trans('youHaveNbSecondsToMakeYourFirstMove')
) : null
];
}

Expand All @@ -111,24 +133,24 @@ module.exports = function(ctrl) {
}, [
ctrl.data.blindMode ? m('div#lichess_board_blind') : null,
m('div.lichess_board_wrap', ctrl.data.blindMode ? null : [
m('div.lichess_board.' + ctrl.data.game.variant, chessground.view(ctrl.chessground)),
m('div.lichess_board.' + ctrl.data.game.variant.key, chessground.view(ctrl.chessground)),
m('div#premove_alert', ctrl.trans('premoveEnabledClickAnywhereToCancel'))
]),
m('div.lichess_ground',
m('div.lichess_table_wrap', [
(ctrl.clock && !ctrl.data.blindMode) ? clockView(ctrl.clock, opposite(ctrl.data.player.color), "top", clockRunningColor) : null,
(ctrl.clock && !ctrl.data.blindMode) ? renderClock(ctrl.clock, opposite(ctrl.data.player.color), "top", clockRunningColor) : null,
m('div', {
class: 'lichess_table onbg ' + classSet({
'table_with_clock': ctrl.clock,
'finished': ctrl.data.game.finished
'finished': status.finished(ctrl.data)
})
}, [
m('div.lichess_opponent', renderOpponent(ctrl)),
m('div.lichess_separator'),
m('div.table_inner',
round.playable(ctrl.data) ? renderTablePlay(ctrl) : renderTableEnd(ctrl)
)
]), (ctrl.clock && !ctrl.data.blindMode) ? clockView(ctrl.clock, ctrl.data.player.color, "bottom", clockRunningColor) : null,
]), (ctrl.clock && !ctrl.data.blindMode) ? renderClock(ctrl.clock, ctrl.data.player.color, "bottom", clockRunningColor) : null,
])
)
]);
Expand Down
Loading

0 comments on commit 51b740d

Please sign in to comment.