Click to See Complete Forum and Search --> : simple math problem


ck_net_2004
09-30-2004, 03:48 AM
Ive created a function for my JS game that displays your score.
But when updating the score it doesn't add the numbers together
it just adds the 2nd number to the end of the first one.

when starting the game:
kscore('','start');
when shooting enemy(1 for head shot,2 for chest,3 for legs):
kscore('1','update');
when gameover:
kscore('','reset');
This is the function:

var k_score="0"

function kscore(area,action){
if(action=='reset'){
k_score="0"
document.getElementById('score').style.display='none'; }
if(action=='start'){
k_score="0"
document.getElementById('score').innerHTML=k_score;
document.getElementById('score').style.fontSize='12';
document.getElementById('score').style.display=''; }
if(action=='update'){
if(area==1){ k_score = k_score + 100 }
if(area==2){ k_score = k_score + 75 }
if(area==3){ k_score = k_score + 50 }
document.getElementById('score').innerHTML=k_score; }
}

and heres the div that displays the score:
<div id='score' style='left: 10; top:15; position: absolute; display:none; z-index:100;'></div>

Kor
09-30-2004, 04:14 AM
You added bananas with oranges...:D

Your values are strings, as they are quoted. If you need a math adding:

Either
set your values as numbers

...
kscore(1,'update');
...
var k_score=0
...
if(action=='start'){
k_score=0

Or parse your strings to numbers

if(area==1){ k_score = Number(k_score) + 100 }
if(area==2){ k_score = Number(k_score) + 75 }
if(area==3){ k_score = Number(k_score) + 50 }

To parse a string to anumber you may use different methods Number(), parseInt(), parseFloat()... or simply multipy/divide with/by 1.

ck_net_2004
09-30-2004, 04:20 AM
Thanks kor, i knew it would be something like that but i could not
figgure it out.

Kor
09-30-2004, 04:42 AM
...and probably is a better ideea to specify the display value(even, at least till know, the default empty value is 'inline')

document.getElementById('score').innerHTML=k_score;
document.getElementById('score').style.fontSize='12';
document.getElementById('score').style.display='inline'; }

or

document.getElementById('score').innerHTML=k_score;
document.getElementById('score').style.fontSize='12';
document.getElementById('score').style.display='block'; }