mercredi 5 octobre 2016

Retrieving value inside delayed JS function

Below I have a score counting function for a canvas game, which shows in the browser window as score. I want the user to click OK on the window alert that shows the instructions of the game before this score function starts counting.

I have the issue of when I have a collision, when displaying a lose alert, console shows that score is not defined. I am sure this is because score is nested inside function startGame.

Before I added setTimeout this worked.

It should be that the window alert is delayed for a short time for canvas fill, then when the user clicks OK in the alert, the counting then starts. The issue is that from my collision, the uncaught reference error cannot determine what score is.

Should there be another function just for returning score? How would I do this?

setTimeout(startGame, 5);
function startGame() {

if(!alert("Welcome to my game!\nUse the arrow keys or the onscreen buttons to play!\nAvoid the falling objects!")); {

var start = new Date().getTime(),
score = '0.1';

var interval = window.setInterval(function() {
  var time = new Date().getTime() - start;
  
  score = Math.floor((time / 100));
  
  if(score === 1001) { 
    window.clearInterval(interval); 
    if(!alert((score)-1 + "0 score! You win!\nPress 'OK' to play again")){ 
        window.location.reload();
    } 
  }

  document.getElementById('displayScore').innerHTML = score += "0.00";
},10);


}}

if (x < object.x-70 + 60 &&
   x + width > object.x-70 && 
   y < object.y-50 + 60 && 
   height + y > object.y-50) {

if(!alert("You reached a score of " + score + ", you lose!\nPress 'OK' to try again?")); {
window.location.reload();
}
ctx.fill();
}

Aucun commentaire:

Enregistrer un commentaire