-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
97 lines (87 loc) · 2.57 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
const boardSize = 20;
const gameBoard = document.getElementById('game-board');
let snake = [{x: 10, y: 10}];
let food = {x: 5, y: 5};
let dx = 1, dy = 0;
let gameRunning = true;
function initBoard() {
for (let i = 0; i < boardSize * boardSize; i++) {
const square = document.createElement('div');
gameBoard.appendChild(square);
}
}
function updateBoard() {
document.querySelectorAll('#game-board > div').forEach(div => div.className = '');
snake.forEach(part => {
const index = part.y * boardSize + part.x;
gameBoard.children[index].classList.add('snake');
});
const foodIndex = food.y * boardSize + food.x;
gameBoard.children[foodIndex].classList.add('food');
}
function moveSnake() {
const head = {x: snake[0].x + dx, y: snake[0].y + dy};
snake.unshift(head);
if (head.x === food.x && head.y === food.y) {
placeFood();
} else {
snake.pop();
}
if (head.x < 0 || head.x >= boardSize || head.y < 0 || head.y >= boardSize || snake.slice(1).some(part => part.x === head.x && part.y === head.y)) {
gameRunning = false;
}
}
function placeFood() {
let newFoodPos;
do {
newFoodPos = {
x: Math.floor(Math.random() * boardSize),
y: Math.floor(Math.random() * boardSize)
};
} while (snake.some(part => part.x === newFoodPos.x && part.y === newFoodPos.y));
food = newFoodPos;
}
function aiBot() {
const head = snake[0];
let newDx = dx;
let newDy = dy;
function willCollide(nextX, nextY) {
return (nextX < 0 || nextX >= boardSize || nextY < 0 || nextY >= boardSize || snake.slice(1).some(part => part.x === nextX && part.y === nextY));
}
if (food.x > head.x && !willCollide(head.x + 1, head.y)) {
newDx = 1; newDy = 0;
} else if (food.x < head.x && !willCollide(head.x - 1, head.y)) {
newDx = -1; newDy = 0;
} else if (food.y > head.y && !willCollide(head.x, head.y + 1)) {
newDx = 0; newDy = 1;
} else if (food.y < head.y && !willCollide(head.x, head.y - 1)) {
newDx = 0; newDy = -1;
}
if (willCollide(head.x + newDx, head.y + newDy)) {
if (!willCollide(head.x, head.y + 1)) {
newDx = 0; newDy = 1;
} else if (!willCollide(head.x, head.y - 1)) {
newDx = 0; newDy = -1;
} else if (!willCollide(head.x + 1, head.y)) {
newDx = 1; newDy = 0;
} else if (!willCollide(head.x - 1, head.y)) {
newDx = -1; newDy = 0;
}
}
dx = newDx;
dy = newDy;
}
function gameLoop() {
if (gameRunning) {
aiBot();
moveSnake();
updateBoard();
setTimeout(gameLoop, 200);
} else {
alert("Game Over!");
}
}
initBoard();
placeFood();
updateBoard();
gameLoop();