xxxxxxxxxx
170
let end;
let add;
let appleX;
let appleY;
let t;
let gmap;
let head;
let freespaces;
let speed = 250;
//fucntions
function clearmap() {
for (let i = 0; i < 10; i++) {
for (let j = 0; j < 10; j++) {
gmap[i][j] = "#";
}
}
}
//----------end game
function endGame() {
clearInterval(t);
background(0);
fill("green");
text("Game Over", 200, 200);
end = true;
console.log("game over");
}
function setup() {
createCanvas(400, 400);
setupGame();
textAlign(CENTER);
}
function setupGame() {
key = ''
snake = [];
end = false;
add = false;
appleX = 1;
appleY = 2;
t = setInterval(updateGame, speed);
gmap = [];
head = [2, 3];
for (let i = 0; i < 10; i++) {
gmap[i] = [];
}
clearmap();
gmap[2][3] = "o";
}
function put_objects_in_gmap(){
gmap[appleX][appleY] = "a";
gmap[head[0]][head[1]] = "h";
for (let i = 0; i < snake.length; i++) {
// console.log(gmap,snake[i])
gmap[snake[i][0]][snake[i][1]] = "o";
}
}
function eat_apple(){
freespaces = []
for (let i=0;i<10;i++){
for (let j=0;j<10;j++){
if (gmap[i][j] == '#'){
freespaces.push([i,j])
}
}
}
//check eaten apple
if (head[0] == appleX && head[1] == appleY) {
add = true;
appleXY = random(freespaces);
appleX = floor(appleXY[0]);
appleY = floor(appleXY[1]);
}
}
function collison(){
for (let i = 0; i < snake.length; i++) {
// console.log(
// snake[i],
// snake[i][0] == head[0] && snake[i][0] == head[0],
// head
// );
if (snake[i][0] == head[0] && snake[i][1] == head[1]) {
console.log("snake collided");
endGame();
}
}
if (head[0] == 0) {
endGame();
}
if (head[0] == 9) {
endGame();
}
if (head[1] == 9) {
endGame();
}
if (head[1] == 0) {
endGame();
}
}
function draw() {}
function updateGame() {
//-----------------------keys---------------------/moving the head/snake
snake.unshift([head[0], head[1]]);
// chead = head;
if (key === "ArrowLeft") {
head[0] -= 1;
} else if (key === "ArrowRight") {
head[0] += 1;
}
if (key === "ArrowDown") {
head[1] += 1;
} else if (key === "ArrowUp") {
head[1] -= 1;
}
//clear game map
clearmap();
//set the apple and snake in gmap
put_objects_in_gmap()
//check free spaces for apple
eat_apple()
//draw da squares from gmap
background(0);
for (let i = 0; i < 10; i++) {
for (let j = 0; j < 10; j++) {
if (gmap[i][j] == "o") {
fill(0, 255, 0);
rect(map(i, 0, 10, 0, 400), map(j, 0, 10, 0, 400), 400 / 10, 400 / 10);
}
if (gmap[i][j] == "h") {
fill(255, 255, 255);
rect(map(i, 0, 10, 0, 400), map(j, 0, 10, 0, 400), 400 / 10, 400 / 10);
//console.log(i, j)
}
if (gmap[i][j] == "a") {
fill(255, 0, 0);
rect(map(i, 0, 10, 0, 400), map(j, 0, 10, 0, 400), 400 / 10, 400 / 10);
}
}
}
if (!add) {
snake.pop();
} else {
add = false;
}
//check collison
collison()
}
function mousePressed(){
end=false
setupGame();
}