Вот кое-что, с чего можно начать:
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
Хранение колышков как объектов с ключами 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]