Battleships

The next example is a simplified version of the classic pencil-and-paper game Battleships . In the game, the browser puts ships randomly onto a grid, and the user selects grid cells one at a time. The browser then reports whether the guess was a hit or a miss. The aim is to sink the whole fleet in as few moves as possible.

As in the earlier example, the first thing to do is set up the WML giving the page structure. This is very regular, since all cells are handled in a similar way. Example 21.4 gives this WML. To make the example shorter, the grid has been kept to only 4 × 4 cells.

Example 21-4. WML for Battleships

<?xml version="1.0"?> <!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN" "http://www.wapforum.org/DTD/wml_1.1.xml"> <wml> <card title="Battleships" newcontext="true" onenterforward="bships.wmls#init( )"> <!-- Display the grid. --> <p> <a href="bships.wmls#guess(0,0)">$d_0_0</a> <a href="bships.wmls#guess(0,1)">$d_0_1</a> <a href="bships.wmls#guess(0,2)">$d_0_2</a> <a href="bships.wmls#guess(0,3)">$d_0_3</a> <br/> <a href="bships.wmls#guess(1,0)">$d_1_0</a> <a href="bships.wmls#guess(1,1)">$d_1_1</a> <a href="bships.wmls#guess(1,2)">$d_1_2</a> <a href="bships.wmls#guess(1,3)">$d_1_3</a> <br/> <a href="bships.wmls#guess(2,0)">$d_2_0</a> <a href="bships.wmls#guess(2,1)">$d_2_1</a> <a href="bships.wmls#guess(2,2)">$d_2_2</a> <a href="bships.wmls#guess(2,3)">$d_2_3</a> <br/> <a href="bships.wmls#guess(3,0)">$d_3_0</a> <a href="bships.wmls#guess(3,1)">$d_3_1</a> ...

Get Learning WML, and WMLScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.