如何为一艘船创建数据模型
How to create a data model for a boat?
如何在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
, 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]
我将首先创建一个数组(或两个,每边一个)来容纳船只。这可以非常简单,只需使用船号作为"填充"位置的数组项。
我的船模型将具有长度(n"pegs"),位置(x, y),方向(垂直或水平)和命中计数器。另一种选择是只存储船占用的每个数组位置,这将使一些事情变得更容易。
相关文章:
- 创建一个数组数组,没有任何重复的Javascript
- 有没有一种方法可以让内联事件处理程序在元素创建后立即执行
- 我正在创建一个聊天,但每次我发送消息时,它都不会让我再发送另一条消息,就像表格一样;不起作用
- 创建一组元素JointJS
- 创建一次角度元素
- 使用jQuery在js中创建日历上的事件,i'I’我被一只奇怪的虫子卡住了
- ES6 const,用于在JavaScript中创建对象原型;这是一种模式吗
- 为给定月份/年的每一天创建文本输入行
- 为文档的每一页创建缩略图
- 使用node.js一步一步创建自定义应用程序
- 从URL字符串为URL的每一段创建数组
- 如何为一艘船创建数据模型
- 在Google Drive SDK中一次创建多个文件夹
- JS time -为两个日期之间的每一年创建一个数组
- 如何一步创建具有属性的函数对象
- 让骨干视图共存,或者一次创建和销毁一个
- 如何为“下一步”创建一个永无止境的循环?奥得河“prev"按钮(php / jquery)
- 另一种创建html表的方法
- 如何为csv中的每一列创建单独的图表
- Processing.js是一种创建JSON的方法