123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- if(MIDAS == undefined) {
- var MIDAS = {};
- }
- MIDAS.TextGame = function(gameConsole) {
- var self = this;
- var polling = null;
- var playerId = null;
- var lastWorldSync = 0;
- var lastPlayerSync = 0;
- var playerQueue = [];
- var worldQueue = [];
- this.requiresUpdate = false;
- this.init = function() {
- playerId = Math.floor(10000 * Math.random() + 1);
- gameConsole.register(input);
- gameConsole.init();
- serverInitialize();
- polling = setInterval(update, 1000);
- this.requiresUpdate = true;
- };
- function serverInitialize() {
- var submitData = {
- "initialize" : true
- , "playerId":playerId
- };
- $.ajax({
- type: 'POST'
- , url: '/?a=textgame'
- , data: submitData
- , success: initializeCallback
- , dataType: 'json'
- });
- }
- function initializeCallback(response) {
- lastWorldSync = response.worldSync;
- lastPlayerSync = 0;
- worldQueue = response.world;
- self.requiresUpdate = false;
- console.log("Starting game at " + lastWorldSync);
- }
- function update() {
- if(self.requiresUpdate) {
- var submitData = {
- "lastWorldSync":lastWorldSync
- , "playerId":playerId
- , "player":playerQueue
- , "playerSync":lastPlayerSync
- };
- console.log("sending update #" + lastPlayerSync);
- $.ajax({
- type: 'POST'
- , url: '/?a=textgame'
- , data: submitData
- , success: updateCallback
- , dataType: 'json'
- });
- self.requiresUpdate = false;
- }
- if(worldQueue.length > 0) {
- var event = worldQueue.shift();
- gameConsole.output("#"+event.userid + " "+event.command+"s \"" + event.data + "\"");
- }
- };
- function updateCallback(response) {
- if(response.result == "update") {
- console.log("received update from version #" + response.playerSync);
- if(response.playerSync < lastPlayerSync) {
- playerQueue = playerQueue.slice(lastPlayerSync - response.playerSync);
- } else {
- playerQueue = [];
- }
- lastWorldSync = response.worldSync;
- worldQueue = response.world;
- self.requiresUpdate = true;
- }
- };
- function input(message) {
- self.requiresUpdate = true;
- playerQueue.push({"playerId":playerId, "command" : message, "time" : Math.round(new Date().getTime() / 1000)});
- lastPlayerSync++;
- //gameConsole.output("I do not understand \""+message+"\"");
- };
- };
|