Compare commits
1 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
285efd8cd0 |
1
.gitignore
vendored
Normal file
1
.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
||||
.idea
|
51
snake.html
51
snake.html
@ -17,8 +17,8 @@
|
||||
}
|
||||
|
||||
.tile {
|
||||
width: calc(100vmin/10);
|
||||
height: calc(100vmin/10);
|
||||
width: calc(100vmin/30);
|
||||
height: calc(100vmin/30);
|
||||
border: 1px solid black;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
@ -37,11 +37,14 @@
|
||||
</style>
|
||||
|
||||
<script>
|
||||
const fieldSize = 30;
|
||||
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
const game = document.getElementById("game");
|
||||
const tileTemplate = document.getElementById("tile-template");
|
||||
for (let x = 0; x < 10; x++) {
|
||||
for (let y = 0; y < 10; y++) {
|
||||
|
||||
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);
|
||||
@ -84,23 +87,61 @@
|
||||
if (fruit !== null) {
|
||||
document.getElementsByClassName(fruit.x + "-" + fruit.y)[0].classList.add("fruit");
|
||||
}
|
||||
}, 1000);
|
||||
}, 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>
|
||||
|
Loading…
Reference in New Issue
Block a user