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. 如何在Ember.js中爲Ember數據模型創建承諾
- 6. 如何爲以下數據創建存儲和模型?
- 7. 如何從relationla數據格式創建Neo4J數據模型?
- 8. 如何創建模型從MS Access數據庫讀取數據?
- 9. 如何在覈心數據中創建數據模型?
- 10. 如何爲此JSON創建模型?
- 11. 如何爲此json創建模型,c#
- 12. 如何爲現有的SQL Server數據庫創建數據模型?
- 13. 如何在django 1.7模型中創建鍵值數據類型
- 14. 如何在Rails模型創建中使用Range數據類型?
- 15. 爲大型數據集創建MySQL數據庫模式
- 16. 如何創建新模型?
- 17. 如何創建模型
- 18. mysql worbench。如何創建數據庫,如果我有模型
- 19. 如何爲模型創建基於類的創建視圖?
- 20. 創建新的核心數據模型
- 21. SQLAlchemy數據庫反射模型創建
- 22. 創建核心數據模型
- 23. 從json數據創建java模型
- 24. Django模型創建數據副本
- 25. 從模型創建數據庫實例
- 26. 如何創建數據子類型
- 27. 如何創建數據感知型TCheckListBox?
- 28. C++模板:爲特定數據類型創建專用函數
- 29. 爲QML TreeView創建模型
- 30. 爲MVC創建模型