Link to home
Start Free TrialLog in
Avatar of applelivetech
applelivetech

asked on

HTML5 Canvas Game (Issue outputting the current game time with Javascript )

Hi I am trying to get my games to output the current time in seconds that the game is running for as a score for the player in the canvas but I keep getting an undefined var instead of the number?

Does anyone have any idea whats wrong with my code??


Thanks, See code below.

User generated image
JS
var Game = {
    canvas : undefined,
    ctx : undefined,
    backgroundImage : undefined,
    backgroundMusic :undefined,
    soundImage: undefined,
    soundImagePosition : { x : 750, y : 10 },
    vy : 0,
    rocket : undefined,
    rocketPosition : { x : 350, y : 400 },
    dxSpeed: 7,
	dySpeed: 3,
	keyboard : { keyDown : -1 },
	keys : {
    A: 65,     B: 66,      C: 67,      D: 68,       E: 69,      F: 70,
    G: 71,     H: 72,      I: 73,      J: 74,       K: 75,      L: 76,
    M: 77,     N: 78,      O: 79,      P: 80,       Q: 81,      R: 82,
    S: 83,     T: 84,      U: 85,      V: 86,       W: 87,      X: 88,
    Y: 89,     Z: 90, 	   LA:37,      UA:38, 	    RA:39,      DA:40,
 }
};

function handleKeyDown(evt) {
    Game.keyboard.keyDown = evt.keyCode;
}

function handleKeyUp(evt) {
    Game.keyboard.keyDown = -1;
}

Game.start = function () {
    
    document.onkeydown = handleKeyDown;
    document.onkeyup = handleKeyUp;

    Game.canvas = document.getElementById("myCanvas");
    Game.ctx = Game.canvas.getContext("2d");
  

    Game.backgroundMusic = new Audio();
    Game.backgroundMusic.src = "assets/audio/start.mp3";
    Game.backgroundMusic.volume = 0.4; // goes between 0.0-1
    Game.backgroundMusic.play();
    // Playing the background music continuously
    Game.backgroundMusic.addEventListener("ended", Game.backgroundMusic.play, false);


    Game.backgroundImage = new Image();
    Game.backgroundImage.src = 'assets/images/bg_star.png';


    Game.soundImage = new Image();
    Game.soundImage.src = "assets/images/soundon.png";
  


    Game.rocket = new Image();
    Game.rocket.src = "assets/images/rocket_small.png"
    Game.mainLoop();
    
};


document.addEventListener( 'DOMContentLoaded', Game.start);




Game.mainLoop = function() {
 
    Game.clearCanvas();
    Game.update();
    Game.draw();
    requestAnimationFrame(Game.mainLoop);
 
};


Game.clearCanvas = function () {
    Game.ctx.clearRect(0, 0, Game.canvas.width, Game.canvas.height);
};


Game.update = function () {

    //-------Calling Move backgound image function------------

    Game.moveBackground();

    //-------Calling Move rocket function------------
    Game.movePlayer();

    //-------Calling volume control function------------
    Game.volumeControl();

}


Game.draw = function() {

    Game.ctx.drawImage(Game.backgroundImage, 0, Game.vy);
    Game.ctx.drawImage(Game.backgroundImage,0, - Game.backgroundImage.height + Game.vy);
    Game.ctx.drawImage(Game.soundImage, Game.soundImagePosition.x, Game.soundImagePosition.y);
    Game.ctx.drawImage(Game.rocket, Game.rocketPosition.x, Game.rocketPosition.y, 110,75);
    // draw the current score
    Game.drawElapsedTime();
    // draw the Final score
};

    
Game.moveBackground  = function(){
    Game.vy += 7;
	if (Game.vy > Game.canvas.height) {
		Game.vy = 0;
	}
}




// Function to move rocket with arrow keys
Game.movePlayer = function(){
	
    switch(Game.keyboard.keyDown)
{
    case Game.keys.LA:
            if ( Game.rocketPosition.x - Game.dxSpeed > -1)
                {
                    Game.rocketPosition.x -= Game.dxSpeed;
                }   
    break;	

    case Game.keys.RA :
          if (Game.rocketPosition.x + Game.dxSpeed < (Game.canvas.width-Game.rocket.width))
            {
                    Game.rocketPosition.x += Game.dxSpeed;
            }
    break;
    
    case Game.keys.UA :
            if (Game.rocketPosition.y - Game.dySpeed > -1)
            {
                    Game.rocketPosition.y -= Game.dySpeed;
            }
    break;
    
    
    
    case Game.keys.DA :
         if (Game.rocketPosition.y + Game.dySpeed < Game.canvas.height-Game.rocket.height)
            {
                    Game.rocketPosition.y += Game.dySpeed;
            }
     break;
    
}

}

