flappy block
by greg gorlen
JavaScript
"use strict";
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
document.body.style.margin = 0;
document.body.style.height = "99vh";
document.body.style.display = "flex";
document.body.style.justifyContent = "center";
document.body.style.alignItems = "center";
canvas.width = canvas.height = 400;
const gridSize = canvas.width / 20;
let keyPressed;
let pipes;
let score;
document.addEventListener("keydown", e => {
e.preventDefault();
if (!e.repeat) { keyPressed = true; }
});
function Pipe(x, width, speed, color, canvas) {
this.x = x;
this.width = width;
this.size = width * 2;
this.speed = speed;
this.color = color;
this.gap = this.newGap(canvas);
}
Pipe.prototype.newGap = function (canvas) {
return this.size / 2 + Math.random() * (canvas.height - this.size * 2);
};
Pipe.prototype.move = function (canvas) {
this.x += this.speed;
if (this.x + this.size < 0) {
this.x = canvas.width;
this.gap = this.newGap(canvas);
return true;
}
return false;
};
Pipe.prototype.draw = function (ctx, canvas) {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, 0, this.width, canvas.height);
ctx.fillStyle = "skyblue";
ctx.fillRect(this.x, this.gap, this.width, this.size);
};
const bird = {
init: function (x, y, size, color) {
this.x = x;
this.y = y;
this.vy = 0;
this.size = size;
this.color = color;
},
flap: function () { this.vy = -5; },
move: function () {
this.vy += 0.3;
this.y += this.vy;
},
draw: function (ctx) {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.size, this.size);
},
alive: function (canvas, pipes) {
for (let i = 0; i < pipes.length; i++) {
if (this.x + this.size >= pipes[i].x &&
this.x <= pipes[i].x + pipes[i].width &&
!(this.y >= pipes[i].gap &&
this.y + this.size <= pipes[i].gap + pipes[i].size)) {
return false;
}
...