-
Notifications
You must be signed in to change notification settings - Fork 0
/
FieldPopulator.js
68 lines (61 loc) · 1.91 KB
/
FieldPopulator.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
var FieldPopulator = function (field, ship) {
var size = field.length;
this.populate = function () {
if (!this.isPositionAvailable()) {
throw 'no position available';
}
var positionFound = false, position;
while (!positionFound) {
positionFound = true;
position = getRandomShipPosition();
positionFound = this.isShipPositionFree(position);
}
for (var i = 0; i < ship; i++) {
field[position.initY + position.multY * i][position.initX + position.multX * i].hasShip = true;
}
};
this.isShipPositionFree = function (position) {
for (var x = position.initX - 1; x <= position.initX + 1 + position.multX * (ship - 1); x++) {
for (var y = position.initY - 1; y <= position.initY + 1 + position.multY * (ship - 1); y++) {
if (isValidCoordinate(x, y) && field[y][x].hasShip)
return false;
}
}
return true;
};
this.isPositionAvailable = function() {
for (var dirIndex = 0; dirIndex < 2; dirIndex++) {
var multX = dirIndex;
var multY = 1 - dirIndex;
for (var initX = 0; initX < size - multX * (ship - 1); initX++) {
for (var initY = 0; initY < size - multY * (ship - 1); initY++) {
if (this.isShipPositionFree({
multX: multX,
multY: multY,
initX: initX,
initY: initY
})) return true;
}
}
}
return false;
}
function getRandomShipPosition() {
var dir = Math.random() < 0.5;
var multX = dir ? 0 : 1;
var multY = dir ? 1 : 0;
return {
multX: multX,
multY: multY,
initX: Math.floor(Math.random() * (size - multX * (ship - 1))),
initY: Math.floor(Math.random() * (size - multY * (ship - 1)))
}
}
function isValidCoordinate(x, y) {
return isValidIndex(x) && isValidIndex(y);
}
function isValidIndex(i) {
return i >= 0 && i < size;
}
};
module.exports = FieldPopulator;