What is causing the crash in p5.js when I use this function to add objects to an array?

I'm currently working on an evolution simulation app that involves reproducing organisms with a health level above 75%. After reproduction, their health is reduced by half. However, I'm encountering an issue where my app crashes in p5.js for reasons unknown to me.

To troubleshoot this problem, I have attempted to reduce the number of organisms to just 3 and encapsulate the process within a function of the organism's class.


var organisms = []; // array to store organism instances

function reproduce(){
  for (let i = 0; i < organisms.length; i++){
     if(organisms[i].life > 0.75){
        // create genetically similar size
        let size = organisms[i].size + (random() > 0.5 ? 1 : -1 * random() * 2);   
        // declare instance
        let org = new Organism(width, height, size)
        organisms.push(org);
        // prevent infinite reproduction
        organisms[i].life -= 0.5;
        }
    }
}

My expectation was for this code to simply generate new instances of the class, but unfortunately, p5.js still crashes.

Answer №1

Loop through the array and generate new organisms. Then, after completing the loop, add the newly created organisms to your initial array.

Below is a sample code snippet that demonstrates this process. The original random method call has been replaced with Math.random(), and variables width and height have been defined to avoid using p5.js.

    var organisms = []; // array to store organism instances
    var width = 100;
var height = 100;

function Organism(w, h, s){
this.width = w;
this.height = h;
this.size = s;
this.life = .76;
}
organisms.push(new Organism(1,1,1));
    console.log("Organisms length before reproduction: " + organisms.length);
reproduce();
    console.log("Organisms length after reproduction: "+organisms.length);

    function reproduce(){
      var organismsToAdd = [];
      for (let i = 0; i < organisms.length; i++){
         if(organisms[i].life > 0.75){
            // creating genetically similar size
            let size = organisms[i].size + (Math.random() > 0.5 ? 1 : -1 * Math.random() * 2);   
            // creating instance
            let org = new Organism(width, height, size)
            organismsToAdd.push(org);
            // preventing unlimited reproduction
            organisms[i].life -= 0.5;
            }
        }
      // adding new organisms to original array
  organisms.push.apply(organisms, organismsToAdd)
    }

Here is an example with p5.js implementation:

      var organisms = []; // array where organisms instances go

function setup(){
  createCanvas(100,100);
  organisms.push(new Organism(1,1,1));
  noLoop();
  }
  
  function draw(){
   console.log("Organisms length before reproduction: " + organisms.length);
  reproduce();
    console.log("Organisms length after reproduction: " + organisms.length);
  }
    function reproduce(){
      var organismsToAdd = [];
      for (let i = 0; i < organisms.length; i++){
         if(organisms[i].life > 0.75){
            // creating genetically similar size
            let size = organisms[i].size + (random() > 0.5 ? 1 : -1 * random() * 2);   
            // creating instance
            let org = new Organism(width, height, size)
            organismsToAdd.push(org);
            // preventing unlimited reproduction
            organisms[i].life -= 0.5;
            }
        }
  // adding new organisms to original array
  organisms.push.apply(organisms, organismsToAdd)
    }
  
function Organism(w, h, s){
  this.width = w;
  this.height = h;
  this.size = s;
  this.life = .76;
}

  
  
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.min.js"></script>

Answer №2

You've set up a loop that could potentially go on forever.

