如何为一艘船创建数据模型

How to create a data model for a boat?

本文关键字:一艘 创建 数据模型      更新时间:2023-09-26

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

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

为此,我需要帮助在我的任务开始编程船!

这里有一些东西可以让你开始:

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

将peg存储为具有x, yhit键的对象不一定是最好的方法。如果你想聪明一点,你可以,例如,存储对象的左上角坐标和方向。然后,点击可以存储在一个数组中。比如:

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]

我将首先创建一个数组(或两个,每边一个)来容纳船只。这可以非常简单,只需使用船号作为"填充"位置的数组项。

我的船模型将具有长度(n"pegs"),位置(x, y),方向(垂直或水平)和命中计数器。另一种选择是只存储船占用的每个数组位置,这将使一些事情变得更容易。