Solved

How do I get Comparison Operators working in JavaScript?

Posted on 2009-05-06
10
264 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
  • 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
 

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 250 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
jQuery Popover 4 372
How do I javascript force paste as plain text cross browser? 4 1,092
Can I align center a jquery mobile footer? 5 387
Passing a text to parent window 4 27
Cloud-based technologies and services will continue to grow in popularity in 2017 thanks to the simple, scalable and cost-effective solutions they deliver. Here are three areas where cloud adoption is poised to really take off.
In 2017, ransomware will become so virulent and widespread that if you aren’t a victim yourself, you will know someone who is.
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…
A company’s greatest vulnerability is their email. CEO fraud, ransomware and spear phishing attacks are the no1 threat to a company’s security. Cybercrime is responsible for the largest loss of money to companies today with losses projected to r…

932 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now