// function to toggle volume  press S for pause volume and P to play sound.
// for volume up and down use U & D keys
Game.volumeControl = function(){
	
	switch(Game.keyboard.keyDown)
	{
		case Game.keys.P :
			Game.backgroundMusic.play();
			Game.soundImage.src = "assets/images/soundon.png";
			
		break;
		
		case Game.keys.S :
			Game.backgroundMusic.pause();
			Game.soundImage.src = "assets/images/soundoff.png";
		
		break;
		
		case Game.keys.U :
            if(Game.backgroundMusic.volume<=0.9){
                Game.backgroundMusic.volume +=0.1;
            }
            if(Game.backgroundMusic.volume >= 0.1){
                Game.soundImage.src = "assets/images/soundon.png";
            }
		break;
		
		case Game.keys.D :
            if(Game.backgroundMusic.volume>=0.1){
                Game.backgroundMusic.volume -=0.1;
            } 
            if(Game.backgroundMusic.volume<=0.1){
                Game.soundImage.src = "assets/images/soundoff.png";
            }
		break;
	
	
	}
}


window.requestAnimationFrame = function() {
	return window.requestAnimationFrame ||
		window.webkitRequestAnimationFrame ||
		window.mozRequestAnimationFrame ||
		window.msRequestAnimationFrame ||
		window.oRequestAnimationFrame ||
		function(f) {
			window.setTimeout(f,1e3/60);
		}
}();

  /* SCORE */
    var startTime;
    // ending elapsed time in seconds
    var score;

        Game.drawElapsedTime = function () {
        Game.startTime = new Date();
        var elapsed = parseInt((new Date() - startTime) / 1000);
        Game.ctx.save();
        Game.ctx.beginPath();
        Game.ctx.fillStyle = "#fff";
        Game.ctx.font = "20px Verdana"
        // draw the running time at half opacity
        Game.ctx.globalAlpha = 0.50;
        Game.ctx.fillText(" Score : "+Game.elapsed, Game.canvas.width - 800, 30);
        Game.ctx.restore();
    }

    Game.drawFinalScore = function () {
        // set the final score just once
        if (Game.score == null) {
            Game.score = Game.parseInt((new Date() - startTime) / 1000);
        }
        Game.ctx.save();
        Game.ctx.beginPath();
        Game.ctx.fillStyle = "red";
        Game.ctx.font = "30px Verdana"
        Game.ctx.fillText("Game Over: " + score + " secs", 50, 35);
        Game.ctx.restore();
    }
    
    

Open in new window

Avatar of Shaun Vermaak
Shaun Vermaak
Flag of Australia image

Don't see you assigning startTime. Guess line 233 should be
Game.score = Game.parseInt((new Date() - Date.parse(startTime)) / 1000);

Open in new window

-or-
Game.score = Game.parseInt((new Date() - Date.parse(Game.startTime)) / 1000);

Open in new window

>> var elapsed = parseInt((new Date() - startTime) / 1000);
>> Game.ctx.fillText(" Score : "+Game.elapsed, Game.canvas.width - 800, 30);
elapsed is not a property of game.  Try:
Game.ctx.fillText(" Score : "+ elapsed, Game.canvas.width - 800, 30);

Open in new window

Avatar of applelivetech
applelivetech

ASKER

thanks but now it gives NAN???
>> Game.startTime = new Date();
You are missing "Game."
var elapsed = parseInt((new Date() - Game.startTime) / 1000);
great now I'm getting a 0 however its not counting??

User generated image
copy and paste the following:
var Game = {
    canvas : undefined,
    ctx : undefined,
    backgroundImage : undefined,
    backgroundMusic :undefined,
    soundImage: undefined,
    soundImagePosition : { x : 750, y : 10 },
    vy : 0,
    rocket : undefined,
    rocketPosition : { x : 350, y : 400 },
    dxSpeed: 7,
	dySpeed: 3,
	keyboard : { keyDown : -1 },
	keys : {
    A: 65,     B: 66,      C: 67,      D: 68,       E: 69,      F: 70,
    G: 71,     H: 72,      I: 73,      J: 74,       K: 75,      L: 76,
    M: 77,     N: 78,      O: 79,      P: 80,       Q: 81,      R: 82,
    S: 83,     T: 84,      U: 85,      V: 86,       W: 87,      X: 88,
    Y: 89,     Z: 90, 	   LA:37,      UA:38, 	    RA:39,      DA:40,
 },
 startTime:0,
 timeElapsed:0,
 score:null
};

