Solved

How do I get Comparison Operators working in JavaScript?

Posted on 2009-05-06
10
265 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
The Eight Noble Truths of Backup and Recovery

How can IT departments tackle the challenges of a Big Data world? This white paper provides a roadmap to success and helps companies ensure that all their data is safe and secure, no matter if it resides on-premise with physical or virtual machines or in the cloud.

 

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
 

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

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Add days to a date 3 211
HTML coding help 6 67
GridMvc Error mvc5 5 186
Popup message with Buttons in Java Script in C# programming 8 120
This article outlines the process to identify and resolve account lockout in an Active Directory environment.
Knowing where your website is hosted is as important as the features you receive, the monthly fee, and the support you receive. Due diligence should be done when choosing your next hosting provider.
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

803 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