简体   繁体   中英

how to improve the performance o my js game

I have started learning javascript a couple of days ago and done the codeacadmey stuff and thought i will try make a simple game.

so i came up with the memory game where you have to find pairs of images.

it is all working and i got a score system in place but a few people have said the delay that happens once the cards have been chosen to allowing another chocie is hindering them and i cant figure out how to improve that performance.

here is a bit of code i think is causing the delay, is there any better way to produce the same result, sorry about before i am new to all this.

function check() {

    clearInterval(tid);

        if(people[secondchocie] === people[firstchocie]) {
            cntr++;

            (cntr === numOfMatches) {

                stop();

                score = checkScore(amountGoes); 


                $('#gameFinished').append('<p>Well done, you managed to complete the game your score is <span>' + score + '</span></p>');

                }
                turns = 0;
                return;


                } else {
                document.images[firstchocie + numOfImages].src = backcard;
                document.images[secondchocie + numOfImages].src = backcard;
                turns = 0;
                return;

                }

        }

I can't create comments, so I'll put this in an answer.

Although I agree with lukas.pukenis ...

Changing images can take some time if they aren't preloaded. To test this: Try to get them into the browser cache by adding them somewhere else in the page (ie with an IMG tag) before starting the game.

Then you'll be sure they are in the cache.

edit:

I recently used this:

var cache = [];
function preLoadImages(arrImg)
    {
    var args_len = arrImg.length;
    for (var i = args_len; i--;)
        {
        var cacheImage = document.createElement('img');
        cacheImage.src = arrImg[i];
        cache.push(cacheImage);
        }
    }
preLoadImages(['images/img1.png','images/img2.png','images/img3.png',]);

you can add all images needed to the javascript array.

If your a quick study :) you can do the following: If your page is generated by php you could let php read the entire images directory and write the filenames in the page as javascript code. Or you could create an ajax request wich returns all paths to the images and sends them to the preload function as a callback.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM