webclient/js/Games.js

82 lines
2.3 KiB
JavaScript
Raw Normal View History

import Messaging;
import player from Room;
import Save;
import Session;
import Table;
import Time;
var metadata = Table.make(function(o) {return o.value.date;});
metadata.insertAll(Save.get('games.metadata') || {});
initMessageHandlers();
return {
metadata: metadata,
proposal: proposal
};
function makeMetadata(state) {
var sessionKey = Session.getKey();
return Time.timestamp({
vs: player(state.public.nextPlayer[sessionKey]),
yourTurn: state.public.playing == sessionKey
});
}
function proposal(playerID, yourTurn) {
metadata.insert(
playerID,
Time.timestamp({vs: player(playerID), yourTurn: yourTurn})
);
}
function pushState(gameID, state) {
var latestPath = "games.state." + gameID + ".latest";
var formerPath = "games.state." + gameID + ".former";
var former = Save.get(latestPath);
if(former != undefined) {
Save.set(formerPath, former);
}
Save.set(latestPath, state);
}
function compare(gameCoordinatesA, gameCoordinatesB) {
if(gameCoordinatesA.month < gameCoordinatesB.month) {
return -1;
} else if(gameCoordinatesA.month > gameCoordinatesB.month) {
return 1;
} else if(gameCoordinatesA.turn < gameCoordinatesB.turn) {
return -1;
} else if(gameCoordinatesA.turn > gameCoordinatesB.turn) {
return 1;
} else {
return 0;
}
}
function initMessageHandlers() {
Messaging.addEventListener(["Game"], function(o) {
var gameID = o.state.public.coordinates.gameID;
var metadata = makeMetadata(o.state);
pushState(gameID, o.state);
Save.set("games.metadata." + gameID, metadata);
metadata.insert(gameID, metadata);
});
Messaging.addEventListener(["Relay", "Sync"], function(o) {
var gameID = o.message.latestKnown.gameID;
var latestKnownHere = Save.get("games.state." + gameID + ".latest");
switch(compare(latestKnownHere, o.message.latestKnown)) {
case -1: Messaging.send({tag: "Yield", onGameID: gameID});
case 1: Messaging.send({tag: "Sync", latestKnown: latestKnownHere});
}
});
Messaging.addEventListener(["Relay", "Yield"], function(o) {
var gameID = o.message.latestKnown.gameID;
var latestKnownHere = Save.get("games.message." + gameID + ".latest");
if(o.from == latestKnownHere.public.nextPlayer[Session.getKey()]) {
Messaging.send({tag: "Share", gameSave: latestKnownHere});
}
});
}