3
A
回答
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
钉存储对象那样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]
相关问题
- 1. 如何创建数据模型动态
- 2. 为Drupal数据库创建AR模型
- 3. 如何为此数据创建模型/商店?
- 4. 如何在核心数据中创建数据模型?
- 5. 如何为此JSON创建模型?
- 6. 如何为此json创建模型,c#
- 7. 如何在django 1.7模型中创建键值数据类型
- 8. 如何在Rails模型创建中使用Range数据类型?
- 9. 为大型数据集创建MySQL数据库模式
- 10. 如何为模型创建基于类的创建视图?
- 11. Django模型创建数据副本
- 12. 创建新的核心数据模型
- 13. 从json数据创建java模型
- 14. 使用UML约定创建元模型并创建数据模型
- 15. Rails - 为模型创建UID
- 16. 为MVC创建模型
- 17. 为QML TreeView创建模型
- 18. 为XML创建模型类
- 19. 为模型创建视图
- 20. 如何使用PetaPoco库自动创建数据库模型?
- 21. 如何使用数据模型在sqlite.swift中创建外键
- 22. 如何从“Model first”模型创建数据库?
- 23. 如何从Linq2Sql模型创建SQL数据库
- 24. 如何创建适当的iOS CoreData数据库模型?
- 25. 如何使用SPARQL从DBPedia数据创建RDF模型
- 26. 如何创建gettable模板类型数据sa类字段?
- 27. 如何从数据存储模型创建嵌套字典?
- 28. 如何从模型.dbml创建数据库
- 29. 如何在Rails中查询数据而无需创建模型?
- 30. AngularJS - 如何使用模型中的数据创建图形