function handleKeyDown(evt) {
    Game.keyboard.keyDown = evt.keyCode;
}

function handleKeyUp(evt) {
    Game.keyboard.keyDown = -1;
}

Game.start = function () {
    
    document.onkeydown = handleKeyDown;
    document.onkeyup = handleKeyUp;

    Game.canvas = document.getElementById("myCanvas");
    Game.ctx = Game.canvas.getContext("2d");
  

    Game.backgroundMusic = new Audio();
    Game.backgroundMusic.src = "assets/audio/start.mp3";
    Game.backgroundMusic.volume = 0.4; // goes between 0.0-1
    Game.backgroundMusic.play();
    // Playing the background music continuously
    Game.backgroundMusic.addEventListener("ended", Game.backgroundMusic.play, false);


    Game.backgroundImage = new Image();
    Game.backgroundImage.src = 'assets/images/bg_star.png';


    Game.soundImage = new Image();
    Game.soundImage.src = "assets/images/soundon.png";
  


    Game.rocket = new Image();
    Game.rocket.src = "assets/images/rocket_small.png"
	Game.score=null;
    Game.mainLoop();
    
};


document.addEventListener( 'DOMContentLoaded', Game.start);




Game.mainLoop = function() {
 
    Game.clearCanvas();
    Game.update();
    Game.draw();
    requestAnimationFrame(Game.mainLoop);
 
};


Game.clearCanvas = function () {
    Game.ctx.clearRect(0, 0, Game.canvas.width, Game.canvas.height);
};


Game.update = function () {

    //-------Calling Move backgound image function------------

    Game.moveBackground();

    //-------Calling Move rocket function------------
    Game.movePlayer();

    //-------Calling volume control function------------
    Game.volumeControl();

}


Game.draw = function() {

    Game.ctx.drawImage(Game.backgroundImage, 0, Game.vy);
    Game.ctx.drawImage(Game.backgroundImage,0, - Game.backgroundImage.height + Game.vy);
    Game.ctx.drawImage(Game.soundImage, Game.soundImagePosition.x, Game.soundImagePosition.y);
    Game.ctx.drawImage(Game.rocket, Game.rocketPosition.x, Game.rocketPosition.y, 110,75);
    // draw the current score
    Game.drawElapsedTime();
    // draw the Final score
};

    
Game.moveBackground  = function(){
    Game.vy += 7;
	if (Game.vy > Game.canvas.height) {
		Game.vy = 0;
	}
}




// Function to move rocket with arrow keys
Game.movePlayer = function(){
	
    switch(Game.keyboard.keyDown)
{
    case Game.keys.LA:
            if ( Game.rocketPosition.x - Game.dxSpeed > -1)
                {
                    Game.rocketPosition.x -= Game.dxSpeed;
                }   
    break;	

    case Game.keys.RA :
          if (Game.rocketPosition.x + Game.dxSpeed < (Game.canvas.width-Game.rocket.width))
            {
                    Game.rocketPosition.x += Game.dxSpeed;
            }
    break;
    
    case Game.keys.UA :
            if (Game.rocketPosition.y - Game.dySpeed > -1)
            {
                    Game.rocketPosition.y -= Game.dySpeed;
            }
    break;
    
    
    
    case Game.keys.DA :
         if (Game.rocketPosition.y + Game.dySpeed < Game.canvas.height-Game.rocket.height)
            {
                    Game.rocketPosition.y += Game.dySpeed;
            }
     break;
    
}

}

// function to toggle volume  press S for pause volume and P to play sound.
// for volume up and down use U & D keys
Game.volumeControl = function(){
	
	switch(Game.keyboard.keyDown)
	{
		case Game.keys.P :
			Game.backgroundMusic.play();
			Game.soundImage.src = "assets/images/soundon.png";
			
		break;
		
		case Game.keys.S :
			Game.backgroundMusic.pause();
			Game.soundImage.src = "assets/images/soundoff.png";
		
		break;
		
		case Game.keys.U :
            if(Game.backgroundMusic.volume<=0.9){
                Game.backgroundMusic.volume +=0.1;
            }
            if(Game.backgroundMusic.volume >= 0.1){
                Game.soundImage.src = "assets/images/soundon.png";
            }
		break;
		
		case Game.keys.D :
            if(Game.backgroundMusic.volume>=0.1){
                Game.backgroundMusic.volume -=0.1;
            } 
            if(Game.backgroundMusic.volume<=0.1){
                Game.soundImage.src = "assets/images/soundoff.png";
            }
		break;
	
	
	}
}


