Change the play.js file

From Progzoo
Jump to: navigation, search

Take a look at the file play.js you should find the section that makes the cells respond to clicks.

  // Set up td#i00 so that it responds to a click
  $('#i00').click(function(){
    $.getJSON('move.php',{gid:gid,pid:pid,r:0,c:0},function(r){
      if (r.OK)
        checkServer();
      else
        alert(r.err);
    });
  });
  // Set up td#i01 so that it responds to a click
  $('#i01').click(function(){
    $.getJSON('move.php',{gid:gid,pid:pid,r:0,c:1},function(r){
      if (r.OK)
        checkServer();
      else
        alert(r.err);
    });
  });
  • You can see that only two cells have been set up to respond.
  • You can copy this until you have dealt with all 9 cells #i00 #i01 #i02 #i10 #i11 #i12 #i20 #i21 #i22
  • Take care to ensure that the correct values for r and c on the $.getJSON line.

How it works

The following phrase makes the system respond with a message on the console when the user clicks on the element with id i00

$('#i00').click(function(){
  console.log('Button clicked');
})

When the user clicks on a cell you want to inform the server that a move has been made. This can be done with a $.getJSON call - this makes an AJAX call to the server.

You want to send the following details to the server:

  • gid - This is the game id; it will be a value such as oxo1234 where 1234 is a random number generated at the start of the game. The variable gid is defined as a global variable at the top of the file.
  • pid - This is the player id; it will be either X or O. The variable pid is similarly a global variable.
  • r - row number, one of 0, 1 or 2
  • c - column number, one of 0, 1 or 2

The AJAX call takes some time; it is an asynchronous call; when it completes the inner function is triggered.

$('#i00').click(function(){
  console.log('Button clicked');
  $.getJSON('move.php',{},function(r){
    console.log('AJAX call completed.');
  });
})

Do it better

Of course we would rather not have 9 copies of the same bit of code. It would be much better to deal with all 9 cells in one go. The $('#board td').each method can do that.

  • The pattern #board td matches all 9 cells
  • The supplied function will be executed once for each cell
  • You can use the expression $(this) to refer to the current cell
$('#board td').each(function(){
  $(this).click(function(){
    console.log("The user just clicked on: "+$(this).attr('id'));
    var row = $(this).attr('id')[1];
    console.log("The current row is character 1 of the id: "+row);
  })
});