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 - 如何使用模型中的數據創建圖形