Solved

How do I get Comparison Operators working in JavaScript?

Posted on 2009-05-06
10
261 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
Comment Utility
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
Comment Utility
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
Comment Utility
...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
Comment Utility
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
Comment Utility
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
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 

Author Comment

by:dtolle
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
You are very welcome! Nice work with the game!
0
 

Author Comment

by:dtolle
Comment Utility
Thanks!
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Suggested Solutions

Veeam Backup & Replication has added a new integration – Veeam Backup for Microsoft Office 365.  In this blog, we will discuss how you can benefit from Office 365 email backup with the Veeam’s new product and try to shed some light on the needs and …
A procedure for exporting installed hotfix details of remote computers using powershell
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

743 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

19 Experts available now in Live!

Get 1:1 Help Now