📄 ex-21-5
字号:
/*
* WMLScript for battleships game.
*/
/*
* Initialize the grid. For simplicity, we don't place the ships randomly.
* Instead, there is one fixed grid layout.
*/
extern function init ( )
{
/* Initialize all the display variables to a space. */
for (var i=0; i<4; ++i) {
for (var j=0; j<4; ++j) {
WMLBrowser.setVar ("d_" + i + "_" + j, ' ');
}
}
/* Initialize the secret locations of the ships. The layout looks like:
* * * * D
* D D * D
* * * * *
* B B B B
*/
WMLBrowser.setVar ("ships", "***DDD*D****BBBB");
WMLBrowser.setVar ("remain", 8);
WMLBrowser.refresh ();
}
/*
* Handle a guess at a square.
*/
extern function guess (gr, gc)
{
/* Read the positions of the ships. */
var ships = WMLBrowser.getVar ("ships");
/* Read the number remaining as an integer. */
var remain = Lang.parseInt (WMLBrowser.getVar ("remain"));
/* Ignore this guess if user has already won. */
if (remain == 0)
return;
/* Calculate the name of the cell's display variable. */
var cellname = "d_" + gr + "_" + gc;
/* Ignore this guess if already guessed or not on board.
* Unguessed cells contain a space character.
*/
if (WMLBrowser.getVar (cellname) != ' ')
return;
/* Find what's in the cell. */
var hit = String.charAt (ships, 4*gr + gc);
/* Reduce remaining ships if appropriate. */
if (hit != '*')
--remain;
/* Update variables accordingly and refresh display. */
WMLBrowser.setVar ("remain", remain);
WMLBrowser.setVar (cellname, hit);
WMLBrowser.refresh ( );
/* Congratulate the user if game is now over. */
if (remain == 0)
congrats ( );
}
/*
* Print congratulatory message when game won.
*/
function congrats ( )
{
/* Count number of shots required. */
var shots = 0, hits = 0;
for (var i=0; i<4; ++i) {
for (var j=0; j<4; ++j) {
var cell = WMLBrowser.getVar ("d_" + i + "_" + j);
if (cell != ' ') {
++shots;
if (cell != '*')
++hits;
}
}
}
/* Calculate accuracy (proportion of shots on target). */
var accuracy = hits / shots;
/* Display message. */
Dialogs.alert ("All ships sunk. "
+ String.format ("You took %d shots. ", shots)
+ String.format ("Accuracy: %.2f%%", accuracy * 100));
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -