使用 p5.js,是否可以绘制一个 class,在其内部绘制子 classes?例如,一个 4x4 的块由 1x1 的块组成

Using p5.js, is it possible to draw a class that draws sub-classes within itself? For example, a 4x4 block made up of 1x1 blocks

我正在尝试制作类似俄罗斯方块的游戏,其中游戏的各个部分均由共享属性的较小部分组成。

目前我有:

    export class SquareTetromino {
      [x: string]: any;
      constructor(x, y, w, h) {
      ...
      }

      show(p5) {
         p5.push();
         p5.translate(this.posX, this.posY);
         p5.fill("#D8B6FF")
         p5.rect(0,0,this.w, this.h);
         p5.pop();

      }
     ...
    }

和:

    export class BlockTetromino {
      [x: string]: any;
      constructor(x, y, w, h) {
      ...
      }

      test(p5) {
          this.testArray.push(new SquareTetromino(this.posX,this.posY,this.w,this.h));
          this.testArray.push(new SquareTetromino(this.posX - 50,this.posY,this.w,this.h));
          this.testArray.push(new SquareTetromino(this.posX - 50,this.posY + 50,this.w,this.h));
          this.testArray.push(new SquareTetromino(this.posX,this.posY + 50,this.w,this.h));
      }

      show(p5) {
          p5.push();
          this.testArray.forEach((block) => {
            block.show(p5)
          })
          p5.pop();

      }
    }

从我的主要组成部分:

  s.setup = () => {

  ...

            bodies.push(new BlockTetromino(200,-50,50,50))
            bodies[0].test(s);
  ...
          }

  s.draw = () => {
         ...


          for (let i = 0; i < bodies.length; i++) {
            bodies[i].show(s)
          }

我希望能够有一个绘制一个小块的 class 块,然后在绘制 4 个小块的 class 正方形中调用该块。然后,通过实例化 Square,我将 4 个块链接在一起作为一个对象。

我想我在某处缺少 for 循环。

我试了一下,想到了这个。它有点简陋,但它认为它可以作为一个起点。

class BuildingBlock{
 constructor(x, y, size, color){
  this.x = x;
  this.y = y;
  this.size = size;
  this.color = color || 'red';
  this.display();
 }

 display(){
  fill(this.color);
  rect(this.x, this.y, this.size, this.size);
 }
}

class Polyomino{
 constructor(x, y, shape, blockSize){
  this.x = x;
  this.y = y;
  this.shape = shape;
  this.blockSize = blockSize;
 }

 display(){
  for(let i = 0; i < this.shape.length; i++)
   for(let j = 0; j < this.shape[i].length; j++)
    if(this.shape[i][j] === 1)
     new BuildingBlock(this.x + (j*this.blockSize), this.y + (i*this.blockSize), this.blockSize);
 }
}

function setup(){
 createCanvas(400, 400);
 background(125);

 let pmShape = [
  [1, 1, 0, 1],
  [0, 1, 0, 1],
  [0, 1, 0, 1],
  [1, 1, 1, 1],
 ]
 let  p = new Polyomino(20, 20, pmShape, 30);
 p.display();

        let tmShape = [
            [1, 1, 0],
            [0, 1, 1]
        ];
        let tetromino = new Polyomino(200, 20, tmShape, 50);
        tetromino.display();
}
<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.min.js"></script>
</head>
<body>
 
</body>
</html>

多联骨牌 class 应该能够处理四联骨牌的子集;只需将形状定义为矩阵即可。