-
Notifications
You must be signed in to change notification settings - Fork 3
/
Tsc 2048.ts
77 lines (62 loc) · 1.68 KB
/
Tsc 2048.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
enum Direction {
Up,
Down,
Left,
Right,
}
class Tile {
value: number;
constructor(value: number) {
this.value = value;
}
}
class Board {
size: number;
tiles: Tile[][];
constructor(size: number) {
this.size = size;
this.tiles = [];
for (let i = 0; i < size; i++) {
this.tiles[i] = [];
for (let j = 0; j < size; j++) {
this.tiles[i][j] = new Tile(0);
}
}
}
generateRandomTile(): void {
const emptyTiles: [number, number][] = [];
for (let i = 0; i < this.size; i++) {
for (let j = 0; j < this.size; j++) {
if (this.tiles[i][j].value === 0) {
emptyTiles.push([i, j]);
}
}
}
if (emptyTiles.length === 0) {
return;
}
const randomIndex = Math.floor(Math.random() * emptyTiles.length);
const [row, col] = emptyTiles[randomIndex];
this.tiles[row][col].value = Math.random() < 0.9 ? 2 : 4;
}
move(direction: Direction): void {
// Implement the logic to move the tiles in the specified direction
// Update the board and generate a new random tile
}
}
class Game {
board: Board;
constructor(size: number) {
this.board = new Board(size);
this.board.generateRandomTile();
this.board.generateRandomTile();
}
play(direction: Direction): void {
this.board.move(direction);
// Implement the logic to handle player's moves and game over condition
}
}
// Create a new game with a 4x4 board
const game = new Game(4);
// Example: Move tiles to the right
game.play(Direction.Right);