我将如何更改此代码以具有5×4网格?
那么如何使代码成为如下所示的 5 x 4 网格。我目前得到一个 5 x 5 的网格并且未定义。
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
感谢 julien.giband 对代码的帮助。
//Grid size: result will be n*n cells
const GRID_SIZE = 5;
const grid = ["0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"];
// Ship Locations
const shipLocations = ["3", "9", "15"];
let guess; //Entered value
let count = 0; //counter for rounds
do { //We'll loop indefintely until the user clicks cancel on prompt
//Construct prompt using string template (multiline)
const prpt = `Round #${++count}
${printGrid()}
Enter a Number Between 0-19`;
guess = prompt(prpt);
if (!guess && guess !== 0)
break; //Stop when cancel was clicked
const hit = shipLocations.indexOf(guess) >= 0;
console.log(`At round ${count}, cell ${guess} is a ${hit ? 'hit': 'miss'}`);
grid[guess] = hit ? '1' : 'X';
} while (guess || guess === 0); //Must have an exit condition
/** Pretty-print the grid **/
function printGrid() {
let res = "";
for (let r = 0; r < GRID_SIZE; r++) {
let srow = "";
for (let c = 0; c < GRID_SIZE; c++) {
srow += " " + grid[r * GRID_SIZE + c];
}
res += srow.substr(1) + 'n';
}
return res;
}
回答
在“printGrid”中,行 (r) 和列 (c) 都循环到 5 (GRID_SIZE)。如果你想要一个 5x4 的网格,你将需要不同的行和列大小值:
ROW_GRID_SIZE=4;
COL_GRID_SIZE=5;
并改变你的循环:
for (let r = 0; r < ROW_GRID_SIZE; r++) {
let srow = "";
for (let c = 0; c < COL_GRID_SIZE; c++) {