-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.js
120 lines (100 loc) · 2.43 KB
/
main.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
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
import { BOARD_WIDTH } from './utils/constants'
import { createRandomPiece, rotatePiece } from './utils/pieces'
import { createBoard, draw, checkCollision } from './utils/canvas'
import './style.css'
// score
let score = 0
// board
const board = createBoard()
// player piece
let piece = createRandomPiece()
// game loop
let dropCounter = 0
let lastTime = 0
let level = 1
function update (time = 0) {
const deltaTime = time - lastTime
lastTime = time
dropCounter += deltaTime
if (dropCounter > 1000 / level) {
piece.position.y++
if (checkCollision(board, piece)) {
piece.position.y--
solidfyPiece()
removeRows()
}
dropCounter = 0
}
draw(board, piece, score, level)
window.requestAnimationFrame(update)
}
// Listen keydowns
document.addEventListener('keydown', event => {
piece = checkKeypressed(event)
})
// check key pressed
function checkKeypressed (event) {
if (event.key === 'ArrowLeft') {
piece.position.x--
if (checkCollision(board, piece)) piece.position.x++
}
if (event.key === 'ArrowRight') {
piece.position.x++
if (checkCollision(board, piece)) piece.position.x--
}
if (event.key === 'ArrowDown') {
piece.position.y++
if (checkCollision(board, piece)) {
piece.position.y--
solidfyPiece()
removeRows()
}
}
if (event.key === 'ArrowUp') {
piece.shape = rotatePiece(piece.shape)
if (checkCollision(board, piece)) piece.shape = rotatePiece(piece.shape)
}
return piece
}
// solidfy piece and generate new one
export function solidfyPiece () {
piece.shape.forEach((row, y) => {
row.forEach((value, x) => {
if (value === 1) {
board[piece.position.y + y][piece.position.x + x] = 1
}
})
})
piece = createRandomPiece()
if (checkCollision(board, piece)) {
gameOver()
}
}
// remove full rows
export function removeRows () {
const rowsToRemove = []
board.forEach((row, y) => {
if (row.every(value => value === 1)) {
rowsToRemove.push(y)
}
})
rowsToRemove.forEach(index => {
board.splice(index, 1)
board.unshift(new Array(BOARD_WIDTH).fill(0))
score += 10
})
level = Math.floor(score / 100) + 1
}
// game over
function gameOver () {
window.alert('Game Over')
board.forEach(row => row.fill(0))
score = 0
level = 1
}
// Listen start game
const $section = document.querySelector('section')
$section.addEventListener('click', () => {
update()
$section.remove()
})