-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathgamemodel.js
More file actions
125 lines (115 loc) · 3.58 KB
/
gamemodel.js
File metadata and controls
125 lines (115 loc) · 3.58 KB
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
class GameModel {
constructor(ctx) {
this.ctx = ctx
this.fallingPiece = null // piece
this.grid = this.makeStartingGrid()
}
makeStartingGrid() {
let grid = []
for (var i = 0; i < ROWS; i++) {
grid.push([])
for (var j = 0; j < COLS; j++) {
grid[grid.length - 1].push(0)
}
}
return grid
}
collision(x, y, candidate=null) {
const shape = candidate || this.fallingPiece.shape
const n = shape.length
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
if (shape[i][j] > 0) {
let p = x + j
let q = y + i
if (p >= 0 && p < COLS && q < ROWS) {
// in bounds
if (this.grid[q][p] > 0) {
return true
}
} else {
return true
}
}
}
}
return false
}
renderGameState() {
for (let i = 0; i < this.grid.length; i++) {
for (let j = 0; j < this.grid[i].length; j++) {
let cell = this.grid[i][j]
this.ctx.fillStyle = COLORS[cell]
this.ctx.fillRect(j, i, 1, 1)
}
}
if (this.fallingPiece !== null) {
this.fallingPiece.renderPiece()
}
}
moveDown() {
if (this.fallingPiece === null) {
this.renderGameState()
return
} else if (this.collision(this.fallingPiece.x, this.fallingPiece.y + 1)) {
const shape = this.fallingPiece.shape
const x = this.fallingPiece.x
const y = this.fallingPiece.y
shape.map((row, i) => {
row.map((cell, j) => {
let p = x + j
let q = y + i
if (p >= 0 && p < COLS && q < ROWS && cell > 0) {
this.grid[q][p] = shape[i][j]
}
})
})
// check game over
if (this.fallingPiece.y === 0) {
alert("Game over!")
this.grid = this.makeStartingGrid()
}
this.fallingPiece = null
} else {
this.fallingPiece.y += 1
}
this.renderGameState()
}
move(right) {
if (this.fallingPiece === null) {
return
}
let x = this.fallingPiece.x
let y = this.fallingPiece.y
if (right) {
// move right
if (!this.collision(x + 1, y)) {
this.fallingPiece.x += 1
}
} else {
// move left
if (!this.collision(x - 1, y)) {
this.fallingPiece.x -= 1
}
}
this.renderGameState()
}
rotate() {
if (this.fallingPiece !== null) {
let shape = [...this.fallingPiece.shape.map((row) => [...row])]
// transpose of matrix
for (let y = 0; y < shape.length; ++y) {
for (let x = 0; x < y; ++x) {
[shape[x][y], shape[y][x]] =
[shape[y][x], shape[x][y]]
}
}
// reverse order of rows
shape.forEach((row => row.reverse()))
if (!this.collision(this.fallingPiece.x, this.fallingPiece.y, shape)) {
this.fallingPiece.shape = shape
}
}
this.renderGameState()
}
}