You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

100 lines
2.2 KiB

function randInt(min, max) {
return Math.floor(Math.random() * max) + min;
}
let snake = {
x: 0,
y: 0,
dir: 1,
score: 0,
tail: []
};
let apple = {
x: randInt(0, 14),
y: randInt(0, 14),
reset: () => {
apple.x = randInt(0, 14);
apple.y = randInt(0, 14);
}
};
// 4
// 3 - 1
// 2
function setup(){
createCanvas(700, 700);
game();
}
function game(){
let game = setInterval(() => {
background(240);
snake.tail.push([snake.x, snake.y]);
if(snake.dir == 1) snake.x++;
else if(snake.dir == 2) snake.y++;
else if(snake.dir == 3) snake.x--;
else if(snake.dir == 4) snake.y--;
if(snake.x == apple.x && snake.y == apple.y){
snake.score++;
document.getElementById("score").innerText = snake.score;
apple.reset();
}
else snake.tail.shift();
fill(51,203,41);
rect(snake.x*50,snake.y*50,50);
let end = false;
snake.tail.forEach(tail => {
fill(169,246,164);
rect(tail[0]*50,tail[1]*50,50);
if(tail[0] == snake.x && tail[1] == snake.y) end = !end;
})
fill(240,55,55);
rect(apple.x*50,apple.y*50,50);
if(snake.x >= 14 ||snake.y >= 14 || snake.x < 0 ||snake.y < 0 || end){
background(0);
document.getElementById("loose").style.display="block";
clearInterval(game);
}
}, 200)
}
function keyPressed(){
if(keyCode === RIGHT_ARROW && snake.dir != 3){
snake.dir = 1;
}
else if(keyCode === DOWN_ARROW && snake.dir != 4){
snake.dir = 2;
}
else if(keyCode === LEFT_ARROW && snake.dir != 1){
snake.dir = 3;
}
else if(keyCode === UP_ARROW && snake.dir != 2){
snake.dir = 4;
}
}
function restart(){
document.getElementById("loose").style.display = "none";
game();
snake = {
x: 0,
y: 0,
dir: 1,
score: 0,
tail: []
};
apple.reset();
}
window.addEventListener("keydown", function(e) {
if(["Space","ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].indexOf(e.code) > -1) {
e.preventDefault();
}
}, false);