I'm interested in exploring whether p5.js allows for the creation of a class that can draw sub-classes within itself. One idea I have in mind is to create a 4x4 grid composed of individual

My goal is to create a game similar to Tetris, where the pieces are composed of smaller blocks that share attributes.

My current progress includes:

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();

      }
     ...
    }

and:

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();

      }
    }

In my main component:

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)
}

I envision having a Block class to draw a small block, then utilizing that within a Square class to draw 4 small blocks. By creating an instance of Square, I aim to have 4 blocks connected as one object.

I suspect there may be a need for a for loop somewhere in my code.

Answer №1

After some experimentation, I created the following code. It may be basic, but it serves as a good starting point.

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>

The polyomino class is capable of managing tetromino subsets by defining their shapes as matrices.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with displaying Wavesurfer.js waveform in custom Shopify section

Greetings to the Stockoverflow Community, I am facing a challenge with integrating WaveSurfer.js into a customized section on my Shopify store. Even though I have successfully implemented the section, the waveform visualization is not appearing. Link to ...

Error thrown by Jest: TypeError - req.headers.get function is not defined

I have a function that is used to find the header in the request object: export async function authorizeAccess(req: Request): Promise<Response | {}> { const access = req.headers.get('Access') if(!access) return Response.json('N ...

Managing the handling of each catch in $httpBackend.when()

I've been working on creating Jasmine unit tests for my Angular project, and I've come across a situation that I'm not quite sure how to tackle. Within my project, I have implemented a response interceptor that can retry a request if it enc ...

Run a PHP script that creates a PDF file using jQuery AJAX

I am currently working with a form that looks like this: <form action="tcpdf/examples/example_0611.php" method="get"> Name: <input type="text" name="name"><br> E-mail: <input type="text" name="email"><br> <input type="subm ...

Unique calculation for rotational movement

I am currently developing a unique compass application. Although the project is progressing well, I am facing a significant challenge with one aspect: My code calculates degree angles within the range of -360 and 360: -318°, -29°, 223°, -163°, ... ...

What is the best way to execute an API function call within an ng-repeat loop?

I'm encountering an issue with a scope function in my controller that calls an API to retrieve data from a database. This scope function is being used within an ng-repeat loop. However, when I try running the application, it becomes unresponsive. Whil ...

Modifying the <TypescriptModuleKind> setting for typescript transpilation in project.csproj is not supported in Visual Studio 2017

I recently encountered an issue with changing the module kind used by the transpiler in Visual Studio. Despite updating the <TypescriptModuleKind> in the project's project.csproj file from commonjs to AMD, the transpiler still defaults to using ...

Turning off the transpiler in Vue Webpack to simplify the debugging process

Debugging in Vue can be quite challenging, especially when it comes to setting breakpoints and stepping through the code. The issue seems to stem from the transpiling of javascript ES6/ES2015/ES2016/ES2017 to ES5. While source maps provide some assistance, ...

Tips for setting up listeners across multiple modules using socket.io

Last year, I created a multiplayer game using node.js and socket.io. Now, as part of my efforts to enhance the game, I am working on breaking down the code into modules. Currently, I am utilizing expressjs 4.4 along with socket.io 1.0. One challenge I enco ...

Encountering a "Parsing error: Unexpected token, expected ";" " when developing a React application with the provided code

I am currently working on developing a React application, and I have encountered an issue in my app.js file regarding the render function. Despite being new to JavaScript, I am unable to figure out why this error is occurring. Apologies if it is due to a s ...

After refreshing, the LocalStorage in Angular 2 seems to disappear

Something a little different here :) So, when attempting to log a user in, I am trying to store the access_token and expires in localStorage. It seems to be working "okay". However, if I refresh the page, the tokens disappear. Also, after clicking the log ...

Angular CORS problem when sending information to Google Forms

When submitting the data: Error Message: Unfortunately, an error occurred while trying to send the data. The XMLHttpRequest cannot load https://docs.google.com/forms/d/xxxxxxxxxxxxx/formResponse. The response to the preflight request did not pass the ac ...

Error: The bun.js application encountered a SegmentationFault at line 188

I'm attempting to execute the following command on my current repository, which already has a registry set up in the .npmrc. bun install -y The purpose of the -y flag is to generate the yarn v1 lockfile. However, it's resulting in the followin ...

Verify for any alterations in the code by utilizing the inspect element feature

Currently dealing with a security concern regarding my older Java application. Is there a method available to detect any modifications made to my code (HTML or script) through Developer Tools on the user's end? This would allow me to prevent form subm ...

Altering the appearance of an input field upon submission

https://jsfiddle.net/3vz45os8/7/ I'm working on a JSFiddle where I am trying to change the background color of input text based on whether the word is typed correctly or incorrectly. Currently, it's not functioning as expected and there are no e ...

What is the process for submitting and storing a collection of files in a database as a list?

I am trying to implement a feature in my MVC project where users can upload multiple files and see them listed before submitting the form. However, I am facing some challenges with finding a solution for this. Demo: My goal is to allow users to add multi ...

Transferring information to the controller and refreshing the interface (Single-page design)

I'm stuck on a personal project and could really use some help. If anyone has any feedback, it would be greatly appreciated. Thanks in advance. In my index.php file, I have a div with the id main-container. Inside this container, there are two separa ...

What is the best way to position a popup div in CSS?

Currently, I am in the process of developing a website that displays DVD details when hovering over an image, similar to what is shown in picture 1. However, I've encountered an issue where the content gets cut off for DVDs located on the right side o ...

Guide on setting up a MEAN stack application to run on port 8080

I am brand new to the mean stack development environment. I'm attempting to configure my root domain name to display the app directory once I enter the command grunt, but the only way it currently works is at website.com:8080/!#/. How can I get it to ...

Manually browse through images in photoswipe by clicking on them to move to the previous or next ones

Utilizing photoswipe within my mobile app has been a seamless experience. Instead of utilizing the full screen view, we are displaying images within a target div. A new requirement was introduced to hide the built-in toolbar and incorporate arrow buttons ...