codingOL

GameForest.js

Sep 10th, 2013
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /// <reference path="guid.js" />
  2. /// <reference path="jquery.js" />
  3. /// <reference path="promise.js" />
  4. /// <reference path="index.html" />
  5.  
  6. 'use strict';
  7.  
  8. // Set this to true when debugging to let Game Forest show alert messages when something went wrong.
  9. var GameForestVerboseMessaging  = false;
  10.  
  11. // Set this to localhost when debugging and to game-forest.cloudapp.net when submitting it to Game Forest.
  12. var GameForestCloudUrl          = "game-forest.cloudapp.net";
  13.  
  14. var GFX_STATUS_LOBBY            = 0,
  15.     GFX_STATUS_CHOOSE           = 1,
  16.     GFX_STATUS_PLAYING          = 2,
  17.     GFX_STATUS_FINISHED         = 4;
  18.  
  19. // Game Forest client API
  20. var GameForest                  = function (gameId, lobbyId, sessionId)
  21. {
  22.     // checker to see if gameforest can initialize
  23.     if (!Guid.isGuid(gameId)    ||
  24.         !Guid.isGuid(lobbyId)   ||
  25.         !Guid.isGuid(sessionId))
  26.     {
  27.         console.error("Parameters required to start GameForest is either missing or in an invalid state.");
  28.  
  29.         if (GameForestVerboseMessaging)
  30.         {
  31.             alert("Parameters required to start GameForest is either missing or in an invalid state.");
  32.         }
  33.  
  34.         return;
  35.     }
  36.  
  37.     // ------------------------------------------------------------------------------------------------
  38.    
  39.     // critical variables
  40.  
  41.     this.lobbyStatus            = 0;
  42.  
  43.     this.gameId                 = gameId;                   // the unique identifier of the game
  44.     this.lobbyId                = lobbyId;                  // the unique identifier of the lobby the player is in
  45.     this.sessionId              = sessionId;                // the unique identifier of the current session of the player
  46.  
  47.     this.connectionId           = "";                       // the unique identifier for the websocket connection
  48.  
  49.     this.wsConnection           = new WebSocket("ws://localhost:8084");     // websocket object
  50.  
  51.     // ------------------------------------------------------------------------------------------------
  52.  
  53.     // helper methods
  54.  
  55.     function sendRequest        (url, type, onSuccess, onError)
  56.     {
  57.         var httpURL = "http://" + cloudURL + ":" + cloudPRT + "/service" + url;
  58.  
  59.         console.log("Doing " + type + " request on URL " + httpURL);
  60.  
  61.         var response = $.ajax({
  62.             url:    httpURL,
  63.             async:  true,
  64.             type:   type,
  65.             cache:  false
  66.         });
  67.  
  68.         response.success(onSuccess);
  69.         response.fail(function (a, b, c)
  70.         {
  71.             onError(b, c);
  72.         });
  73.     }
  74.  
  75.     function constructWSRequest (ws, cid, sid, subject, payload)
  76.     {
  77.         if (payload.length > 0)
  78.             console.log("Sending message with subject " + subject + " and payload " + payload);
  79.         else
  80.             console.log("Sending message with subject " + subject);
  81.  
  82.         ws.send(JSON.stringify(
  83.             {
  84.                 "ConnectionId": cid,
  85.                 "SessionId":    sid,
  86.                 "Subject":      subject,
  87.                 "Message":      payload
  88.             }));
  89.     }
  90.  
  91.     // ------------------------------------------------------------------------------------------------
  92.  
  93.     // URL of the game forest server and its port. DO NOT EVER EVER EVER CHANGE THIS IF YOU DON'T WANT YOUR GAME TO EXPLODE. >:)
  94.  
  95.     var cloudURL                = GameForestCloudUrl,
  96.         cloudPRT                = 1193,
  97.         wsPromise               = new promise.Promise();    // promise instance for websocket messages
  98.  
  99.     // internal game forest messages
  100.  
  101.     var GFX_INIT_CONNECTION     = "GFX_INIT_CONNECTION",    // message to initiate connection with a game forest server
  102.         GFX_STOP_CONNECTION     = "GFX_STOP_CONNECTION",    // message to terminate connection with a game forest server
  103.  
  104.     // messages the client will send to the server
  105.  
  106.         GFX_ASK_DATA            = "GFX_ASK_DATA",           // message to ask for the game's data
  107.         GFX_ASK_USER_DATA       = "GFX_ASK_USER_DATA",      // message to ask for the user's game data
  108.  
  109.         GFX_SEND_DATA           = "GFX_SEND_DATA",          // message to send game data
  110.         GFX_SEND_USER_DATA      = "GFX_SEND_USER_DATA",     // message to send user game data
  111.  
  112.         GFX_FINISH              = "GFX_GAME_FINISH",        // message to inform the server the game is finished
  113.  
  114.         GFX_GAME_START          = "GFX_GAME_START",         // message to inform the server the game should start
  115.         GFX_GAME_START_CONFIRM  = "GFX_GAME_START_CONFIRM", // message to inform the server the client has acknowledged the GFX_GAME_START message
  116.  
  117.         GFX_NEXT_TURN           = "GFX_NEXT_TURN",          // message to inform the server that its the next player's turn
  118.         GFX_CONFIRM_TURN        = "GFX_CONFIRM_TURN",       // message to change the player's order
  119.  
  120.     // messages the client will receive from the server
  121.  
  122.         GFX_START_GAME          = "GFX_START_GAME",         // message to inform the client the game has started
  123.         GFX_START_CHOICE        = "GFX_START_CHOICE",       // message to inform the client the game should display the order choose screen
  124.         GFX_GAME_FINISHED       = "GFX_GAME_FINISHED",      // message to inform the client the game has finished
  125.         GFX_TURN_START          = "GFX_TURN_START",         // message to inform the client its the player's turn
  126.         GFX_TURN_CHANGED        = "GFX_TURN_CHANGED",       // message to inform the client the player's turn has changed
  127.         GFX_TURN_RESOLVE        = "GFX_TURN_RESOLVE",       // message to inform the client the player's orders are updated
  128.         GFX_DATA_CHANGED        = "GFX_DATA_CHANGED";       // message to inform the client the game's data is changed
  129.  
  130.     // ------------------------------------------------------------------------------------------------
  131.  
  132.     // function to start the game forest client
  133.     this.start                  = function ()
  134.     {
  135.         var pGfxObject = this;
  136.  
  137.         this.wsConnection.onopen    = function ()
  138.         {
  139.             if (GameForestVerboseMessaging)
  140.             {
  141.                 alert("Connection is opened with the server! Expecting the server to give connection ID...");
  142.             }
  143.         };
  144.         this.wsConnection.onclose   = function ()
  145.         {
  146.             if (GameForestVerboseMessaging)
  147.             {
  148.                 alert("Connection is closed with the server.");
  149.             }
  150.         };
  151.         this.wsConnection.onmessage = function (message)
  152.         {
  153.             var parse = JSON.parse(message.data);
  154.  
  155.             console.log(message.data);
  156.  
  157.             switch (parse.Subject)
  158.             {
  159.                 case GFX_ASK_DATA:
  160.                 case GFX_ASK_USER_DATA:
  161.                 case GFX_SEND_DATA:
  162.                 case GFX_SEND_USER_DATA:
  163.                 case GFX_NEXT_TURN:
  164.                 case GFX_CONFIRM_TURN:
  165.                 case GFX_GAME_START_CONFIRM:
  166.  
  167.                     console.log("Reply recevied! " + message.data);
  168.  
  169.                     if (parse.ResponseCode === 0)
  170.                     {
  171.                         wsPromise.done(null, parse.Message);
  172.                     } else
  173.                     {
  174.                         wsPromise.done(parse.ResponseCode + ":" + parse.Message, null);
  175.                     }
  176.                     break;
  177.                 case GFX_FINISH:
  178.  
  179.                     pGfxObject.lobbyStatus = GFX_STATUS_FINISHED;
  180.  
  181.                     console.log("Game is finished!");
  182.  
  183.                     if (parse.ResponseCode === 0)
  184.                     {
  185.                         wsPromise.done(null, parse.Message);
  186.                     } else
  187.                     {
  188.                         wsPromise.done(parse.ResponseCode + ":" + parse.Message, null);
  189.                     }
  190.  
  191.                     break;
  192.                 case GFX_INIT_CONNECTION:
  193.  
  194.                     console.log("Server acknowledges connection! Yay!!");
  195.  
  196.                     pGfxObject.connectionId = parse.Message;
  197.                     constructWSRequest(pGfxObject.wsConnection, pGfxObject.connectionId, pGfxObject.sessionId, GFX_INIT_CONNECTION, "");
  198.                     break;
  199.                 case GFX_GAME_START:
  200.  
  201.                     console.log("Server sent a start game signal.");
  202.  
  203.                     GameForest.prototype.onGameStartSignal();
  204.                     break;
  205.                 case GFX_START_GAME:
  206.  
  207.                     console.log("Server sent a start game event! Time to really start the game.");
  208.  
  209.                     clearInterval(updateUserList);
  210.  
  211.                     $("#gameForestLobbyWindow").hide();
  212.                     $("#gameForestGameWindow").show();
  213.  
  214.                     pGfxObject.lobbyStatus = GFX_STATUS_PLAYING;
  215.  
  216.                     GameForest.prototype.onGameStart();
  217.                     break;
  218.                 case GFX_START_CHOICE:
  219.  
  220.                     console.log("Server is asking the players to choose! Show the choose screen.");
  221.  
  222.                     $("#gameForestLobbyWindow").hide();
  223.                     $("#gameForestGameWindow").show();
  224.  
  225.                     pGfxObject.lobbyStatus = GFX_STATUS_CHOOSE;
  226.  
  227.                     GameForest.prototype.onGameChoose();
  228.                     break;
  229.                 case GFX_GAME_FINISHED:
  230.  
  231.                     console.log("Server is informing players that the game is finished!");
  232.  
  233.                     GameForest.prototype.onGameFinish(parse.Message);
  234.                     break;
  235.                 case GFX_TURN_START:
  236.  
  237.                     console.log("Server is saying my turn has started.");
  238.  
  239.                     GameForest.prototype.onTurnStart();
  240.                     break;
  241.                 case GFX_TURN_CHANGED:
  242.  
  243.                     console.log("Server is informing other players the game's turn have changed.");
  244.  
  245.                     GameForest.prototype.onTurnChange();
  246.                     break;
  247.                 case GFX_TURN_RESOLVE:
  248.  
  249.                     console.log("Server is asking the player to choose his/her order.");
  250.  
  251.                     GameForest.prototype.onTurnSelect(parse.Message);
  252.                     break;
  253.                 case GFX_DATA_CHANGED:
  254.  
  255.                     console.log("Server is informing players the game's data has changed.");
  256.  
  257.                     var packagedData = JSON.parse(parse.Message);
  258.  
  259.                     GameForest.prototype.onUpdateData(packagedData.Key, JSON.parse(packagedData.Data));
  260.                     break;
  261.             }
  262.         };
  263.     };
  264.     // function to stop the game forest client
  265.     this.stop                   = function ()
  266.     {
  267.         constructWSRequest(this.wsConnection, this.connectionId, this.sessionId, GFX_STOP_CONNECTION, "");
  268.     };
  269.  
  270.     // function to navigate back to the games page.
  271.     this.navigateToGame         = function ()
  272.     {
  273.         window.location.href = "../../../games.html";
  274.     };
  275.  
  276.     // lol method
  277.     this.thenStarter            = function ()
  278.     {
  279.         var p = new promise.Promise();
  280.  
  281.         p.done(null, "");
  282.  
  283.         return p;
  284.     };
  285.  
  286.     // ------------------------------------------------------------------------------------------------
  287.  
  288.     // function to inform the server its the next player's turn
  289.     this.nextTurn               = function ()
  290.     {
  291.         wsPromise = new promise.Promise();
  292.  
  293.         constructWSRequest(this.wsConnection, this.connectionId, this.sessionId, GFX_NEXT_TURN, "");
  294.  
  295.         return wsPromise;
  296.     };
  297.     // function to inform the server the player wants its turn to change order
  298.     this.confirmTurn            = function (changedTurn)
  299.     {
  300.         wsPromise = new promise.Promise();
  301.  
  302.         constructWSRequest(this.wsConnection, this.connectionId, this.sessionId, GFX_CONFIRM_TURN, changedTurn);
  303.  
  304.         return wsPromise;
  305.     };
  306.    
  307.     // function to get the lobby's current state (lobby, choose, playing)
  308.     this.getLobbyState          = function ()
  309.     {
  310.         return this.lobbyStatus;
  311.     };
  312.  
  313.     // function to get the current active player
  314.     this.getCurrentPlayer       = function ()
  315.     {
  316.         var p = new promise.Promise();
  317.  
  318.         sendRequest("/lobby/currentplayer?lobbyid=" + this.lobbyId + "&usersessionid=" + this.sessionId, "GET",
  319.             function (result)
  320.             {
  321.                 console.log("Result is: " + result.ResponseType + " with payload: " + result.AdditionalData);
  322.  
  323.                 if (result.ResponseType == 0)
  324.                     p.done(null, JSON.parse(result.AdditionalData));
  325.                 else
  326.                     p.done(result.ResponseType + " " + result.AdditionalData);
  327.             },
  328.             function (status, why)
  329.             {
  330.                 p.done(status + ": " + why, null);
  331.  
  332.                 if (GameForestVerboseMessaging)
  333.                 {
  334.                     alert("Error in getCurrentPlayer function: [status=" + status + "] [reason=" + why + "]");
  335.                 }
  336.             });
  337.  
  338.         return p;
  339.     };
  340.     // function to get the next player "steps" from the player calling this function
  341.     this.getNextPlayer          = function (steps)
  342.     {
  343.         var p = new promise.Promise();
  344.  
  345.         sendRequest("/lobby/nextplayer?lobbyid=" + this.lobbyId + "&usersessionid=" + this.sessionId + "&steps=" + steps, "GET",
  346.             function (result)
  347.             {
  348.                 if (result.ResponseType == 0)
  349.                     p.done(null, JSON.parse(result.AdditionalData));
  350.                 else
  351.                     p.done(result.ResponseType + " " + result.AdditionalData);
  352.             },
  353.             function (status, why)
  354.             {
  355.                 p.done(status + ": " + why, null);
  356.  
  357.                 if (GameForestVerboseMessaging)
  358.                 {
  359.                     alert("Error in getCurrentPlayer function: [status=" + status + "] [reason=" + why + "]");
  360.                 }
  361.             });
  362.  
  363.         return p;
  364.     };
  365.  
  366.     // function to get the user's current order
  367.     this.getUserOrder           = function ()
  368.     {
  369.         var p = new promise.Promise();
  370.  
  371.         sendRequest("/lobby/turn?lobbyid=" + this.lobbyId + "&usersessionid=" + this.sessionId, "GET",
  372.                     function (result)
  373.                     {
  374.                         if (result.ResponseType == 0)
  375.                             p.done(null, parseInt(result.AdditionalData));
  376.                         else
  377.                             p.done(result.ResponseType + " " + result.AdditionalData);
  378.                     },
  379.                     function (status, why)
  380.                     {
  381.                         p.done(status + ": " + why, null);
  382.  
  383.                         if (GameForestVerboseMessaging)
  384.                         {
  385.                             alert("Error in getUserOrder function: [status=" + status + "] [reason=" + why + "]");
  386.                         }
  387.                     });
  388.  
  389.         return p;
  390.     };
  391.     // function to get the user's information
  392.     this.getUserInfo            = function (username)
  393.     {
  394.         var p = new promise.Promise();
  395.  
  396.         if (username == undefined || username.length == 0 || username == " ")
  397.         {
  398.             sendRequest("/user/session/" + this.sessionId, "GET",
  399.                         function (result)
  400.                         {
  401.                             if (result.ResponseType == 0)
  402.                                 p.done(null, JSON.parse(result.AdditionalData));
  403.                             else
  404.                                 p.done(result.ResponseType + " " + result.AdditionalData);
  405.                         },
  406.                         function (status, why)
  407.                         {
  408.                             p.done(status + ": " + why, null);
  409.  
  410.                             if (GameForestVerboseMessaging)
  411.                             {
  412.                                 alert("Error in getUserInfo function: [status=" + status + "] [reason=" + why + "]");
  413.                             }
  414.                         });
  415.         }
  416.         else
  417.         {
  418.             sendRequest("/user/" + username, "GET",
  419.                         function (result)
  420.                         {
  421.                             if (result.ResponseType == 0)
  422.                                 p.done(null, JSON.parse(result.AdditionalData));
  423.                             else
  424.                                 p.done(result.ResponseType + " " + result.AdditionalData);
  425.                         },
  426.                         function (status, why)
  427.                         {
  428.                             p.done(status + ": " + why, null);
  429.  
  430.                             if (GameForestVerboseMessaging)
  431.                             {
  432.                                 alert("Error in getUserInfo function: [status=" + status + "] [reason=" + why + "]");
  433.                             }
  434.                         });
  435.  
  436.         }
  437.        
  438.         return p;
  439.     };
  440.     // function to get the lobby's user list
  441.     this.getUserList            = function ()
  442.     {
  443.         var p = new promise.Promise();
  444.  
  445.         sendRequest("/lobby/users?lobbyid=" + this.lobbyId + "&usersessionid=" + this.sessionId, "GET",
  446.             function (result)
  447.             {
  448.                 if (result.ResponseType == 0)
  449.                     p.done(null, JSON.parse(result.AdditionalData));
  450.                 else
  451.                     p.done(result.ResponseType + " " + result.AdditionalData);
  452.             },
  453.             function (status, why)
  454.             {
  455.                 p.done(status + ": " + why, null);
  456.  
  457.                 if (GameForestVerboseMessaging)
  458.                 {
  459.                     alert("Error in getUserList function: [status=" + status + "] [reason=" + why + "]");
  460.                 }
  461.             });
  462.  
  463.         return p;
  464.     };
  465.     // function to get the game's information
  466.     this.getGameInfo            = function ()
  467.     {
  468.         var p = new promise.Promise();
  469.  
  470.         sendRequest("/game/" + this.gameId, "GET",
  471.             function (result)
  472.             {
  473.                 if (result.ResponseType == 0)
  474.                     p.done(null, JSON.parse(result.AdditionalData));
  475.                 else
  476.                     p.done(result.ResponseType + " " + result.AdditionalData);
  477.             },
  478.             function (status, why)
  479.             {
  480.                 p.done(status + ": " + why, null);
  481.  
  482.                 if (GameForestVerboseMessaging)
  483.                 {
  484.                     alert("Error in getGameInfo function: [status=" + status + "] [reason=" + why + "]");
  485.                 }
  486.             });
  487.  
  488.         return p;
  489.     };
  490.  
  491.     // function to retrieve the game data
  492.     this.askGameData            = function ()
  493.     {
  494.         wsPromise = new promise.Promise();
  495.  
  496.         constructWSRequest(this.wsConnection, this.connectionId, this.sessionId, GFX_ASK_DATA, "");
  497.  
  498.         return wsPromise;
  499.     };
  500.     // function to retrieve the user data
  501.     this.askUserGameData        = function ()
  502.     {
  503.         wsPromise = new promise.Promise();
  504.  
  505.         constructWSRequest(this.wsConnection, this.connectionId, this.sessionId, GFX_ASK_USER_DATA, "");
  506.  
  507.         return wsPromise;
  508.     };
  509.  
  510.     // function to finish the game
  511.     this.finishGame             = function (tallyResults)
  512.     {
  513.         wsPromise = new promise.Promise();
  514.  
  515.         constructWSRequest(this.wsConnection, this.connectionId, this.sessionId, GFX_FINISH, tallyResults);
  516.  
  517.         return wsPromise;
  518.     };
  519.     // function to send game data
  520.     this.sendGameData           = function (key, payload)
  521.     {
  522.         wsPromise = new promise.Promise();
  523.  
  524.         var packagedData =
  525.             {
  526.                 Key:    key,
  527.                 Data:   JSON.stringify(payload)
  528.             };
  529.  
  530.         constructWSRequest(this.wsConnection, this.connectionId, this.sessionId, GFX_SEND_DATA, JSON.stringify(packagedData));
  531.  
  532.         return wsPromise;
  533.     };
  534.     // function to send user data
  535.     this.sendUserGameData       = function (payload)
  536.     {
  537.         wsPromise = new promise.Promise();
  538.  
  539.         constructWSRequest(this.wsConnection, this.connectionId, this.sessionId, GFX_SEND_USER_DATA, JSON.string(payload));
  540.  
  541.         return wsPromise;
  542.     };
  543.  
  544.     this.startGame              = function ()
  545.     {
  546.         wsPromise = new promise.Promise();
  547.  
  548.         constructWSRequest(this.wsConnection, this.connectionId, this.sessionId, GFX_GAME_START, "");
  549.  
  550.         return wsPromise;
  551.     };
  552.     this.readyGame              = function ()
  553.     {
  554.         wsPromise = new promise.Promise();
  555.  
  556.         constructWSRequest(this.wsConnection, this.connectionId, this.sessionId, GFX_GAME_START_CONFIRM, "");
  557.  
  558.         return wsPromise;
  559.     };
  560. };
  561.  
  562. GameForest.prototype.onGameStartSignal  = function ()
  563. {
  564.     console.log("Game start signal invoked!");
  565.  
  566.     $("#gfxButtonStart").removeAttr("disabled");
  567. };
  568.  
  569. // override these methods in your game
  570.  
  571. // method to override when the game has started
  572. GameForest.prototype.onGameStart        = function ()
  573. {
  574.  
  575. };
  576.  
  577. // method to override when the game should display the choose screen
  578. GameForest.prototype.onGameChoose       = function ()
  579. {
  580.  
  581. };
  582.  
  583. // method to override when its the player's turn
  584. GameForest.prototype.onTurnStart        = function ()
  585. {
  586.  
  587. };
  588.  
  589. // method to override when its the other player's turn
  590. GameForest.prototype.onTurnChange       = function ()
  591. {
  592.  
  593. };
  594.  
  595. // method to override when its the player's time to change his/her order
  596. GameForest.prototype.onTurnSelect       = function (originalTurn)
  597. {
  598.  
  599. };
  600.  
  601. // method to override when the game's data has changed
  602. GameForest.prototype.onUpdateData       = function (key, data)
  603. {
  604.  
  605. };
  606.  
  607. // method to override when the game is finished
  608. GameForest.prototype.onGameFinish       = function (tallyList)
  609. {
  610.  
  611. };
Advertisement
Add Comment
Please, Sign In to add comment