2011-11-05 66 views
3

如何在JavaScript中创建一个模型,作为笛卡尔平面中的网格参考?如何为船创建数据模型?

我想通过创建流行的游戏战舰克隆学习JavaScript!

为此我需要帮助才能开始编程船!

回答

0

我会首先创建一个数组(或两个,每边一个)来容纳小船。这可能非常简单,只需使用船号作为“填充”位置的数组入口。我的船模型将有一个长度(n“pegs”),一个位置(x,y),一个方向(垂直或水平)和一个计数器。另一种选择是只存储船只占据的每个阵列位置,这会使一些东西变得更容易一些。

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 

钉存储对象那样xy,并且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]