Repository navigation
Expand file tree
/
Copy pathtetris.js
More file actions
100 lines (85 loc) · 2.34 KB
/
Copy pathtetris.js
File metadata and controls
100 lines (85 loc) · 2.34 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
// setup
const startBtn = document.getElementById('start-button')
const restartBtn = document.getElementById('restart-button')
let canvas = document.getElementById("game-canvas")
let scoreboard = document.getElementById("scoreboard")
let ctx = canvas.getContext("2d")
ctx.scale(BLOCK_SIDE_LENGTH, BLOCK_SIDE_LENGTH)
let model = new GameModel(ctx)
let score = 0
window.score = 0
let playing = true
let timerId;
model.renderGameState()
let newGameState = () => {
fullSend()
if (model.fallingPiece === null) {
const rand = Math.round(Math.random() * 6) + 1
const newPiece = new Piece(SHAPES[rand], ctx)
model.fallingPiece = newPiece
model.moveDown()
} else {
model.moveDown()
}
}
const fullSend = () => {
const allFilled = (row) => {
for (let x of row) {
if (x === 0) {
return false
}
}
return true
}
for (let i = 0; i < model.grid.length; i++) {
if (allFilled(model.grid[i])) {
// window.score += 1
model.grid.splice(i, 1)
model.grid.unshift([0,0,0,0,0,0,0,0,0,0])
}
}
scoreboard.innerHTML = "Score: " + String(window.score)
}
document.addEventListener("keydown", (e) => {
if(timerId) {
e.preventDefault()
switch(e.key) {
case "w":
model.rotate()
break
case "d":
model.move(true)
break
case "s":
model.moveDown()
break
case "a":
model.move(false)
break
case "ArrowUp":
model.rotate()
break
case "ArrowRight":
model.move(true)
break
case "ArrowLeft":
model.move(false)
break
case "ArrowDown":
model.moveDown()
}
}
})
startBtn.addEventListener('click', () => {
if (timerId) {
clearInterval(timerId)
timerId = null
} else {
timerId = setInterval(() => newGameState(), GAME_CLOCK);
}
startBtn.style.visibility='hidden'
})
// find out how game is restarted and create a function for it
restartBtn.addEventListener('click', () => {
document.location.href="tetris.php"
})