diff --git a/snake.html b/snake.html index 5abc304..8a81257 100644 --- a/snake.html +++ b/snake.html @@ -65,10 +65,13 @@ upPressed(); } else if (e.key === "ArrowDown") { downPressed(); + } else if (e.key === "Escape") { + escPressed(); } }); window.setInterval(() => { + gameUpdate(); for (const tile of document.querySelectorAll(".body, .head, .fruit")) { @@ -84,24 +87,83 @@ if (fruit !== null) { document.getElementsByClassName(fruit.x + "-" + fruit.y)[0].classList.add("fruit"); } - }, 1000); + }, 300); // this is where your implementation starts - - function gameUpdate() { + let dir = 1; //orientation variable, 0 = up, 1 = right, 2 = down, 3 = left + let paused = false; + let justAte = false; + function getRand(x) { + return Math.floor(Math.random() * x); } + function gameUpdate() { + if(paused){ + return; + } + if (fruit === null) { + fruit = {x: getRand(10), y: getRand(10)}; + } + //console.log(dir); + + if (fruit.x === snake[0].x && fruit.y === snake[0].y) { + justAte = true; + fruit = null; + snake.unshift({...snake[0]}); + } + if (!justAte) { + for (let i = snake.length - 1; i > 0; i--){ + snake[i].x = snake[i-1].x; + snake[i].y = snake[i-1].y; + } + } + switch (dir) { + case 1: + snake[0].x += 1 + break; + case 2: + snake[0].y += 1 + break; + case 3: + snake[0].x -= 1 + break; + case 0: + snake[0].y -= 1 + break; + + } + for (let index = snake.length - 1; index > 0; index--) { + const element = snake[index]; + if (snake[0].x === element.x && snake[0].y === element.y){ + alert('You suck at snake'); + window.location.replace('https://www.youtube.com/watch?v=dQw4w9WgXcQ&list=PLahKLy8pQdCM0SiXNn3EfGIXX19QGzUG3'); + + } + + } + snake[0].x = (snake[0].x + 10) % 10; + snake[0].y = (snake[0].y + 10) % 10; + justAte = false; + } function leftPressed() { + dir = 3; } function rightPressed() { + dir = 1; } function upPressed() { + dir = 0; } function downPressed() { + dir = 2; } + function escPressed() { + paused = !paused + } + });