0

I develop game with Phaser.js

Now I need to parse csv file, before game starts, and use Papa Parse for that. The csv file contains image url's for preload stage in Phaser.

I try to do it like that:

function preload() {
    Papa.parse("http://localhost:9000/bad_images.csv", {
        download: true,
        complete: function(results) {
            i = 1;
            results.data.forEach(function(entry){
                bad_images.append(entry);
                bad_names.append("b" + i++);
            })
        }
    });

    Papa.parse("http://localhost:9000/good_images.csv", {
        download: true,
        complete: function(results) {
            i = 1;
            results.data.forEach(function(entry){
                good_images.append(entry);
                good_names.append("b" + i++);
            })
        }
    });

    for (var i = 0; i < good_images.length; ++i) {
        game.load.image(good_names[i], good_images[i]);
    }

    for (var i = 0; i < bad_images.length; ++i) {
        game.load.image(bad_names[i], bad_images[i]);
    }
}

But in that case function preload ends before papa parse csv, cause it asynchronous. How to make all functions execute in sequence, not asynchronous?

StopKran
  • 395
  • 5
  • 22

1 Answers1

2

Why need to be synchronous ?

try this :

function loadCSV(){
    Papa.parse("http://localhost:9000/bad_images.csv", {
        download: true,
        complete: function(results) {
            i = 1;
            results.data.forEach(function(entry){
                bad_images.append(entry);
                bad_names.append("b" + i++);
            });

            Papa.parse("http://localhost:9000/good_images.csv", {
                download: true,
                complete: function(results) {
                    i = 1;

                    results.data.forEach(function(entry){
                        good_images.append(entry);
                        good_names.append("b" + i++);
                    });

                    startGame(); // Start the game when the load is finished

                }
            });
         }
    });
}

function startGame(){ .... }


function preload() {
    for (var i = 0; i < good_images.length; ++i) {
        game.load.image(good_names[i], good_images[i]);
    }

    for (var i = 0; i < bad_images.length; ++i) {
        game.load.image(bad_names[i], bad_images[i]);
    }          
}
Hacketo
  • 4,978
  • 4
  • 19
  • 34
  • It need to be synchronous, becouse in phaser.js, game starts after preload function. If imeges doesn't loaded, it is actually not good for game. – StopKran Jan 05 '15 at 13:46
  • so you have to parse the csv before the preload function, then start your game and load all the images in the preload – Hacketo Jan 05 '15 at 13:48
  • 1
    @StopKran A synchronous download will lock up your browser page. Frankly, modern browsers don't allow synchronous XMLHttpRequest because of that. The only way to do it is asynchronously. – Matt Jan 05 '15 at 14:39