Get a sticky random number in a often called function (Javascript) -
i making guess number machine, supported book 'html5 game programming dummies'. got stuck @ function random number called.
i tried put outside function, doesn't work, because number doesn't refresh when there no turns. tried put in first if statement, called first time, gives undefined error. any1 can me?
code:
var turns = 3; function guess() { var randnum = math.round(math.random()*100); var input = document.getelementbyid('input').value; var output = document.getelementbyid('output'); if(turns == 3) { if(input == randnum) { output.innerhtml = 'congratulations! thats right answer!'; turns = 4; } else if(input > randnum) { output.innerhtml = 'the number lower!'; } else { output.innerhtml = 'the number higher!'; } turns--; } else if(turns == 2) { if(input == randnum) { output.innerhtml = 'congratulations! thats right answer!'; turns = 4; } else if(input > randnum) { output.innerhtml = 'the number lower!'; } else { output.innerhtml = 'the number higher!'; } turns--; } else if(turns == 1) { if(input == randnum) { output.innerhtml = 'congratulations! thats right answer!'; turns = 3; } else if(input > randnum) { output.innerhtml = 'the number '+randnum+'. lost!'; turns = 3; } else { output.innerhtml = 'the number '+randnum+'. lost!'; turns = 3; } } }
ps. code not optimalized. any1 have tips optimalize code? lot!
it took me little while work out asking here, think answer you're looking ...
add line outside function
var turns = 3; var randnum = math.round(math.random()*100); // 1 function guess() { // ...
and towards end of function:
} else { output.innerhtml = 'the number '+randnum+'. lost!'; turns = 3; } randnum = math.round(math.random()*100); // 1 }
so you're setting random number when document loaded, , having global variable function can access. user attempts 3 times guess number between 1 , 100 (pretty unreasonable challenge), , when run out of 'turns', randnum gets reset new random number user keep on guessing.
Comments
Post a Comment