• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 287
  • Last Modified:

How do I get Comparison Operators working in JavaScript?

I am learning how to make small games and decided to start with JavaScript.  I'm working on the high score display.  I have the function do a IF statement that will compare the current score to the high score.  However if I use Logical operators (&& and ||) it works fine, but if I use < or > it just doesn't work.  Any help would be great!  Thanks!
function gameOver() {
    //end the game by clearing the timer and modifying the score label
    //If score is higher then high score, replaces the high score
    clearTimeout(timer);
    score.innerHTML += "     - Game Over";
    score.style.backgroundColor = 'rgb(128,0,0)';
    if (currentScore || hiScore && currentScore <= hiScore) {
         hiScore.innerHTML = 'High Score: ' + currentScore
    }
    
    hiScore.style.backgroundColor = 'rgb(128,0,0)';
}

Open in new window

0
dtolle
Asked:
dtolle
  • 6
  • 4
1 Solution
 
LordOfPortsCommented:
Try surrounding the variables with parseInt http://www.w3schools.com/jsref/jsref_parseInt.asp e.g.:

if (parseInt(currentScore) <= parseInt(hiScore)) {

Use parseFloat http://www.w3schools.com/jsref/jsref_parseFloat.asp if the numbers are floating point values and not integers.
0
 
dtolleAuthor Commented:
I have tried your suggestion, but It failed, I have plugged it in like you said so it looked like:

if (parseInt(currentScore) <= parseInt(hiScore)) {
         hiScore.innerHTML = 'High Score: ' + currentScore
    }

But the score does not display, In case it was a operator object error I also tried >=, <, an >.
0
 
LordOfPortsCommented:
...I just noticed hiScore is actually a reference to an element in your code. Is it a DIV since you use .innerHTML? Do you keep the score values separately in variables?

In the code snippet it is not quite clear what currentScore and hiScore contain, it seems at least hiScore could be a DIV element and currentScore might be a numeric value in which case try:

if (parseInt(currentScore) <= parseInt(hiScore.innerHTML)) {

Please post more code.
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
dtolleAuthor Commented:
Here is the full code for the HTM file and the JS file.  I hope it helps
Rebound.js file:
 
//get info, process data, update screen objects
//instance vars
var ball;
var paddle;
var score;
var hiScore;
 
//initial speeds
var dx = 6;
var dy = 6;
var currentScore = 0;
var timer;
 
//set initial conditions for ball and paddle
var paddleLeft = 228;
var ballLeft = 200;
var ballTop = 4;
 
function init() {
    //instantiate HTML object instance vars
    ball = document.getElementById('ball');
    paddle = document.getElementById('paddle');
    score = document.getElementById('score');
    hiScore = document.getElementById('hiScore');
    //resister key listener with document object
    document.onkeydown = keyListener;
    //start the game loop
    start();
}
 
function keyListener(e) {
    if (!e) {
        //for IE
        e = window.event;
    }
    if (e.keyCode == 37 && paddleLeft > 0) {
        //keycode 37 is left arrow
        paddleLeft -= 10;
        paddle.style.left = paddleLeft + 'px';
    }
    if (e.keyCode == 39 && paddleLeft < 436) {
        //keycode 39 is right arrow
        paddleLeft += 10;
        paddle.style.left = paddleLeft + "px";
    }
    // FYI - Keycode 38 is up arrow,
    //       Keycode 40 is down arrow
}
 
 
 
function start() {
    //game loop
    detectCollisions();
    render();
    difficulty();
 
    //end conditions
    if (ballTop < 470) {
        //still in play - keep the loop going
        timer = setTimeout('start()', 50);
    }
    else {
        gameOver();
    }
}
 
function detectCollisions() {
    //just reflect the ball on a collision
    //a more robust engine could change trajectory of
    //the ball based on where the ball hits the paddle
    if (collisionX())
        dx = dx * -1;
    if (collisionY())
        dy = dy * -1;
}
 
function collisionX() {
    //check left and right boundaries
    if (ballLeft < 4 || ballLeft > 480)
        return true;
    return false;
}
 
function collisionY() {
    //check if at top of playing area
    if(ballTop < 4)
    return true;
    //check to see if ball collided with paddle
    if(ballTop >450) {
        if(ballLeft > paddleLeft && ballLeft < paddleLeft + 64)
            return true;
        }
    return false;
}
 
function render() {
    moveBall();
    updateScore();
}
 
function moveBall() {
    ballLeft += dx;
    ballTop += dy;
    ball.style.left = ballLeft;
    ball.style.top = ballTop;
}
 
function updateScore() {
    currentScore += 10;
    score.innerHTML = 'Score: ' + currentScore;
}
 
function difficulty() {
    //as the game progresses, increase magnitude of the vertical speed
    if (currentScore % 1000 == 0) {
        if (dy > 0)
            dy += 1;
        else
            dy -= 1;
    }
}
 
function gameOver() {
    //end the game by clearing the timer and modifying the score label
    //If score is higher then high score, replaces the high score
    clearTimeout(timer);
    score.innerHTML += "     - Game Over";
    score.style.backgroundColor = 'rgb(128,0,0)';
    if (parseInt(currentScore) < parseInt(hiScore)) {
         hiScore.innerHTML = 'High Score: ' + currentScore
    }
    
    hiScore.style.backgroundColor = 'rgb(128,0,0)';
}
 
function resetg() {
    //Resets the game back to it's starting points but leaves the high score
    
    currentScore = 0;
    paddleLeft = 228;
    ballLeft = 200;
    ballTop = 4;
    start();
    score.style.backgroundColor = 'rgb(32,128,64)';
    hiScore.style.backgroundColor = 'rgb(32,128,64)';
 
}
 
------------------------------
Rebound.htm file:
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
 
<link rel="Stylesheet" type="text/css" href="Rebound.css" />
<script type="text/javascript" src="rebound.js"></script>
    <title>My First JavaScript Game - Rebound</title>
</head>
 
 
<body onload="init()">
    <h1>Rebound</h1>
    <div id="playingArea">
        <div id="paddle">
            <img src="img\paddle.gif" alt="" />
        </div>
        <div id="ball">
            <img src="img\ball.gif" alt="" />
        </div>
        <div id="score">
            Score: 0
        </div>
	<div id="hiScore">
	    High Score: 0
	</div>
	<div id="reset">
	<button class="button" type="button" onclick="resetg()">Reset Game</button>
	</div>
    </div>
 
    This is my first attempt at a javascript game. 
    
</body>
</html>

Open in new window

0
 
LordOfPortsCommented:
The problem was that hiScore referred to a DIV element of which the value had text in it so the solution was to add a separate variable named highScore in this case which will keep track of the numeric value for the high score, the update is just in the rebound.js which is below, try to see if now acts correctly:
//get info, process data, update screen objects
//instance vars
var ball;
var paddle;
var score;
var hiScore;
 
//initial speeds
var dx = 6;
var dy = 6;
var currentScore = 0;
var highScore = 0;
var timer;
 
//set initial conditions for ball and paddle
var paddleLeft = 228;
var ballLeft = 200;
var ballTop = 4;
 
function init() {
    //instantiate HTML object instance vars
    ball = document.getElementById('ball');
    paddle = document.getElementById('paddle');
    score = document.getElementById('score');
    hiScore = document.getElementById('hiScore');
    //resister key listener with document object
    document.onkeydown = keyListener;
    //start the game loop
    start();
}
 
function keyListener(e) {
    if (!e) {
        //for IE
        e = window.event;
    }
    if (e.keyCode == 37 && paddleLeft > 0) {
        //keycode 37 is left arrow
        paddleLeft -= 10;
        paddle.style.left = paddleLeft + 'px';
    }
    if (e.keyCode == 39 && paddleLeft < 436) {
        //keycode 39 is right arrow
        paddleLeft += 10;
        paddle.style.left = paddleLeft + "px";
    }
    // FYI - Keycode 38 is up arrow,
    //       Keycode 40 is down arrow
}
 
 
 
function start() {
    //game loop
    detectCollisions();
    render();
    difficulty();
 
    //end conditions
    if (ballTop < 470) {
        //still in play - keep the loop going
        timer = setTimeout('start()', 50);
    }
    else {
        gameOver();
    }
}
 
function detectCollisions() {
    //just reflect the ball on a collision
    //a more robust engine could change trajectory of
    //the ball based on where the ball hits the paddle
    if (collisionX())
        dx = dx * -1;
    if (collisionY())
        dy = dy * -1;
}
 
function collisionX() {
    //check left and right boundaries
    if (ballLeft < 4 || ballLeft > 480)
        return true;
    return false;
}
 
function collisionY() {
    //check if at top of playing area
    if(ballTop < 4)
    return true;
    //check to see if ball collided with paddle
    if(ballTop >450) {
        if(ballLeft > paddleLeft && ballLeft < paddleLeft + 64)
            return true;
        }
    return false;
}
 
function render() {
    moveBall();
    updateScore();
}
 
function moveBall() {
    ballLeft += dx;
    ballTop += dy;
    ball.style.left = ballLeft;
    ball.style.top = ballTop;
}
 
function updateScore() {
    currentScore += 10;
    score.innerHTML = 'Score: ' + currentScore;
}
 
function difficulty() {
    //as the game progresses, increase magnitude of the vertical speed
    if (currentScore % 1000 == 0) {
        if (dy > 0)
            dy += 1;
        else
            dy -= 1;
    }
}
 
function gameOver() {
    //end the game by clearing the timer and modifying the score label
    //If score is higher then high score, replaces the high score
    clearTimeout(timer);
    score.innerHTML += "     - Game Over";
    score.style.backgroundColor = 'rgb(128,0,0)';
    if (parseInt(currentScore) >= parseInt(highScore)) {
	highScore = currentScore;
        hiScore.innerHTML = 'High Score: ' + highScore;
    }
    
    hiScore.style.backgroundColor = 'rgb(128,0,0)';
}
 
function resetg() {
    //Resets the game back to it's starting points but leaves the high score
    
    currentScore = 0;
    paddleLeft = 228;
    ballLeft = 200;
    ballTop = 4;
    start();
    score.style.backgroundColor = 'rgb(32,128,64)';
    hiScore.style.backgroundColor = 'rgb(32,128,64)';
 
}

Open in new window

0
 
dtolleAuthor Commented:
SWEET, it worked, I just had to add one thing and now it works!  Thanks!


if (currentScore > highScore) {
    	 highScore = currentScore
         hiScore.innerHTML = 'High Score: ' + highScore
    }

Open in new window

0
 
dtolleAuthor Commented:
Nevermind, I just looked at your code and you did have that in there (the highscore = currentscore) part.

Thanks again!
0
 
dtolleAuthor Commented:
I have been struggling for 3 days with that issue, Thank you for helping me so I can proceed with the rest of my plans for the game.
0
 
LordOfPortsCommented:
You are very welcome! Nice work with the game!
0
 
dtolleAuthor Commented:
Thanks!
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

  • 6
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now