Chapter 8, Exercise 2 – POSTing Scores With AJAX

Write a routine to post the player’s score to a fictional server address using jQuery’s ajax method. Post the score at the end of each level and write a checksum function to add basic security using your method of choice.

Assume we’re posting high scores to a directory called http://buildanhtml5game.com/bubbleshooter/score/
We’re going to add a checksum when we post the score. The checksum value will be a simple modulus of the score. We could even use the number of bubbles the player fired and pass that parameter along with the score. This would give us another level of security: if we see suspicious scores, then we can see if the number of bubbles is realistic. If the player has used 100, or only 5, then it’s likely that something’s wrong.

POSTing the score will happen inside the endGame function in game.js:

var endGame = function(hasWon){
  if(score > highScore){
    highScore = score;
    $("#new_high_score").show();
    BubbleShoot.ui.drawHighScore(highScore);
    if(window.localStorage){
      localStorage.setItem("high_score",highScore);
    }
  }else{
    $("#new_high_score").hide();
  };
  if(hasWon){
    level++;
  }else{
    score = 0;
    level = 0;
  };
  $(".but_start_game").click("click",startGame);
  $("#board .bubble").remove();
  BubbleShoot.ui.endGame(hasWon,score);
  $.ajax({
    url : 'http://buildanhtml5game.com/bubbleshooter/score/',
    data : {
      score : score,
      bubbles : numBubbles,
      cs : score % numBubbles
    },
    type : 'POST',
    success : function(response){
      console.log(response);
    }
  })
};

We’re using jQuery’s AJAX method (http://api.jquery.com/jQuery.ajax/) to POST the score, with the parameter “cs” containing our checksum. The parameters, in brief, are:

url : the url to post the score to
data : a JSON object containing our three parameters of score, number of bubbles, and checksum
type : POST, rather than GET
success : a function to call once the POST has been completed. This simply logs the response to the console, but in a full game you’re likely to want to do something with the result, such as show the user a confirmation message that their score has been saved.

If you put this into your game and keep the URL at http://buildanhtml5game.com/bubbleshooter/score/ you should see a message saying either “Score posted”. Try messing around with the checksum or posting a fake score and you’ll get a “Nice try” message instead.

Leave a Reply

Your email address will not be published. Required fields are marked *