xxxxxxxxxx
57
let columns,
rows,
gridScale,
grid,
snake,
food;
function setup() {
columns = 20;
rows = 20;
gridScale = 20;
grid = new Grid(columns, rows, gridScale);
snake = new Snake(grid, 0, 0, 50);
food = new Food(grid, 0, 0, "#C36");
food.randomPosition(snake.getBody());
createCanvas(columns * gridScale, rows * gridScale);
frameRate(10);
}
function draw() {
background(22);
food.show();
snake.move();
if (snake.selfCollide()) {
createP("Game over!").style("color", "#EEE").style("font-family", "Montserrat");
noLoop();
}
if (snake.eats(food)) {
snake.grow();
food.randomPosition(snake.getBody());
}
snake.show();
}
function keyPressed() {
switch (key) {
case "ArrowUp":
snake.setSpeed(0, -1);
break;
case "ArrowDown":
snake.setSpeed(0, 1);
break;
case "ArrowLeft":
snake.setSpeed(-1, 0);
break;
case "ArrowRight":
snake.setSpeed(1, 0);
break;
}
}
function sign(number) {
if (number)
return number / abs(number);
return 0;
}