window.requestAnimationFrame = function() {
	return window.requestAnimationFrame ||
		window.webkitRequestAnimationFrame ||
		window.mozRequestAnimationFrame ||
		window.msRequestAnimationFrame ||
		window.oRequestAnimationFrame ||
		function(f) {
			window.setTimeout(f,1e3/60);
		}
}();



        Game.drawElapsedTime = function () {
        Game.startTime = new Date();
        Game.elapsed = parseInt((new Date() - Game.startTime) / 1000);
        Game.ctx.save();
        Game.ctx.beginPath();
        Game.ctx.fillStyle = "#fff";
        Game.ctx.font = "20px Verdana"
        // draw the running time at half opacity
        Game.ctx.globalAlpha = 0.50;
        Game.ctx.fillText(" Score : "+Game.elapsed, Game.canvas.width - 800, 30);
        Game.ctx.restore();
    }

    Game.drawFinalScore = function () {
        // set the final score just once
        if (Game.score == null) {
            Game.score = parseInt((new Date() - Game.startTime) / 1000);
        }
        Game.ctx.save();
        Game.ctx.beginPath();
        Game.ctx.fillStyle = "red";
        Game.ctx.font = "30px Verdana"
        Game.ctx.fillText("Game Over: " + Game.score + " secs", 50, 35);
        Game.ctx.restore();
    }
    
    
    

Open in new window

still just says 0 and not updating?? thanks for your help
On my previous post, line 22 should be simply elapsed, not elapsedTime, but if you did a copy-paste of my previous code, it should have still worked.  The only way I can see this still displaying 0 is if it runs in automated mode and the whole game takes less than a second.

Do you get any errors in the  console? Do you have a demo url?
hmm strange still dont work, I dont have any errors a and I am working on it locally unfortunately.  how would I tell if its in auto mode??
>> how would I tell if its in auto mode??
What I meant was that if you "run/launch" the game and it "plays by itself" (meaning that you are not interacting with it) until completion.

The only other scenario that makes sense is if the requestAnimationFrame is not being invoked.  The following does not look right to me:

window.requestAnimationFrame = function() {      
      return window.requestAnimationFrame || ...
}

Copy/Paste the following and give it a try:
var Game = {
    canvas : undefined,
    ctx : undefined,
    backgroundImage : undefined,
    backgroundMusic :undefined,
    soundImage: undefined,
    soundImagePosition : { x : 750, y : 10 },
    vy : 0,
    rocket : undefined,
    rocketPosition : { x : 350, y : 400 },
    dxSpeed: 7,
	dySpeed: 3,
	keyboard : { keyDown : -1 },
	keys : {
    A: 65,     B: 66,      C: 67,      D: 68,       E: 69,      F: 70,
    G: 71,     H: 72,      I: 73,      J: 74,       K: 75,      L: 76,
    M: 77,     N: 78,      O: 79,      P: 80,       Q: 81,      R: 82,
    S: 83,     T: 84,      U: 85,      V: 86,       W: 87,      X: 88,
    Y: 89,     Z: 90, 	   LA:37,      UA:38, 	    RA:39,      DA:40,
 },
 startTime:0,
 elapsed:0,
 score:null
};

function handleKeyDown(evt) {
    Game.keyboard.keyDown = evt.keyCode;
}

function handleKeyUp(evt) {
    Game.keyboard.keyDown = -1;
}

Game.start = function () {
    
    document.onkeydown = handleKeyDown;
    document.onkeyup = handleKeyUp;

    Game.canvas = document.getElementById("myCanvas");
    Game.ctx = Game.canvas.getContext("2d");
  

    Game.backgroundMusic = new Audio();
    Game.backgroundMusic.src = "assets/audio/start.mp3";
    Game.backgroundMusic.volume = 0.4; // goes between 0.0-1
    Game.backgroundMusic.play();
    // Playing the background music continuously
    Game.backgroundMusic.addEventListener("ended", Game.backgroundMusic.play, false);


    Game.backgroundImage = new Image();
    Game.backgroundImage.src = 'assets/images/bg_star.png';


    Game.soundImage = new Image();
    Game.soundImage.src = "assets/images/soundon.png";
  


    Game.rocket = new Image();
    Game.rocket.src = "assets/images/rocket_small.png"
	Game.score=null;
    Game.mainLoop();
    
};


document.addEventListener( 'DOMContentLoaded', Game.start);




Game.mainLoop = function() {
 
    Game.clearCanvas();
    Game.update();
    Game.draw();
    requestAnimFrame(Game.mainLoop);
 
};


