【问题标题】:How to create a data model for a boat?如何为船创建数据模型?
【发布时间】:2011-12-22 12:35:15
【问题描述】:

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

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

为此,我需要帮助来开始编程船!

【问题讨论】:

    标签: javascript datamodel


    【解决方案1】:

    我首先创建一个阵列(或两个,每侧一个)来固定船。这可以很简单,只需使用船号作为“已填充”位置的数组条目。

    我的船模型将有一个长度(n 个“钉子”)、一个位置(x,y)、一个方向(垂直或水平)和一个计数器。另一种选择是只存储船占据的每个数组位置,这会使一些事情更容易一些。

    【讨论】:

      【解决方案2】:

      以下是帮助您入门的内容:

      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
      

      使用xyhit 键将钉子存储为对象不一定是最好的方法。例如,如果您想聪明一点,可以将对象的最左上角坐标与方向一起存储。然后,命中可以存储在一个数组中。比如:

      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]
      

      【讨论】:

        猜你喜欢
        • 2019-02-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-03
        • 1970-01-01
        • 1970-01-01
        • 2014-08-19
        • 1970-01-01
        相关资源
        最近更新 更多