Printing a race track by linking sprites to a .txt file p5.play

Viewed 133

I am trying to make a game using p5js and p5.play. It is a top-down 2d racing game where the background is created by creating sprites and linking them to numbers from a .txt file called 'track.txt'. The txt file is below and below it is the code I have written.

0 = Grass
1 = Track
2 = Finish/Start line

0 0 0 0 0 0 0 0 0 
0 1 1 1 1 1 1 1 0
0 1 0 0 0 0 0 1 0
0 1 0 1 1 1 0 2 0
0 1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1 0
0 1 1 1 0 1 1 1 0
0 0 0 0 0 0 0 0 0

Code

let track = [];
let images = [];

function preload() {
    images[0] = loadImage("grass.png");
    images[1] = loadImage("track.png");
    images[2] = loadImage("finish.png");
}

function setup() {
    createCanvas(800, 800);
    background(210);
    loadStrings("track.txt", getTrack);
}

function getTrack(arr){
    for(let i = 0; i < arr.length; i++)
    {
      let line = arr[i].trim(); 
      let tempArr = line.split(" ");
      track.push(tempArr);
    }}

function getImage(col, row) {
    return images[track[col][row]];
 }

The code does not work and is only showing the background. My aim here is to print a race of sprites by reading from track.txt. Any suggestions or solutions??

1 Answers

Hopefully track.txt only contains:

0 0 0 0 0 0 0 0 0 
0 1 1 1 1 1 1 1 0
0 1 0 0 0 0 0 1 0
0 1 0 1 1 1 0 2 0
0 1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1 0
0 1 1 1 0 1 1 1 0
0 0 0 0 0 0 0 0 0

If so, you're only missing out one tiny detail:

let tempArr = line.split(" ");
track.push(tempArr);

tempArr will be an array of String objects so getImage() will fail when you try to retrieve images by a String instead of an integer (Number in JS).

A quick fix is to simply use int() which conveniently in p5.js can also take an array as an argument (and will convert each string (e.g. ["1","2","3"]) to a Number (e.g. [1, 2, 3]).

Like so:

let tempArr = line.split(" ");
track.push(int(tempArr));
Related