for (let i = 0; i < organisms.length; i++){

Let's say, hypothetically, your array organisms initially has 5 elements. If the if condition in the next line adds another element to the array during the first iteration, then each subsequent iteration will modify the next element. However, because your array is growing by one with each loop, you'll never reach the end of it!

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

Is there a way to implement full-page scrolling in Vue?

Looking for a Vue equivalent of the fullpage.js library. Need a component that allows scrolling through elements similar to fullpage.js. ...

Error: Trying to set a value to an undefined object in the bind() method

I am currently working on implementing a listener for my video player in order to update the input range on some custom controls. However, I have encountered an issue with an error message that states Uncaught ReferenceError: Invalid left-hand side in as ...

Save data in a function

I have a functionality in place that processes data received from a server through websocket. Depending on the specific page being accessed, the data is handled differently. sock.onmessage = function (e) { log(e.data); } function returnCurrentPage(m) ...

"Is there a way to initiate a Date Picker with the current date using Javascript in an AngularJS application

I am having an issue with my date picker where the month starts from the current month and goes up to the next 12 months. However, I only want to display dates from the current date to the last date of the current month. I believe I need to set a limit so ...

Ways to conceal the current state changes from being displayed in the URL

I've implemented a React form with text fields and radio buttons to store data in the state. The 'Proceed' button triggers an onClick function: handleClick(event){ console.log(this.state); var userID = 1; firebase.database().ref ...

What is the best way to store JSON data in a MySQL database?

I am facing a challenge with a JavaScript rich page that is sending a large JSON formatted data to PHP for insertion into a MySQL database. The JSON contains user input strings, some of which may include basic HTML tags like <a> and <strong>. ...

Sharing and displaying images on Sails JS platform

Using Sails JS, I am attempting to upload an image and display it in a view. Queries: The uploaded image is located in .tmp/uploads, how can I retrieve it from a view? Is there a method to access the uploaded image? The image's name is altered in ...

In Protractor, mastering the technique to extract multiple values simultaneously is crucial for efficiently handling applications that receive a large amount of push notifications

I am currently developing an automation test using Protractor for an application that receives a large volume of push notifications. The issue I am facing is testing a simple logic. expect(A + B).toEqual(C); The problem arises because A, B, and C are sou ...

I am experiencing issues with my three.js script not functioning properly within the context of a

I have been working on implementing a raycaster function in my project that only activates when an entity is visible. To achieve this, I was advised to create a custom script for better control. I have set up all entities and their child entities to be in ...

Exploring the Differences between Slim Framework's Currying and Dependency Injection

Frameworks like Angular allow for injecting services and controllers into each other, as shown in the code snippet below: App.controller('exampleController', function($scope, ajaxService){ ajaxService.getData().then(function(data) { ...

Capture the content from a paragraph element and save it into a variable

Is there a way in VueJS to extract the text from a p tag and save it into a variable? Currently, the text is just displayed inside the p tag, but I want to store it in a variable for future use. Here is the HTML code I am working with: <b-form-input ...

Covering a doughnut shape with a twisting spiral

I want to achieve a hula hoop covered in tape effect using three.js. The 3D model should look similar to the image below. https://i.sstatic.net/lj9cR.jpg I have been able to create the hoop in 3D space using TorusGeometry and pan around, but I am strugg ...

Is there a way to enable horizontal scrolling for a div table within an iframe element?

Looking for a solution to scroll a table horizontally to specific locations by clicking anchor tags outside of its frame? I initially used inline js which worked with the old table, but after updating to CSS, it stopped working. Seeking assistance from exp ...

What is the most efficient method for storing text in my web application?

Hey there, I'm looking for a way to easily store and access the wording used in my application so that I can use them again whenever needed. For example, loading messages, validation messages, or informational messages are some of the wordings I want ...

What is the best way to retrieve a comprehensive outcome from a sql search utilizing php and consequently showcase it using javascript?

Need help with my PHP script that executes a query and returns multiple rows? Learn how to use json_encode in conjunction with JavaScript to fetch this data and display it in a table. This code snippet echoes two JSON encoded lines, each representing one ...

Instructions on how to properly align a Youtube video using the react-youtube package

I'm currently encountering an issue with my YouTube video display. I have managed to make it responsive, but it is stuck on the left side of the screen and I am unsure how to center it properly. I tried adjusting the padding, but it didn't work a ...

What is the best way to remove text using javascript?

Hey everyone! I am new to coding in javascript and I'm hoping for some help with stripping text. I have a string that is formatted like this: <iframe src="http://embed.videokoo.com/61YVek?client_file_id=390856&width=720&height=480" style=" ...

I'm struggling to retrieve $wpdb data after using a PHP function to load my posts with AJAX

Hey there! I'm trying to create a cool feature where users can view post archives grouped by year. When they click on a specific year, all the posts from that year should be displayed. I've set up an AJAX call to my functions.php file, which con ...

Establish a specific character limit for input text

Is there a method to restrict the input length of a textbox to exactly 9 characters? I am looking for a solution and any assistance would be greatly valued. Thank you in advance! ...

Ways to incorporate an SVG file into an HTML canvas element while adjusting its dimensions on the fly

I'm struggling with implementing an SVG into my web-based game. I am attempting to draw the SVG, which has been encoded into a data URL, onto a canvas that should match the dimensions of the document window even when the window is resized. (functio ...