xxxxxxxxxx
85
let snake;
function setup() {
createCanvas(500, 500);
snake = new Snake(250, 250);
snake.add();
snake.add();
snake.add();
console.log(snake.circles);
}
function keyPressed(){
snake.xchange = 0; snake.ychange = 0;
if (keyCode === LEFT_ARROW) snake.xchange = -1;
if (keyCode === RIGHT_ARROW) snake.xchange = 1;
if (keyCode === UP_ARROW) snake.ychange = -1;
if (keyCode === DOWN_ARROW) snake.ychange = 1;
}
function draw() {
background(220);
snake.move();
snake.draw();
}
class Snake{
constructor(x, y){
this.r = 10;
this.circles = [new Circle(x, y)];
this.xchange = -1;
this.ychange = 0;
}
draw(){
noStroke();
fill(255, 0, 0);
for (let i=0; i<this.circles.length; i++)
this.circles[i].draw(this.r);
}
add(){
if (this.xchange === -1){
let temp = new Circle(this.circles[this.circles.length-1].x+2*this.r, this.circles[this.circles.length-1].y);
this.circles.push(temp);
}
}
move(){
for (let i=this.circles.length-1; i>0; i--){
if (this.xchange !== 0){
if (this.circles[i].y === this.circles[0].y)
this.circles[i].x += this.xchange;
else{
if (this.circles[0].y - this.circles[i].y > 0) this.circles[i].y += 1;
else this.circles[i].y -= 1;
}
}
else{
if (this.circles[i].x === this.circles[0].x)
this.circles[i].y += this.ychange;
else
if (this.circles[0].x - this.circles[i].x > 0) this.circles[i].x += 1;
else this.circles[i].x -= 1;
}
}
this.circles[0].x += this.xchange;
this.circles[0].y += this.ychange;
if (this.circles[0].x < -this.r) this.circles[0].x = width+this.r;
else if (this.circles[0].x > (width+this.r)) this.circles[0].x = -this.r;
else if (this.circles[0].y < -this.r) this.circles[0].y = height+this.r;
else if (this.circles[0].y > (height+this.r)) this.circles[0].y = -this.r;
}
}
class Circle{
constructor(x, y){
this.x = x;
this.y = y;
}
draw(r){
circle(this.x, this.y, 2*r);
}
}