PageRenderTime 41ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/src/blokus/static/js/blokus.js

https://bitbucket.org/bahman/comp3001-group-blokus
JavaScript | 183 lines | 162 code | 18 blank | 3 comment | 26 complexity | 99c09c3338c3b13508773ac73fa8862e MD5 | raw file
Possible License(s): BSD-3-Clause
  1. window.blokus = (function ($, _, Backbone, Raphael) { // Create the blokus core module
  2. "use strict";
  3. var restRootUrl = "/api/rest/",
  4. keyDownMappings = {}, // Maps of key-codes to array of functions to call when key is released
  5. keyUpMappings = {}, // Maps of key-codes to array of functions to call when key is pressed
  6. blokusDeferreds = [], // List of jQuery Deferred objects to be resolved before starting blokus
  7. authDfd = undefined; // Deferred object that will prevent blokus loading before logged in user is known
  8. var getCurrentUser = function(callback) { // Get currently logged in user (or anonymous user if not logged in)
  9. $.ajax({
  10. url: "/get_logged_in_user/",
  11. dataType: 'json',
  12. success: function (model) {
  13. blokus.user.set(model);
  14. blokus.userProfile.set(model.userprofile);
  15. authDfd.resolve();
  16. if (callback != null) callback();
  17. },
  18. error: function () {
  19. blokus.showError("Failed to create guest user account!");
  20. authDfd.reject();
  21. }
  22. });
  23. };
  24. $(document).ready(function () { // Note below, a "view" in the following context is what might be considered a "page" - lobby, game, help etc
  25. var currentView, // Reference to the current view
  26. blokus = window.blokus,
  27. switchToView = function (view, new_game_id) { // Switch to a different view
  28. var game_id = blokus.userProfile.get("game_id");
  29. if (game_id != null && new_game_id != game_id) {
  30. blokus.showYesNo("You are currently in a game. Would you like to continue it?", function () {
  31. blokus.router.navigate("game/" + game_id, true);
  32. }, function () {
  33. blokus.waiting(true);
  34. blokus.userProfile.save({ status: "offline" }, { success: function () {
  35. blokus.waiting(false);
  36. }});
  37. }, true);
  38. }
  39. var oldView = currentView,
  40. $newview = $(view.render().el); // Render new view
  41. if (oldView) {
  42. $(oldView.el).fadeOut(200, function () {// Fade out old view then remove
  43. oldView.remove();
  44. oldView.trigger("close"); // Run any view-specific cleanup operations
  45. oldView.unbind(); // Unbind any event bindings (to avoid object not being garbage-collected)
  46. });
  47. }
  48. currentView = view;
  49. $("#container").append($newview);
  50. //Ensure input field labels are hidden if they contain text
  51. $('input, textarea').each(function() {
  52. var input = $(this);
  53. if (input.val()) {
  54. input.prev('span').css('visibility', 'hidden')
  55. }
  56. });
  57. };
  58. blokus.router = new (Backbone.Router.extend({ // Make a new router, which binds hash-urls to events. Each hash-url should load a view.
  59. routes: {
  60. "": "lobby", // When there is no hash url
  61. "lobby": "lobby",
  62. "lobby/:hash": "privatelobby",
  63. "game/:id": "game",
  64. "register": "register"
  65. },
  66. lobby: function () { switchToView(new blokus.LobbyView()); },
  67. privatelobby: function(hash) {
  68. var lobbyView = new blokus.LobbyView();
  69. switchToView(lobbyView);
  70. lobbyView.selectGameType("private", null, hash);
  71. },
  72. game: function (id) { switchToView(new blokus.GameView({ id: id }), id); },
  73. register: function () { switchToView(new blokus.RegisterView()); }
  74. }))();
  75. authDfd = new $.Deferred();
  76. blokusDeferreds.push(authDfd);
  77. blokus.user = new blokus.User(); // Will be the logged in user
  78. blokus.userProfile = new blokus.UserProfile();
  79. getCurrentUser(null);
  80. // Bind all key mappings
  81. $(window).keyup(function (e) {
  82. _(keyUpMappings[e.keyCode]).each(function (f) { f.call(); });
  83. }).keydown(function (e) {
  84. _(keyDownMappings[e.keyCode]).each(function (f) { f.call(); });
  85. });
  86. $(window).bind('beforeunload', function(){
  87. if (blokus.userProfile.get("game_id") == null) {
  88. blokus.userProfile.save({status: "offline"});
  89. } else {
  90. return "Are you sure you wish to quit."
  91. }
  92. });
  93. blokus.pieceMasters = new blokus.PieceMasterCollection();
  94. var pieceMastersFetched = new $.Deferred()
  95. blokusDeferreds.push(pieceMastersFetched);
  96. blokus.pieceMasters.fetch({
  97. success: function (collection) { if (collection.length > 0) pieceMastersFetched.resolve(); else pieceMastersFetched.reject(); },
  98. error: function () { pieceMastersFetched.reject(); }
  99. });
  100. $.when.apply(undefined, blokusDeferreds).then(function () { Backbone.history.start(); }) // Start blokus when everything is loaded
  101. .fail(function () { blokus.showError("Error initializing. Failed to get pieceMasters? (Have you run syncdb?)"); });
  102. });
  103. Array.prototype.clean = function (deleteValue) { // Remove all occurrences of specified value from an array
  104. for (var i = 0; i < this.length; i++) {
  105. if (this[i] == deleteValue) {
  106. this.splice(i, 1);
  107. i--;
  108. }
  109. }
  110. return this;
  111. };
  112. var msgPersist = false;
  113. return {
  114. showError: function (msg) {
  115. var $error = $('<div class="error">' + msg + '</div>').hide();
  116. $("#errorstack").append($error);
  117. $error.slideDown();
  118. $error.click(function() { $error.slideUp(); });
  119. },
  120. showMsg: function (msg, timeout, persist, callback) {
  121. if (msgPersist) return;
  122. var $msg = $("#msgcontainer").fadeIn();
  123. $msg.find(".content").html(msg);
  124. $msg.find(".okButtons").show().siblings().hide();
  125. $msg.find(".close").unbind("click").click(function () { $msg.fadeOut(); if(callback) callback.call(); });
  126. if (timeout) { setTimeout(function() { msgPersist = false; $msg.fadeOut(); }, timeout); }
  127. msgPersist = persist || false;
  128. },
  129. showYesNo: function (msg, yesCallback, noCallback, persist) {
  130. if (msgPersist) return;
  131. var $msg = $("#msgcontainer").fadeIn();
  132. $msg.find(".content").html(msg);
  133. $msg.find(".yesNoButtons").show().siblings().hide();
  134. $msg.find(".yes").unbind("click").click(yesCallback).click(function() { msgPersist = false; $msg.fadeOut() });
  135. $msg.find(".no").unbind("click").click(noCallback).click(function () { msgPersist = false; $msg.fadeOut() });
  136. msgPersist = persist || false;
  137. },
  138. waiting: function (on) {
  139. if (on) $("#blokuswaiting").fadeIn();
  140. else $("#blokuswaiting").fadeOut();
  141. },
  142. getCurrentUser: getCurrentUser,
  143. urls: {
  144. user: restRootUrl + "user/",
  145. userProfile: restRootUrl + "userprofile/",
  146. game: restRootUrl + "game/",
  147. pieceMaster: restRootUrl + "piecemaster/",
  148. player: restRootUrl + "player/",
  149. piece: restRootUrl + "piece/"
  150. },
  151. mapKeyUp: function (keyCode, callback) { // Bind a function to a key being released
  152. if (!keyUpMappings.hasOwnProperty(keyCode)) { keyUpMappings[keyCode] = []; }
  153. keyUpMappings[keyCode].push(callback);
  154. },
  155. mapKeyDown: function (keyCode, callback) { // Bind a function to a key being pressed
  156. if (!keyDownMappings.hasOwnProperty(keyCode)) { keyDownMappings[keyCode] = []; }
  157. keyDownMappings[keyCode].push(callback);
  158. },
  159. // Get template source
  160. getTemplate: function (name) {
  161. return _.template($('#' + name + '-template').html());
  162. },
  163. haloArr: new Array()
  164. };
  165. }(jQuery, _, Backbone, Raphael));