textgame.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. if(MIDAS == undefined) {
  2. var MIDAS = {};
  3. }
  4. MIDAS.TextGame = function(gameConsole) {
  5. var self = this;
  6. var polling = null;
  7. var playerId = null;
  8. var lastWorldSync = 0;
  9. var lastPlayerSync = 0;
  10. var playerQueue = [];
  11. var worldQueue = [];
  12. this.requiresUpdate = false;
  13. this.init = function() {
  14. playerId = Math.floor(10000 * Math.random() + 1);
  15. gameConsole.register(input);
  16. gameConsole.init();
  17. serverInitialize();
  18. polling = setInterval(update, 1000);
  19. this.requiresUpdate = true;
  20. };
  21. function serverInitialize() {
  22. var submitData = {
  23. "initialize" : true
  24. , "playerId":playerId
  25. };
  26. $.ajax({
  27. type: 'POST'
  28. , url: '/?a=textgame'
  29. , data: submitData
  30. , success: initializeCallback
  31. , dataType: 'json'
  32. });
  33. }
  34. function initializeCallback(response) {
  35. lastWorldSync = response.worldSync;
  36. lastPlayerSync = 0;
  37. worldQueue = response.world;
  38. self.requiresUpdate = false;
  39. console.log("Starting game at " + lastWorldSync);
  40. }
  41. function update() {
  42. if(self.requiresUpdate) {
  43. var submitData = {
  44. "lastWorldSync":lastWorldSync
  45. , "playerId":playerId
  46. , "player":playerQueue
  47. , "playerSync":lastPlayerSync
  48. };
  49. console.log("sending update #" + lastPlayerSync);
  50. $.ajax({
  51. type: 'POST'
  52. , url: '/?a=textgame'
  53. , data: submitData
  54. , success: updateCallback
  55. , dataType: 'json'
  56. });
  57. self.requiresUpdate = false;
  58. }
  59. if(worldQueue.length > 0) {
  60. var event = worldQueue.shift();
  61. gameConsole.output("#"+event.userid + " "+event.command+"s \"" + event.data + "\"");
  62. }
  63. };
  64. function updateCallback(response) {
  65. if(response.result == "update") {
  66. console.log("received update from version #" + response.playerSync);
  67. if(response.playerSync < lastPlayerSync) {
  68. playerQueue = playerQueue.slice(lastPlayerSync - response.playerSync);
  69. } else {
  70. playerQueue = [];
  71. }
  72. lastWorldSync = response.worldSync;
  73. worldQueue = response.world;
  74. self.requiresUpdate = true;
  75. }
  76. };
  77. function input(message) {
  78. self.requiresUpdate = true;
  79. playerQueue.push({"playerId":playerId, "command" : message, "time" : Math.round(new Date().getTime() / 1000)});
  80. lastPlayerSync++;
  81. //gameConsole.output("I do not understand \""+message+"\"");
  82. };
  83. };