/
TrackFactory.js
87 lines (68 loc) · 1.96 KB
/
TrackFactory.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
77
78
79
80
81
82
83
84
85
86
87
function TrackFactory(lanes, rows, numObstacles) {
this.lanes = lanes;
this.rows = rows;
this.snowmanSpeed = 1/1000;
this.entities = [];
var retries = 0;
var started = new Date();
var solution = this.getSolution();
while(this.entities.length < numObstacles && retries < 5) {
var newObstacle = this.makeObstacle();
var nope = this.entities.some(e => e.x == newObstacle.x && e.y == newObstacle.y);
if( !nope &&
newObstacle instanceof Rock &&
newObstacleIsInSolution(newObstacle)) {
var newSolution = this.getSolution(newObstacle);
if(!newSolution)
nope = true;
else
solution = newSolution;
}
if(nope)
retries++;
else {
retries = 0;
this.entities.push(newObstacle);
}
}
if(this.entities.length < numObstacles) {
var skipped = numObstacles - this.entities.length;
log("Warning: failed to place "+skipped+" obstacles");
}
var duration = new Date() - started;
log("Level created in "+duration/1000+" ms");
function newObstacleIsInSolution(newObstacle) {
var node = solution;
while(node) {
if(node.x == newObstacle.x && node.y == newObstacle.y)
return true;
node = node.parent;
}
return false;
}
}
TrackFactory.prototype.getSolution = function(newObstacle) {
var o = this.entities;
if(newObstacle)
o = o.concat(newObstacle);
return findPathToFinish(this.entities.concat(newObstacle), {x: 0, y: this.rows - 1}, this.lanes);
};
(function() {
var weightedItemsCollection = [];
var i;
for(i = 0; i < 5; i++)
weightedItemsCollection.push(Rock);
for(i = 0; i < 1; i++)
weightedItemsCollection.push(ItemFactory);
TrackFactory.prototype.makeObstacle = function() {
var obstacle = new (sample(weightedItemsCollection));
obstacle.x = Math.floor(Math.random() * this.lanes);
//don't put obstacles in the bottom row
obstacle.y = Math.floor(Math.random() * (this.rows - 2));
return obstacle;
};
})();
function sample(arr) {
const i = Math.floor(Math.random() * arr.length);
return arr[i];
}