?
Solved

How do I get Comparison Operators working in JavaScript?

Posted on 2009-05-06
10
Medium Priority
?
275 Views
Last Modified: 2012-06-21
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
Comment
Question by:dtolle
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 4
10 Comments
 
LVL 19

Expert Comment

by:LordOfPorts
ID: 24319604
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
 

Author Comment

by:dtolle
ID: 24319947
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
 
LVL 19

Expert Comment

by:LordOfPorts
ID: 24319968
...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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 

Author Comment

by:dtolle
ID: 24320151
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
 
LVL 19

Accepted Solution

by:
LordOfPorts earned 1000 total points
ID: 24320333
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
 

Author Comment

by:dtolle
ID: 24320576
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
 

Author Comment

by:dtolle
ID: 24320584
Nevermind, I just looked at your code and you did have that in there (the highscore = currentscore) part.

Thanks again!
0
 

Author Closing Comment

by:dtolle
ID: 31578734
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
 
LVL 19

Expert Comment

by:LordOfPorts
ID: 24320605
You are very welcome! Nice work with the game!
0
 

Author Comment

by:dtolle
ID: 24320681
Thanks!
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The well known Cerber ransomware continues to spread this summer through spear phishing email campaigns targeting enterprises. Learn how it easily bypasses traditional defenses - and what you can do to protect your data.
In today's business world, data is more important than ever for informing marketing campaigns. Accessing and using data, however, may not come naturally to some creative marketing professionals. Here are four tips for adapting to wield data for insi…
In this video we outline the Physical Segments view of NetCrunch network monitor. By following this brief how-to video, you will be able to learn how NetCrunch visualizes your network, how granular is the information collected, as well as where to f…
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…
Suggested Courses

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question