P5 - load data from a matrix

Viewed 185

I'm attempting to create a game with the p5.play.js library and I've run into some problems. I want the GUI of the game to comprise x amount of squares (sprites) on board, pulled from a text file sitting in an assets folder. They have to be sprites because I want to interact with them with mouse events and other sprites. The text file is currently an 8 x 8 matrix, but I want to use any sized matrix - from 8 x8 to 24 x 24.

I've used the splitTokens function to convert each line of 8 into 8 separate strings...so far, so good! However, the conditional logic that I have used isn't interpreting the 1, 2 and 3's contained in the text file into red, green and blue. I'm not sure whether I should convert the string to an integer - I've tried that, but it didn't work...funny that!

I've only been coding for 2 months, so I'm pushing the envelope of my limited knowledge!

My code thus far:

let fileContent;
let tiles;
let spr;

function preload(){
  fileContent = loadStrings('assets/game.txt'); 
}

function setup() {
  createCanvas(500, 500);

  gui = new Array(fileContent.length);

  for (let i = 0; i < gui.length; i++) {
    let tiles = splitTokens(fileContent[i]);     
    console.log(tiles);

    for (let j = 0; j < gui.length; j++) {
      for (let k = 0; k < gui.length; k++) {
        spr = createSprite(j * 50 + 75, k * 50 + 75, 50, 50);
        if (tiles[i] == "1") {
          spr.shapeColor = color('red');
        }
        if (tiles[i] == "2") {
          spr.shapeColor = color('green');
        }
        if (tiles[i] == "3") {
          spr.shapeColor = color('blue');
        }
      }    
    }
  }  
}

function draw() {
  background(0);
 
  drawSprites()
}

I'm not sure where to upload any external assets here, so the current text file is as follows:

1 2 3 2 1 3 1 2
2 3 1 1 2 1 3 1
2 3 1 2 2 1 3 1
1 3 1 1 2 1 3 1
2 3 1 1 2 1 3 1
1 2 1 1 2 2 3 1
2 3 2 3 2 1 3 1
2 1 2 2 2 1 3 1

As you can see from the code, it resides in an "assets" folder.

1 Answers

You are triply nesting here when not necessary on a 2d matrix. Rather than iterating 64 times, you are instead iterating 512 times (with the incorrect index as well on tiles[i], changing it to the nested iterators also "works"). However I suggest you remove the j loop and rename the outer i to j. I tried to recreate based on the info you gave here, with the change in mind.

Related