👳 Checkpoint

./script.js:9517054/1554
./style.css:9517054/150
This commit is contained in:
Glitch (glitch-hello-website) 2022-02-28 19:11:15 +00:00
parent d33cba71a2
commit 192f879bf3
2 changed files with 33 additions and 15 deletions

View file

@ -27,9 +27,9 @@ function draw() {
ctx.clearRect(0, 0, 500, 500);
for (let i = 0; i < game.size; i++) {
for (let j = 0; j < game.size; j++) {
ctx.fillStyle = inSnake(i, j) ? "green"
: (i === game.apple[0] && j === game.apple[1]) ? "red"
: "black";
ctx.fillStyle = inSnake(i, j) ? "#43ad39"
: (i === game.apple[0] && j === game.apple[1]) ? "#eb4034"
: "#222222";
ctx.fillRect(i * size, j * size, size, size);
}
}
@ -37,42 +37,55 @@ function draw() {
function update() {
const b = game.snake.body;
move();
if(game.apple[0] === b[b.length - 1][0] && game.apple[1] === b[b.length - 1][1]) {
const l = b[b.length - 1];
const next = move();
if(game.apple[0] === next[0] && game.apple[1] === next[1]) {
const x = Math.floor(Math.random() * game.size);
const y = Math.floor(Math.random() * game.size);
game.apple = [x, y];
} else {
b.shift();
}
if(inSnake(next[0], next[1])) {
console.log("a");
// game over
}
if(l[0] < 0 || l[0] >= game.size || l[1] < 0 || l[1] >= game.size) {
console.log("a");
// game over
}
b.push(next);
function move() {
const [x, y] = b[b.length - 1];
const [x, y] = l;
switch (game.snake.dir) {
case "left":
return b.push([x - 1, y]);
return [x - 1, y];
case "right":
return b.push([x + 1, y]);
return [x + 1, y];
case "up":
return b.push([x, y - 1]);
return [x, y - 1];
case "down":
return b.push([x, y + 1]);
return [x, y + 1];
}
}
}
document.addEventListener("keydown", (e) => {
console.log(e);
const s = game.snake;
switch (e.key) {
case "ArrowLeft":
return (s.dir = "left");
return (s.dir !== "right" ? s.dir = "left" : 0);
case "ArrowRight":
return (s.dir = "right");
return (s.dir !== "left" ? s.dir = "right" : 0);
case "ArrowUp":
return (s.dir = "up");
return (s.dir !== "down" ? s.dir = "up" : 0);
case "ArrowDown":
return (s.dir = "down");
return (s.dir !== "up" ? s.dir = "down" : 0);
}
});

View file

@ -0,0 +1,5 @@
body {
margin: 2em auto;
padding: 0;
text-align: center;
}