-
Notifications
You must be signed in to change notification settings - Fork 53
/
piece.js
46 lines (40 loc) · 871 Bytes
/
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
class Piece {
constructor(ctx) {
this.ctx = ctx;
this.spawn();
}
spawn() {
this.typeId = this.randomizeTetrominoType(COLORS.length - 1);
this.shape = SHAPES[this.typeId];
this.color = COLORS[this.typeId];
this.x = 0;
this.y = 0;
this.hardDropped = false;
}
draw() {
this.ctx.fillStyle = this.color;
this.shape.forEach((row, y) => {
row.forEach((value, x) => {
if (value > 0) {
this.ctx.fillRect(this.x + x, this.y + y, 1, 1);
}
});
});
}
move(p) {
if (!this.hardDropped) {
this.x = p.x;
this.y = p.y;
}
this.shape = p.shape;
}
hardDrop() {
this.hardDropped = true;
}
setStartingPosition() {
this.x = this.typeId === 4 ? 4 : 3;
}
randomizeTetrominoType(noOfTypes) {
return Math.floor(Math.random() * noOfTypes + 1);
}
}