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

Set a personalized date as the initial reference point for the datepicker interface

Wondering how to set a default starting date for the datepicker in angular-ui.bootstrap? I recently discovered that this line of code does the trick. $scope.date = new Date(1980-12-12); While it successfully displays the value in the input box and date ...

Hidden visibility of input field prevents the value from being posted

I have a dropdown menu containing numbers as options. When a user selects a number, I want to display an input box using jQuery based on their selection. However, the issue arises when I try to submit the values of these input boxes as they are not being s ...

Transferring Data from Python Script to Browser (with an xserver running on a Linux system)

Looking for suggestions on how to efficiently transfer data from a Python script to a web browser. The Python script, as well as the browser, are operating under an xServer environment in Linux (specifically Raspbian on Raspberry Pi). The script is respon ...

napi and SWIG: ThreadSafeFunction only runs in a thread after the thread has finished its execution

Check out this repository I created, where a thread-safe function in a SWIG C++ class is executed using node-addon-api. The thread within the SWIG C++ class is triggered using the napi BlockingCallback as shown below: // C++ thread implementation for (int ...

How can I uniquely combine a code with an existing CSS class and make modifications to it?

I am using ngx-skeleton-loader and I would like to change the color, but I am facing some difficulties. Here is an image that illustrates the issue. When looking at the developer tools, you can see the styles action in the styles action bar. .loader ...

Encountered an error: Uncaught TypeError - Unable to access property 'active' as it is undefined within React code

<script type="text/babel"> class Frame extends React.Component{ render(){ return ( <div> <h2 className="os-animation" dat ...

The search for the view in the directory "/views" was unsuccessful in Express 4.0

I've been working on a project using Express 4.0 and the Express3-handlebars libraries for NodeJS. Below is the setup: app.set('views', path.join(__dirname, 'views/')); app.engine('hbs', hbs({defaultLayout: 'main&a ...

AngularJS component downgraded without change detection

Currently, I am utilizing Angular's downgradeComponent for performance optimization purposes. You can find more information about it here: https://angular.io/api/upgrade/static/downgradeComponent. The Angular component I am working with is defined as ...

The modification of a controller's attribute does not impact the view

Recently diving into Angular, I've encountered a small issue. Here's what's going on: After creating a module named "myMod", I proceeded to define a directive like so: myMod.directive("myDirective", function () { dir = { restri ...

Obtaining values from multi-dimensional arrays with JavaScript and node.js

I have a data structure like this: let arr = [ ['animal','lion'], ['plant','rose'], ['tree','coconut'], ] I want to reformat it to look like this: ['animal','lion' ...

Is there a bug in NodeJS that causes an error when a return statement is used with a line feed before the string to be returned?

I am attempting to call a function from a module in order to generate an HTML string. When the function is written with a line feed (LF) between the return statement and the string declaration as shown below, the return value becomes "undefined"... export ...

Using the Greasemonkey browser extension, one can employ the waitForKeyElements utility to trigger a function once a designated element becomes visible on the webpage

(In connection to the question I posted on Stack Overflow). I have been developing a userscript for metal-archives.com, which can be found here. When you navigate to a band page (like this example), you will see the DISCOGRAPHY section and its sub-tabs ...

Using PHP variables in JavaScript to access getElementById

I have multiple forms displayed on a single PHP page. They all follow a similar structure: <form id="test_form_1" action="test_submit.php" method="post" name="test_form"> <label>This is Question #1:</label> <p> &l ...

Command to conceal components for users visiting as guests

I'm looking to develop a directive that hides specific elements for guest users. Here is the current code I have: angular.module('someMod') .directive('premiumUser', premiumUser) .controller('PremiumUserCtrl', Pr ...

Transforming an array into a JSON object

I currently have an array structured like this: [ 'quality', 'print-quality: 4', 'x-dimension', 'Value: 21590', 'Value: y-dimension', 'Value: 27940', 'Value: ', 'Valu ...

Issue with Knockoutjs Custom Binding for Radio Button Groups Failing to Update Selection

I am currently working on creating a unique custom binding in knockout that is similar to the default options binding handler, but instead of a dropdown, it utilizes radio buttons. Whenever an item is added to the array, the update is triggered. However, ...

Scroll the content of a div to the bottom using JavaScript

I'm facing a situation with my code: function scrollme(){ dh=document.body.scrollHeight ch=document.body.clientHeight if(dh>ch){ moveme=dh-ch window.scrollTo(0,moveme) } } However, I am looking for a way to make it scroll only within a specific d ...

Creating a dynamic dropdown list with PHP and AJAX using JQuery

I was attempting to create a dynamic dependent select list using AJAX, but I am facing issues with getting the second list to populate. Below is the code I have been working with. The gethint.php file seems to be functioning properly. I'm not sure whe ...

When using jQuery, the value of an input type text field remains constant despite any alerts

My issue involves an input text used to check if the corrected values are being displayed in an alert. However, when I modify a value in the form and check if the updated value appears in the alert box, it still shows the old value. Below is the relevant ...

Dynamically delete a property from a JSON object

I am currently working on a task that involves removing properties from a JSON object. I need to create a system where I can specify an array of locations from which the fields should be redacted. The JSON request I am dealing with looks like this: { "nam ...