-
-
Notifications
You must be signed in to change notification settings - Fork 102
/
piece-factory.ts
55 lines (48 loc) · 1.57 KB
/
piece-factory.ts
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
import { Piece } from '../interface/piece/piece';
import { NonePiece } from '../interface/piece/none';
import { PieceI } from '../interface/piece/I';
import { PieceJ } from '../interface/piece/J';
import { PieceL } from '../interface/piece/L';
import { PieceO } from '../interface/piece/O';
import { PieceS } from '../interface/piece/S';
import { PieceT } from '../interface/piece/T';
import { PieceZ } from '../interface/piece/Z';
import { Injectable } from '@angular/core';
export const SPAWN_POSITION_X = 4;
export const SPAWN_POSITION_Y = -4;
@Injectable({
providedIn: 'root'
})
export class PieceFactory {
private available: (typeof Piece)[] = [];
private currentBag: (typeof Piece)[] = [];
constructor() {
this.available.push(PieceI);
this.available.push(PieceJ);
this.available.push(PieceL);
this.available.push(PieceO);
this.available.push(PieceS);
this.available.push(PieceT);
this.available.push(PieceZ);
}
getRandomPiece(x = SPAWN_POSITION_X, y = SPAWN_POSITION_Y): Piece {
if (this.currentBag.length === 0) {
this.generateNewBag();
}
const nextPiece = this.currentBag.pop();
return new nextPiece(x, y);
}
getNonePiece(x = SPAWN_POSITION_X, y = SPAWN_POSITION_Y): Piece {
return new NonePiece(x, y);
}
generateNewBag() {
this.currentBag = this.available.slice();
this.shuffleArray(this.currentBag);
}
shuffleArray(array: (typeof Piece)[]) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}
}