Modeling Game Objects with Classes
In game development, visual objects generally fall into two categories: blocks (static objects that do not move) and sprites (objects that can be moved and manipulated as a single entity). Let’s create class-based abstractions for each one, starting with Block.
Building the Block Class
Create a src/model folder, then add a block.js file:
class Block {
constructor(x, y, width, height, color) {
this.x = x;
this.y = y;
this.height = height;
this.width = width;
this.color = color;
}
draw(ctx) {
ctx.beginPath();
ctx.rect(this.x, this.y, this.width, this.height);
ctx.fillStyle = this.color;
ctx.fill();
ctx.closePath();
}
}
This should look familiar from the Todo app, where we used classes to model Todo and TodoList. The difference is what we are modeling. There we modeled data. Here we are modeling something visual, a rectangular block on a canvas.
The constructor takes position (x, y), dimensions (width, height), and a color. The draw method takes a canvas rendering context (ctx) and uses it to draw a filled rectangle at the block’s position. So each block knows how to draw itself.
Checkpoint: Commit your progress.
git add .
git commit -m "brick-03: Add Block class with constructor and draw method"
git push