HTML5 Guidelines for Web Developers

(coco) #1

244 Chapter 9—WebSockets


If the invitation to play was answered with Yes, the server is informed that the
two players are now playing together, the game is prepared, and the selection list
of logged-in players is hidden. If the answer was No, only the message No thanks,
not now is displayed for two seconds.
As a direct consequence of the server message We are now playing together, other
steps follow, such as the update of the player status object on the server, which
then informs all users that the two players involved are not currently available
for other games.
For the server in game_server.js, it would look as follows:

var setBusy = function(id) {.
USERS[id].busy = true;
var msg = {task:'isPlaying',user:USERS[id]};
conn.broadcast(JSON.stringify(msg));
conn.write(JSON.stringify(msg));
};
...
else if (msg.task == 'setPlaying') {
setBusy(conn.id);
setBusy(msg.client);
}

Back in the client, this message is caught in the onmessage callback and the locally
kept list of logged-in players is updated. The result of this update is that both
players can no longer be selected, because their option elements are deactivated
via a disabled attribute:

else if (msg.task == 'isPlaying') {
var opts = document.forms.loggedin.users.options;
for (var i=0; i<opts.length; i++) {
if (opts[i].value == msg.user.id) {
opts[i].disabled = 'disabled';
}
}
}

If both players agree that they want to play together, they can start placing the
ships. If you are logged in as user test1 or test2, your ships are already prepared
for you; if not, a pull-down menu pops up, allowing you to digitalize your flotilla
via five buttons. Select whether to arrange each ship in a horizontal or vertical
orientation, and then click on the desired ship type and place the ship onto the
play area in the desired place by clicking once more.
The relevant fields are formatted to represent ships via a CSS class ship and
are recorded in three JavaScript variables. The variable game.ships.isShip re-
members the designated positions, and the variable game.ships.parts records
Free download pdf