Game.clearCanvas = function () {
    Game.ctx.clearRect(0, 0, Game.canvas.width, Game.canvas.height);
};


Game.update = function () {

    //-------Calling Move backgound image function------------

    Game.moveBackground();

    //-------Calling Move rocket function------------
    Game.movePlayer();

    //-------Calling volume control function------------
    Game.volumeControl();

}


Game.draw = function() {

    Game.ctx.drawImage(Game.backgroundImage, 0, Game.vy);
    Game.ctx.drawImage(Game.backgroundImage,0, - Game.backgroundImage.height + Game.vy);
    Game.ctx.drawImage(Game.soundImage, Game.soundImagePosition.x, Game.soundImagePosition.y);
    Game.ctx.drawImage(Game.rocket, Game.rocketPosition.x, Game.rocketPosition.y, 110,75);
    // draw the current score
    Game.drawElapsedTime();
    // draw the Final score
};

    
Game.moveBackground  = function(){
    Game.vy += 7;
	if (Game.vy > Game.canvas.height) {
		Game.vy = 0;
	}
}




// Function to move rocket with arrow keys
Game.movePlayer = function(){
	
    switch(Game.keyboard.keyDown)
{
    case Game.keys.LA:
            if ( Game.rocketPosition.x - Game.dxSpeed > -1)
                {
                    Game.rocketPosition.x -= Game.dxSpeed;
                }   
    break;	

    case Game.keys.RA :
          if (Game.rocketPosition.x + Game.dxSpeed < (Game.canvas.width-Game.rocket.width))
            {
                    Game.rocketPosition.x += Game.dxSpeed;
            }
    break;
    
    case Game.keys.UA :
            if (Game.rocketPosition.y - Game.dySpeed > -1)
            {
                    Game.rocketPosition.y -= Game.dySpeed;
            }
    break;
    
    
    
    case Game.keys.DA :
         if (Game.rocketPosition.y + Game.dySpeed < Game.canvas.height-Game.rocket.height)
            {
                    Game.rocketPosition.y += Game.dySpeed;
            }
     break;
    
}

}

// function to toggle volume  press S for pause volume and P to play sound.
// for volume up and down use U & D keys
Game.volumeControl = function(){
	
	switch(Game.keyboard.keyDown)
	{
		case Game.keys.P :
			Game.backgroundMusic.play();
			Game.soundImage.src = "assets/images/soundon.png";
			
		break;
		
		case Game.keys.S :
			Game.backgroundMusic.pause();
			Game.soundImage.src = "assets/images/soundoff.png";
		
		break;
		
		case Game.keys.U :
            if(Game.backgroundMusic.volume<=0.9){
                Game.backgroundMusic.volume +=0.1;
            }
            if(Game.backgroundMusic.volume >= 0.1){
                Game.soundImage.src = "assets/images/soundon.png";
            }
		break;
		
		case Game.keys.D :
            if(Game.backgroundMusic.volume>=0.1){
                Game.backgroundMusic.volume -=0.1;
            } 
            if(Game.backgroundMusic.volume<=0.1){
                Game.soundImage.src = "assets/images/soundoff.png";
            }
		break;
	
	
	}
}


window.requestAnimFrame = function() {
	
	return window.requestAnimationFrame ||
		window.webkitRequestAnimationFrame ||
		window.mozRequestAnimationFrame ||
		window.msRequestAnimationFrame ||
		window.oRequestAnimationFrame ||
		function(f) {
			window.setTimeout(f,1000/60);
		}
}();



        Game.drawElapsedTime = function () {
        Game.startTime = new Date();
        Game.elapsed = parseInt((new Date() - Game.startTime) / 1000);
        Game.ctx.save();
        Game.ctx.beginPath();
        Game.ctx.fillStyle = "#fff";
        Game.ctx.font = "20px Verdana"
        // draw the running time at half opacity
        Game.ctx.globalAlpha = 0.50;
        Game.ctx.fillText(" Score : "+Game.elapsed, Game.canvas.width - 800, 30);
        Game.ctx.restore();
    }

    Game.drawFinalScore = function () {
        // set the final score just once
        if (Game.score == null) {
            Game.score = parseInt((new Date() - Game.startTime) / 1000);
        }
        Game.ctx.save();
        Game.ctx.beginPath();
        Game.ctx.fillStyle = "red";
        Game.ctx.font = "30px Verdana"
        Game.ctx.fillText("Game Over: " + Game.score + " secs", 50, 35);
        Game.ctx.restore();
    }
    

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Snarf0001
Snarf0001
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Works perfect now Thanks