-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.js
111 lines (93 loc) · 2.59 KB
/
game.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
import { updateScore, showGameOverScreen, resetUI } from './ui.js';
import { saveFinalScore } from './index.js';
let canvas = document.getElementById("gameCanvas");
let ctx = canvas.getContext("2d");
let Snake = [];
let Food = {};
let speedX = 10;
let speedY = 0;
let interval = 100;
let move;
let score = 0;
function initSnake() {
Snake = [{ x: 50, y: 50 }];
speedX = 10;
speedY = 0;
}
function isFoodOnSnake(newFood) {
return Snake.some(segment => segment.x === newFood.x && segment.y === newFood.y);
}
function createNewFood() {
let newFood;
do {
newFood = {
x: Math.floor(Math.random() * (canvas.width / 10)) * 10,
y: Math.floor(Math.random() * (canvas.height / 10)) * 10,
};
} while (isFoodOnSnake(newFood));
Food = newFood;
}
function endGame() {
clearInterval(move);
showGameOverScreen(score);
saveFinalScore(score);
}
function checkSelfCollision() {
for (let i = 1; i < Snake.length; i++) {
if (Snake[0].x === Snake[i].x && Snake[0].y === Snake[i].y) {
return true;
}
}
return false;
}
function movingSnake() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = Snake.length - 1; i > 0; i--) {
Snake[i] = { ...Snake[i - 1] };
}
Snake[0].x += speedX;
Snake[0].y += speedY;
if (Snake[0].x < 0 || Snake[0].x >= canvas.width || Snake[0].y < 0 || Snake[0].y >= canvas.height) {
endGame();
return;
}
if (checkSelfCollision()) {
endGame();
return;
}
if (Snake[0].x === Food.x && Snake[0].y === Food.y) {
Snake.push({ ...Snake[Snake.length - 1] });
createNewFood();
score++;
updateScore(score);
}
ctx.fillStyle = 'red';
ctx.fillRect(Food.x, Food.y, 10, 10);
ctx.fillStyle = 'lime';
Snake.forEach(segment => {
ctx.fillRect(segment.x, segment.y, 10, 10);
});
}
export function startGame() {
resetUI();
initSnake();
createNewFood();
score = 0;
updateScore(score);
move = setInterval(movingSnake, interval);
document.addEventListener('keydown', function (event) {
if (event.key === "ArrowRight" && speedX === 0) {
speedX = 10;
speedY = 0;
} else if (event.key === "ArrowLeft" && speedX === 0) {
speedX = -10;
speedY = 0;
} else if (event.key === "ArrowDown" && speedY === 0) {
speedX = 0;
speedY = 10;
} else if (event.key === "ArrowUp" && speedY === 0) {
speedX = 0;
speedY = -10;
}
});
}