2011-11-05 62 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]