-
Notifications
You must be signed in to change notification settings - Fork 2
/
piece.js
51 lines (43 loc) · 1.13 KB
/
piece.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
class Piece {
x;
y;
color;
shape;
ctx;
constructor(ctx) {
this.ctx = ctx;
this.spawn();
}
spawn() {
const typeId = this.randomizeTetrominoType(COLORS.length);
this.color = COLORS[typeId];
this.shape = SHAPES[typeId];
// Starting position
this.x = 0;
this.y = 0;
}
draw() {
this.ctx.fillStyle = this.color;
this.shape.forEach((row, y) => {
row.forEach((value, x) => {
// this.x, this.y gives the left upper position of the shape
// x, y gives the position of the block in the shape
// this.x + x is the position of the block on the board
if (value > 0) {
this.ctx.fillRect(this.x + x, this.y + y, 1, 1);
}
});
});
}
move(p) {
this.x = p.x;
this.y = p.y;
this.shape = p.shape;
}
randomizeTetrominoType(numberOfTypes) {
return Math.floor(Math.random() * numberOfTypes);
}
setStartingPosition() {
this.x = this.typeId === 4 ? 4 : 3;
}
}