-
Notifications
You must be signed in to change notification settings - Fork 61
/
Copy pathtile.js
90 lines (80 loc) · 2.19 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// Reverse a string
function reverseString(s) {
let arr = s.split('');
arr = arr.reverse();
return arr.join('');
}
// Compare if one edge matches the reverse of another
function compatibleEdges(a, b) {
return a == reverseString(b);
}
const UP = 0;
const RIGHT = 1;
const DOWN = 2;
const LEFT = 3;
// Class for each tile
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 and find matching edges with other tiles
analyze(tiles) {
for (let i = 0; i < tiles.length; i++) {
let tile = tiles[i];
// Skip if both tiles are tile 5
if (tile.index == 5 && this.index == 5) continue;
// Check if the current tile's bottom edge matches this tile's top edge
if (compatibleEdges(tile.edges[DOWN], this.edges[UP])) {
this.up.push(i);
}
// Check if the current tile's left edge matches this tile's right edge
if (compatibleEdges(tile.edges[LEFT], this.edges[RIGHT])) {
this.right.push(i);
}
// Check if the current tile's top edge matches this tile's bottom edge
if (compatibleEdges(tile.edges[UP], this.edges[DOWN])) {
this.down.push(i);
}
// Check if the current tile's right edge matches this tile's left edge
if (compatibleEdges(tile.edges[RIGHT], this.edges[LEFT])) {
this.left.push(i);
}
}
}
compatibles(dir) {
switch (dir) {
case UP:
return this.up;
case RIGHT:
return this.right;
case DOWN:
return this.down;
case LEFT:
return this.left;
}
}
// Rotate the tile image and edges
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);
}
}