snake/snake.html
2020-12-18 16:32:30 +01:00

157 lines
3.4 KiB
HTML

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Pátek snake</title>
<style>
body {
margin: 0;
}
#game {
width: 100vmin;
height: 100vmin;
display: flex;
flex-wrap: wrap;
margin: 0 auto;
}
.tile {
width: calc(100vmin/30);
height: calc(100vmin/30);
border: 1px solid black;
box-sizing: border-box;
}
.tile.body {
background-color: green;
}
.tile.head {
background-color: red;
}
.tile.fruit {
background-color: gold;
}
</style>
<script>
const fieldSize = 30;
document.addEventListener("DOMContentLoaded", () => {
const game = document.getElementById("game");
const tileTemplate = document.getElementById("tile-template");
for (let x = 0; x < fieldSize; x++) {
for (let y = 0; y < fieldSize; y++) {
const tile = tileTemplate.content.cloneNode(true);
tile.querySelector(".tile").classList.add(y + "-" + x);
game.appendChild(tile);
}
}
document.dispatchEvent(new Event("gameReady"));
});
</script>
<script>
document.addEventListener("gameReady", () => {
let snake = [{x: 0, y: 0}];
let fruit = null;
document.addEventListener("keydown", (e) => {
if (e.key === "ArrowLeft") {
leftPressed();
} else if (e.key === "ArrowRight") {
rightPressed();
} else if (e.key === "ArrowUp") {
upPressed();
} else if (e.key === "ArrowDown") {
downPressed();
}
});
window.setInterval(() => {
gameUpdate();
for (const tile of document.querySelectorAll(".body, .head, .fruit")) {
tile.classList.remove("body", "head", "fruit");
}
for (let i = 1; i < snake.length; i++) {
const tile = snake[i];
document.getElementsByClassName(tile.x + "-" + tile.y)[0].classList.add("body");
}
document.getElementsByClassName(snake[0].x + "-" + snake[0].y)[0].classList.add("head");
if (fruit !== null) {
document.getElementsByClassName(fruit.x + "-" + fruit.y)[0].classList.add("fruit");
}
}, 100);
// this is where your implementation starts
let direction = {x: 0, y: 0}
let length = 1;
fruit = randomPlace();
function vectorAdd(a,b) {
return {x: a.x+b.x, y: a.y+b.y}
}
function randomPlace() {
return {x: Math.round(Math.random() * (fieldSize-1)), y: Math.round(Math.random() * (fieldSize-1))};
}
function gameUpdate() {
const oldSnake = snake[0];
const newSnake = vectorAdd(oldSnake, direction);
newSnake.x = (fieldSize + newSnake.x) % fieldSize
newSnake.y = (fieldSize + newSnake.y) % fieldSize
snake.unshift(newSnake);
snake = snake.slice(0, length);
for (let i = 1; i < snake.length; i++) {
if (snake[i].x === snake[0].x && snake[i].y === snake[0].y) {
length = 1;
snake = [{x:0, y:0}];
fruit = randomPlace();
}
}
if (fruit.x === snake[0].x && fruit.y === snake[0].y) {
length++;
fruit = randomPlace();
}
}
function leftPressed() {
direction = {x: -1, y: 0};
}
function rightPressed() {
direction = {x: 1, y: 0};
}
function upPressed() {
direction = {x: 0, y: -1};
}
function downPressed() {
direction = {x: 0, y: 1};
}
});
</script>
</head>
<body>
<template id="tile-template">
<div class="tile"></div>
</template>
<div id="game">
</div>
</body>
</html>