xxxxxxxxxx
117
let w = 700;
let h = 700;
let sq = 20;
function setup() {
createCanvas(w, h);
}
class Snake {
constructor(x, y) {
this.x = x;
this.y = y;
this.size = 19;
this.body = [];
this.score = 0;
}
drawSnake() {
this.head = [this.x, this.y];
fill(255, 0, 0);
rect(this.head[0], this.head[1], this.size, this.size);
for (let i = 0; i < this.body.length; i++) {
rect(this.body[i][0], this.body[i][1], this.size, this.size);
}
}
Mvt() {
if (keyCode === UP_ARROW) {
this.y -= 20;
} else if (keyCode === DOWN_ARROW) {
this.y += 20;
} else if (keyCode === RIGHT_ARROW) {
this.x += 20;
} else if (keyCode === LEFT_ARROW) {
this.x -= 20;
}
if (this.x > w) {
this.x = 0;
}
if (this.x < 0) {
this.x = w;
}
if (this.y > h) {
this.y = 0;
}
if (this.y < 0) {
this.y = h;
}
}
eatFood() {
if (this.x === food.x && this.y === food.y) {
this.score += 1;
for (let i = 0; i < this.body; i++) {
}
return true;
} else {
return false;
}
}
bodyGenerator() {
this.eatFood();
this.body.push([this.head[0], this.head[1]]);
if (this.body.length > this.score) {
this.body.splice(0, 1);
}
}
eatSelf() {
if (this.body.lentgh >= 1){
for (let i = 1; i < this.body.length; i++) {
if (this.head[0] === this.body[i][0] && this.head[1] === this.body[i][1]) {
this.body.splice(0, this.body.length - 1);
}
}
}
}
}
class Food {
constructor() {
this.x = this.x = Math.floor((Math.random() * w) / 20) * 20;
this.y = this.y = Math.floor((Math.random() * h) / 20) * 20;
this.color = 255;
this.size = 19;
}
drawFood() {
fill(0, 255, 0);
rect(this.x, this.y, this.size, this.size);
}
spawn() {
if (snake.x === this.x && snake.y === this.y) {
let xc = Math.random();
let yc = Math.random();
this.x = Math.floor((xc * w) / 20) * 20;
this.y = Math.floor((yc * h) / 20) * 20;
}
}
}
let snake = new Snake(200, 200);
let food = new Food();
function draw() {
background(0);
frameRate(6);
stroke(255);
for (let x = sq; x < w; x = x + sq) {
line(x, 0, x, h);
}
for (let y = sq; y < h; y = y + sq) {
line(0, y, h, y);
}
snake.drawSnake();
snake.Mvt();
snake.bodyGenerator();
snake.eatSelf();
food.drawFood();
food.spawn();
}