xxxxxxxxxx
87
let [x, y] = [400, 400];
let foods = [];
let player = null;
function setup() {
createCanvas(800, 800);
for (i = 0; i < 5; i++) {
generateFood();
}
player = new Player(400, 400, 15, "red");
}
function draw() {
background(230);
showFood();
player.move();
player.draw();
player.collided();
}
function showFood() {
for (let i = 0; i < foods.length; i++) {
rect(foods[i].x, foods[i].y, foods[i].size, foods[i].size);
}
}
function generateFood() {
let fd = new Food(floor(random(0, width)), floor(random(0, width)),10);
foods.push(fd);
}
class Player {
constructor(x, y, size, color) {
this.x = x;
this.y = y;
this.size = size;
this.color = color;
}
draw() {
circle(this.x, this.y, this.size);
fill(this.color);
}
move() {
if (keyIsDown(LEFT_ARROW)) {
this.x -= 5;
}
if (keyIsDown(RIGHT_ARROW)) {
this.x += 5;
}
if (keyIsDown(UP_ARROW)) {
this.y -= 5;
}
if (keyIsDown(DOWN_ARROW)) {
this.y += 5;
}
}
grow(){
this.size = this.size + 3;
}
collided(){
for(let i = 0; i < foods.length; i++){
let d = dist(this.x,this.y, foods[i].x, foods[i].y);
if(d < player.size + 10){
foods.splice(i,1);
player.grow();
generateFood();
}
}
}
}
class Food {
constructor(x, y,size) {
this.x = x;
this.y = y;
this.size = size;
}
}