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.

HTML5 Canvas
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

applelivetechAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Shaun VermaakTechnical Specialist IVCommented:
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

0
hieloCommented:
>> 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

0
applelivetechAuthor Commented:
thanks but now it gives NAN???
0
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

hieloCommented:
>> Game.startTime = new Date();
You are missing "Game."
var elapsed = parseInt((new Date() - Game.startTime) / 1000);
0
applelivetechAuthor Commented:
great now I'm getting a 0 however its not counting??

Screen-Shot-2018-02-13-at-20.49.30.png
0
hieloCommented:
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

0
applelivetechAuthor Commented:
still just says 0 and not updating?? thanks for your help
0
hieloCommented:
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?
0
applelivetechAuthor Commented:
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??
0
hieloCommented:
>> 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

0
Snarf0001Commented:
The .requestAnimationFrame code is typical, just a method of normalizing different browser prefixes.

Problem is that you're resetting the start time on every loop of the animation.  First line in drawElapsedTime is resetting the starttime.
1) Move startTime and score into "Game" level variables as hielo suggested.
2) Set the Game.startTime once in the .start() function
3) Remove it from the .drawElapsedTime function
4) Use the proper Game. vs global vars in the function


Try this:
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,
    score = 0

};

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"

    //set the starttime ONCE here when the game begins
    Game.startTime = new Date();

    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();      //don't reset here, set once in the .start() function
    var 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 : " + 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() - Game.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

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
applelivetechAuthor Commented:
Works perfect now Thanks
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Game Programming

From novice to tech pro — start learning today.