-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
113 lines (95 loc) · 2.75 KB
/
script.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
let blockSize = 25;
let rows = 20;
let columns = 20;
let table;
let context;
//snake head
let snakeX = blockSize * 5;
let snakeY = blockSize * 5;
//moves count
let movementX = 0;
let movementY = 0;
let snake = [];
//food for snake
let foodX;
let foodY;
let score = 0;
let gameOver = false;
window.onload = function () {
table = document.getElementById("table");
table.height = rows * blockSize;
table.width = columns * blockSize;
context = table.getContext("2d");
placeFood();
document.addEventListener("keyup", changeDirection);
setInterval(displayTable, 1000 / 10);
}
function restartGame() {
window.location.reload();
}
function displayTable() {
if (gameOver) {
return;
}
context.fillStyle = "lime";
context.fillRect(0, 0, table.width, table.height);
context.fillStyle = "red";
context.fillRect(foodX, foodY, blockSize, blockSize);
eatFood();
context.fillStyle = "darkblue";
snakeX += movementX * blockSize;
snakeY += movementY * blockSize;
context.fillRect(snakeX, snakeY, blockSize, blockSize);
for (let s = 0; s < snake.length; ++s) {
context.fillRect(snake[s][0], snake[s][1], blockSize, blockSize);
}
checkBuffer();
}
function eatFood() {
if (snakeX == foodX && snakeY == foodY) {
snake.push([foodX, foodY]);
++score;
document.getElementById('score-count').innerText = score;
placeFood();
}
for (let s = snake.length - 1; s > 0; --s) {
snake[s] = snake[s - 1];
}
if (snake.length) {
snake[0] = [snakeX, snakeY];
}
}
function checkBuffer() {
if (snakeX < 0 || snakeX > columns * blockSize || snakeY < 0 || snakeY > rows * blockSize) {
gameOver = true;
document.getElementById('score-count').innerText = "Game Over";
}
for (let s = 0; s < snake.length; ++s) {
if (snakeX == snake[s][0] && snakeY == snake[s][1]) {
gameOver = true;
document.getElementById('score-count').innerText = "Game Over";
}
}
}
function changeDirection(e) {
if (e.code == "ArrowUp" && movementY != 1) {
movementX = 0;
movementY = -1;
} else if (e.code == "ArrowDown" && movementY != -1) {
movementX = 0;
movementY = 1;
}
else if (e.code == "ArrowLeft" && movementX != 1) {
movementX = -1;
movementY = 0;
}
else if (e.code == "ArrowRight" && movementX != -1) {
movementX = 1;
movementY = 0;
}
}
//set apple random in the table
function placeFood() {
foodX = Math.floor(Math.random() * columns) * blockSize;
foodY = Math.floor(Math.random() * rows) * blockSize;
}