forked from CodingTrain/Wave-Function-Collapse
-
Notifications
You must be signed in to change notification settings - Fork 1
/
tile.js
67 lines (59 loc) · 1.44 KB
/
tile.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
function reverseString(s) {
let arr = s.split('');
arr = arr.reverse();
return arr.join('');
}
function compareEdge(a, b) {
return a == reverseString(b);
}
class Tile {
constructor(img, edges, i) {
this.img = img;
this.edges = edges;
this.up = [];
this.right = [];
this.down = [];
this.left = [];
if (i !== undefined) {
this.index = i;
}
}
analyze(tiles) {
for (let i = 0; i < tiles.length; i++) {
let tile = tiles[i];
// Tile 5 can't match itself
if (tile.index == 5 && this.index == 5) continue;
// UP
if (compareEdge(tile.edges[2], this.edges[0])) {
this.up.push(i);
}
// RIGHT
if (compareEdge(tile.edges[3], this.edges[1])) {
this.right.push(i);
}
// DOWN
if (compareEdge(tile.edges[0], this.edges[2])) {
this.down.push(i);
}
// LEFT
if (compareEdge(tile.edges[1], this.edges[3])) {
this.left.push(i);
}
}
}
rotate(num) {
const w = this.img.width;
const h = this.img.height;
const newImg = createGraphics(w, h);
newImg.imageMode(CENTER);
newImg.translate(w / 2, h / 2);
newImg.rotate(HALF_PI * num);
newImg.image(this.img, 0, 0);
const newEdges = [];
const len = this.edges.length;
for (let i = 0; i < len; i++) {
newEdges[i] = this.edges[(i - num + len) % len];
}
return new Tile(newImg, newEdges, this.index);
}
}