xxxxxxxxxx
92
map1 = [];
h = 100;
w = 100;
//snake class
class snake {
constructor(hx, hy) {
this.x = hx;
this.y = hy;
this.tail = [];
this.map = [];
}
move() {
var phx = this.x;
var phy = this.y;
if (keyCode == UP_ARROW) {
this.y--;
} else if (keyCode == RIGHT_ARROW) {
this.x++;
} else if (keyCode == LEFT_ARROW) {
this.x--;
} else if (keyCode == DOWN_ARROW) {
this.y++;
}
for (var i = 0; i < this.tail.length; i++) {
if (i == 0) {
//if its the first time set the next one to the head
this.tail[i].x = phx;
this.tail[i].y = phy;
} else {
//if its not the first time, set it to the last poition
//keep the previous x
tpx = this.tail[i].x;
tpy = this.tail[i].y;
//move it to the last one
this.tail[i].x = px;
this.tail[i].y = py;
px = tpx;
py = tpy;
}
}
}
drawsnek() {
//console.log()
this.map[this.x][this.y] = 1 //draw the head of the snake
//loop to draw the tail
for (var i=0;i<this.tail.length;i++){
this.map1[this.tail[i].x][this.tail[i].y] = 1;//set the tail in the map1 array
}
return this.map
}
}
player = new snake(0, 0);
function setup() {
createCanvas(500, 500);
strokeWeight(1);
//just make the empty map
for (var x = 0; x < w; x++) {
append(player.map, []);
for (var y = 0; y < h; y++) {
append(player.map[x], 0);
}
}
emap = player.map; //this is an empty map
}
function draw() {
//background(255);
//draw the snake to the map1 array
map1=player.drawsnek(map1)
//draws the map1 array
for (var x = 0; x < 2500; x += 50) {
for (var y = 0; y < 2500; y += 50) {
if (map1[x / 50][y / 50] == 1) {
fill(0, 255, 0);
} else {
fill(0);
}
square(x, y, 50);
}
}
//out of the loop
player.move()
//console.log(keyCode == RIGHT_ARROW)
}