9.3 Example: Battleships! 247
game.you.grid[msg.field].setAttribute("class",
msg.result);
deactivateField();
}
else if (msg.result == 'hit') {
game.you.grid[msg.field].setAttribute("class",
msg.result);
}
...
From the attacker’s point of view, the answer hit marks the field he clicked on in
red. If the answer is destroyed, all fields belonging to that ship are turned from
red to green to show it was hit and destroyed. At the same time, in the play area
of the attacked player, his hit position is marked in red. In the case of destroyed,
all previously red ship sections are turned blue to show that the attacked ship
was destroyed and has been replaced by blue blocks, or water. So, the more blue
you can see on your play area, the worse the situation; the more green in the op-
ponent’s play area, the better the chance of victory.
If the answer is water, it is now the attacked player’s turn to retaliate (the
deactivateField() function prevents further actions). The game continues
back and forth until one of the two players has destroyed all of the opponent’s
ships and is declared the winner. Marking the status of your own and enemy
ships is done via CSS formats for each button element, as mentioned previ-
ously. The turn-taking between players is possible because the opposing game
area for the currently inactive player is deactivated with pointer-events:none
and opacity:0.2.
After the end of the game, both players are separated again; their status is reset
to Available to play, and the next invitation can be issued. In the current version,
Battleships! does not yet allow for playing several consecutive games with the
same player; perhaps you would like to try implementing this new feature? An-
other good idea might be a Logout button, and if you are feeling really brave, you
could implement a multiplayer mode. There are many options for developing
this application further. You are only limited by your imagination!
The example demonstrates in an impressive way the new options offered by the
WebSocket protocol for developing interactive applications. Our examples dealt
with interaction between users. But a feature you could easily implement would
be the WebSocket server getting information from the Internet, processing it,
and then sending it to the connected users. The previously mentioned applica-
tion for broadcasting current stock market prices would be a good example of
this. Another possible scenario would be displaying new messages received in
Twitter. The advantages are obvious: The client is notified of news via the mes-
sage event, and the data stream between client and server is very lean, conserv-
ing network bandwidth.