xxxxxxxxxx
122
const WIDTH = 200;
const HEIGHT = 20;
const SPEED = 1;
const ACCL = 0.1;
let currentBlock;
let blocks = [];
let gameOver = false;
let win = false;
function setup() {
createCanvas(400, 400);
noStroke();
textAlign(CENTER);
textSize(30);
reset();
}
function draw() {
background(50);
fill(255, 0, 0);
for(let i = 0; i < blocks.length; i ++) {
blocks[i].draw();
}
if(!gameOver) {
currentBlock.update();
fill(0, 255, 0);
currentBlock.draw();
} else {
if(win) {
fill(0, 255, 0);
text("You Win!", width/2, height/2);
} else {
fill(0, 0, 255);
text("Game Over :(", width/2, height/2);
}
}
}
function keyReleased() {
if(key === " ") {
if(gameOver) {
reset();
} else {
dropBlock();
}
}
}
function dropBlock() {
currentBlock.drop(blocks[blocks.length - 1]);
if(currentBlock.w <= 0) {
gameOver = true;
return;
}
blocks.push(currentBlock);
currentBlock = currentBlock.nextBlock();
if(currentBlock.y <= 0) {
gameOver = true;
win = true;
return;
}
}
function reset() {
gameOver = false;
startBlock = new Block(SPEED, WIDTH, height - HEIGHT);
startBlock.x = width/2 - WIDTH/2;
blocks = [startBlock];
currentBlock = new Block(SPEED, WIDTH, height - HEIGHT * 2);
}
class Block {
constructor(spd, w, y) {
this.dir = 1;
this.spd = spd
this.w = w;
this.x = 0;
this.y = y;
}
nextBlock() {
return new Block(this.spd + ACCL, this.w, this.y - HEIGHT);
}
left() {
return this.x;
}
right() {
return this.x + this.w;
}
drop(prev) {
if(!prev) {
return;
}
const l = max(this.left(), prev.left());
const r = min(this.right(), prev.right());
this.x = l;
this.w = r - l;
}
update() {
this.x += this.spd * this.dir;
if(this.x <= 0 || this.x + this.w >= width) {
this.dir *= -1;
}
}
draw() {
rect(this.x, this.y, this.w, HEIGHT);
}
}