9.3 Example: Battleships! 239
As with the connection event, all users receive a message in the close event as
well. In this case, they are told that a user has left the conference. Then the server
is bound to port 8887 and receives queries from that point on.
That was an initial, very brief example. In the next section we will develop a game
that makes even better use of the advantages of WebSockets.
9.3 Example: Battleships!
A more detailed websocket example is devoted to a popular strategy game for
which you would normally only need paper and pencil—Battleships! The rules
are easy to explain: Each player places ten ships of different sizes on a play area
sized ten-by-ten spaces. The ships are not allowed to be touching, can be ar-
ranged horizontally or vertically, and are two to five spaces long. You distribute
them following the rule: 1×5, 2×4, 3×3, and 4×2 spaces per ship. The player who
is first to finish arranging his or her ships can start the game by choosing one
of the opponent’s spaces. If the space chosen contains only water, it’s the op-
ponent’s turn next; if that space contains a ship or part of a ship, the player can
keep guessing. You continue in this way until all parts of all ships have been hit,
and the ships have been sunk.
For converting Battleships! to HTML5, we require an HTML file on the client
with a JavaScript library and a CSS stylesheet; on the server we use node-web-
socket-server, which we already mentioned in section 9.1, The WebSocket
Server. All files relevant for the application can be found on the companion
website at these links:
z http://html5.komplett.cc/code/chap_websockets/game_en.html
z http://html5.komplett.cc/code/chap_websockets/game_en.js
z http://html5.komplett.cc/code/chap_websockets/game.css
z http://html5.komplett.cc/code/chap_websockets/ws/game_server.js
The game is shown in Figure 9.2.