https://editor.p5js.org/guldus/full/r1G7x-SW4
var box = [];
var block;
var score = 0;
function setup() {
createCanvas(500, 500);
for (var i = 0; i < 20; i++) {
box[i] = new Box();
}
block = new Block();
textSize(22);
textFont("Thoma")
}
function keyPressed() {
if (keyCode === LEFT_ARROW) {
if (block.x != 0) block.move(-25)
} else if (keyCode === RIGHT_ARROW) {
if (block.x != width - block.blockLength) block.move(25)
}
}
function gameOver() {
for (var i = 0; i < 20; i++) {
if (box[i].y + 25 == block.y) {
for (var j = 1; j < (block.blockLength) / 25; j++) {
if (box[i].x == block.x + j * 25 || box[i].x + 25 == block.x + j * 25) {
noLoop();
fill(255,0,0);
text("game over",width/2-60,100);
break
}
}
}
}
}
function draw() {
background(160);
for (var i = 0; i < 20; i++) {
box[i].fall();
box[i].show();
}
block.show();
gameOver();
fill(255,255,0);
text("Score: "+score,30,50 )
}
function Box() {
this.x = floor(random(0, 25)) * 25;
this.y = floor(random(-25, 0)) * 25;
this.ySpeed = 2.5;
this.fall = function () {
this.y += this.ySpeed;
if (this.y > height) {
this.x = floor(random(0, 25)) * 25;
this.y = floor(random(-25, 0)) * 25;
score +=1;
}
}
this.show = function () {
fill(255, 0, 0);
rect(this.x, this.y, 25, 25);//x position, y position, height, width
}
}
function Block() {
this.blockLength = 100;
this.x = (width - this.blockLength) / 2;
this.y = height - 25;
//this.xSpeed = 3.5;,
this.move = function (xSpeed) {
this.x += xSpeed;
}
this.show = function () {
fill(0, 255, 0);
rect(this.x, this.y, this.blockLength, 25)
}
}
Leave a comment