-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathboardShipPlacerHelper.js
76 lines (61 loc) · 1.82 KB
/
boardShipPlacerHelper.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
69
70
71
72
73
74
75
76
class BoardShipPlacerHelper {
static getStartCoordinates(direction, shipLength, boardRows, boardCols){
if(direction === 'horizontal')
{
return [this.getRandomInteger(0, (boardRows+1) - shipLength), this.getRandomInteger(0, boardCols)];
}
else {
return [this.getRandomInteger(0, boardRows), this.getRandomInteger(0, (boardCols+1) - shipLength)];
}
}
static generateRandomDirection() {
let x = (Math.floor(Math.random() * 2) == 0);
if(x){
return 'horizontal';
}else{
return 'vertical';
}
}
static generateCoordinates(posX, posY, shipLength, direction) //startPosition is [x,y]
{
let coordinates = [];
if(direction == 'horizontal') { //horizontal, increment x
for(let i = posX; i < posX + shipLength; i++)
{
coordinates.push([i, posY]);
}
}else { //vertical, increment y
for(let i = posY; i < posY + shipLength; i++)
{
coordinates.push([posX, i]);
}
}
return coordinates;
}
static generateListOfRandomMoves(rows, cols){
const randomMoves = [];
Array.prototype.swap = function (x,y) {
var b = this[x];
this[x] = this[y];
this[y] = b;
return this;
}
//Create ordered list
for(let i = 0; i < rows; i++){
for(let j = 0; j < cols; j++){
randomMoves.push([i,j]);
}
}
//Shuffle the order.
let totalNumbers = rows * cols;
for(let r = 0; r < (totalNumbers); r++){
let tempIndex = this.getRandomInteger(0, totalNumbers);
randomMoves.swap(r, tempIndex);
}
return randomMoves;
}
static getRandomInteger(min, max) {
return Math.floor(Math.random() * (max - min) ) + min;
}
}
module.exports = BoardShipPlacerHelper;