我试着用Javascript创建一个简单的战舰游戏。游戏应该有一个7x7网格系统,战舰应该被随机放置在网格上,无论是垂直的还是水平的。
下面是创建1x7网格(水平)的代码:
/* Declare length of battleground */
var battleground = 7;
/* Calculate and position the battleships */
while (battleground < 7);
var battlegroundCalc = parseInt(battleground) - 2;
var randomLoc = Math.floor(Math.random() * battlegroundCalc);
var location1 = randomLoc;
var location2 = location1 + 1;
var location3 = location2 + 1;
console.log(location1);
console.log(location2);
console.log(location3);
/* Add tiles to construct the battleground */
for (var i = 0; i < battleground; i++){
document.getElementById('tableRow').innerHTML +="<td id='"+i+"'></td>"
};然而,我在弄清楚如何创建多个行时遇到了困难,所以我得到了一个7x7网格。
如果有人能帮我解决这个问题,我会非常感激的。
提前谢谢。
发布于 2014-09-09 15:16:51
以下是一种方法:
var dimensionx = 7;
var grid = new Array(dimensionx);
var i, j, row, box;
// this is our table
var board = document.getElementById('tbody_id');
for (i = 0; i < grid.length; i++) {
grid[i] = new Array(dimensionx);
grid[i].fill('~'); //fill the grid with water
row = document.createElement('tr');
for (j = 0; j < grid[i].length; j++) {
box = document.createElement('td');
box.setAttribute('id', "" + i + j); //practical identification for cells
row.appendChild(box);
}
board.appendChild(row);
}这里的不同之处在于,我在开始使用它之前创建了一个二维数组(我所做的就是在构建整个过程之前清除单元格)。在此之后,只需通过grid[i][j]引用所需的单元格,并通过其id引用表单元格,方法与设置属性的方式相同。
这是一个小提琴。为了方便起见,它还有一个update_board()函数。
我本应该早点回答的,但我太激动了,几乎在jsFiddle上实现了整个游戏,直到我停止了自己。
https://stackoverflow.com/questions/25743909
复制相似问题