-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsnake_obj.js
More file actions
64 lines (61 loc) · 1.85 KB
/
snake_obj.js
File metadata and controls
64 lines (61 loc) · 1.85 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
import getInputDirection from "./input_keys.js";
let upBtn = document.getElementById("up");
let downBtn = document.getElementById("down");
let speed = document.getElementById("speed");
upBtn.addEventListener("click", () => {
SNAKE_SPEED += 1;
speed.innerText = `Speed ${SNAKE_SPEED}`;
});
downBtn.addEventListener("click", () => {
if (SNAKE_SPEED <= 1) return;
SNAKE_SPEED -= 1;
speed.innerText = `Speed ${SNAKE_SPEED}`;
});
export let SNAKE_SPEED = 5;
const snakeBody = [{ x: 11, y: 11 }];
let newSegment = 0;
export function updateSnake() {
addNewSegment();
// console.log(newSegment);
let inputDirection = getInputDirection();
for (let i = snakeBody.length - 2; i >= 0; i--) {
snakeBody[i + 1] = { ...snakeBody[i] };
}
snakeBody[0].x += inputDirection.x;
snakeBody[0].y += inputDirection.y;
}
export function drawSnake(gameboard) {
snakeBody.forEach((segment) => {
const snakeElement = document.createElement("div");
snakeElement.style.gridRowStart = segment.y;
snakeElement.style.gridColumnStart = segment.x;
snakeElement.classList.add("snake");
gameboard.appendChild(snakeElement);
});
}
export function expandSnake(expandRate) {
newSegment += expandRate;
}
export function onSnake(currentPosition, { ignoreHead = false } = {}) {
return snakeBody.some((sigment, index) => {
if (ignoreHead && index === 0) return false;
return equalPosition(sigment, currentPosition);
});
}
function equalPosition(snakePosition, foodPosition) {
return (
snakePosition.x === foodPosition.x && snakePosition.y === foodPosition.y
);
}
function addNewSegment() {
for (let i = 0; i < newSegment; i++) {
snakeBody.push({ ...snakeBody[snakeBody.length - 1] });
}
newSegment = 0;
}
export function getHead() {
return snakeBody[0];
}
export function snakeIntersection() {
return onSnake(snakeBody[0], { ignoreHead: true });
}