class GameObject {
static assets = new Map();
url;
// …
constructor(url, ctx) {
this.url = url;
this.ctx = ctx;
}
async preload() {
if (!GameObject.assets.has(this.url)) {
const asset = new Image();
asset.src = this.url;
GameObject.assets.set(
this.url,
asset.decode().then(() => asset),
);
}
this.asset = await GameObject.assets.get(this.url);
if (this.size.w === undefined) {
this.size.w = this.asset.width;
this.size.h = this.asset.height;
}
}
// …
}Build the brick field / notebook
Build the brick field
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
class Brick extends GameObject {
constructor(url, ctx, x, y, w, h) {
super(url, ctx);
this.pos = { x, y };
this.size = { w, h };
}
draw() {
const { left, top } = this.hitbox;
this.ctx.drawImage(this.asset, left, top, this.size.w, this.size.h);
}
}// …
const paddle = new Paddle("img/paddle.png", ctx);
colliders.push(paddle);
const bricks = initBricks();
// …function initBricks() {
const bricksLayout = {
width: 50,
height: 20,
count: {
row: 3,
col: 7,
},
offset: {
top: 50,
left: 60,
},
padding: 10,
};
const bricks = [];
// continue adding here...
return bricks;
}for (let c = 0; c < bricksLayout.count.col; c++) {
for (let r = 0; r < bricksLayout.count.row; r++) {
const brickX =
c * (bricksLayout.width + bricksLayout.padding) +
bricksLayout.offset.left;
const brickY =
r * (bricksLayout.height + bricksLayout.padding) +
bricksLayout.offset.top;
const newBrick = new Brick(
"img/brick.png",
ctx,
brickX,
brickY,
bricksLayout.width,
bricksLayout.height,
);
bricks.push(newBrick);
}
}for (const brick of bricks) {
brick.draw();
}const bricks = initBricks();
for (const brick of bricks) {
colliders.push(brick);
}class Brick extends GameObject {
// …
onCollide() {
bricks.splice(bricks.indexOf(this), 1);
colliders.splice(colliders.indexOf(this), 1);
}
}