如何在javascript中为船只创建模型,该模型在笛卡尔平面中作为网格参考存在?
我想通过创建流行游戏Battleship的克隆来学习javascript!
为此,我需要协助开始编程船只!
答案 0 :(得分:5)
这是让你入门的东西:
function Boat(name, length) {
this.name = name
this.pegs = new Array(length)
this.sunk = false
}
Boat.prototype.place = function (x, y, orientation) {
// Before calling this method you'd need to confirm
// that the position is legal (on the board and not
// conflicting with the placement of existing ships).
// `x` and `y` should reflect the coordinates of the
// upper-leftmost peg position.
for (var idx = 0, len = this.pegs.length; idx < len; idx++) {
this.pegs[idx] = {x: x, y: y, hit: false}
if (orientation == 'horizontal') x += 1
else y += 1
}
}
Boat.prototype.hit = function (x, y) {
var sunk = true
var idx = this.pegs.length
while (idx--) {
var peg = this.pegs[idx]
if (peg.x == x && peg.y == y) peg.hit = true
// If a peg has not been hit, the boat is not yet sunk!
if (!peg.hit) sunk = false
}
return this.sunk = sunk // this is assignment, not comparison
}
用法:
var submarine = new Boat('submarine', 3)
submarine.place(2, 6, 'horizontal')
submarine.hit(2, 6) // false
submarine.hit(3, 6) // false
submarine.hit(4, 6) // true
将pegs作为具有x
,y
和hit
键的对象存储不一定是最佳方法。例如,如果你想要聪明,可以将最左上角的坐标与方向一起存储。然后,命中可以存储在一个数组中。类似的东西:
name: 'submarine'
x: 2
y: 6
orientation: 'horizontal'
pegs: [0, 0, 0]
在(2,6)击中后,船的属性将是:
name: 'submarine'
x: 2
y: 6
orientation: 'horizontal'
pegs: [1, 0, 0]
答案 1 :(得分:0)
我开始创建一个阵列(或两个,每侧一个)来固定船只。这可以非常简单,只需使用船号作为&#34;填充&#34;的数组条目。位置。
我的船型将具有长度(n&#34;桩钉#34;),位置(x,y),方向(垂直或水平)和点击计数器。另一种选择是存储船只占据的每个阵列位置,这会使一些东西更容易。