So I was learning javascript and at one point I thought, maybe I could create a small game, so I went on to create “The Number Guessing Game”. It is like binary search, if you dont know what that is, then search it up. I need you, to debug my code because I can’t seem to fix it myself, also I know this is the wrong section, though I couldn’t find a section for this, so it is here. Sorry…
<Below this line, in what way does your code behave incorrectly? Include ALL error messages.>
My code won’t really start, as it is supposed to, obviously.
JAVASCRIPT
document.addEventListener('DOMContentLoaded',function() {
var tNum=getNum(); // The chosen number to find
var tries=0;
var z=document.querySelector('.button'); // The button that submits the text
z.addEventListener('click', function () {
numReact(tries,tNum);
tries=numReact(tries,tNum);
var gameOver=checkLose(tries);
if(gameOver===true) {
document.querySelector('.input').disabled=true; //disable the text box and submit button if games over, reset page to try again
}
});
});
// the chosen number
function getNum () {
return Math.random()*100+1;
}
// the chosen number
// how to react to the number chosen by the player to the real number
function numReact (tries,tNum) { // takes in tNum and tries to try find if the player got the number and how to react
var x= document.querySelector('.chosenNum');
document.querySelector('.oldNum').innerHTML='YOU CHOSE' + x + '.';
document.querySelector('.chosenNum').innerHTML= '';
if (x<tNum) {
document.querySelector('.tooHighLow').innerHTML= 'Too Low'; // replay with too low if the number is... too low
tries+=1;
return tries; // return the turn the player is on
}else if(x>tNum) {
document.querySelector('.tooHighLow').innerHTML= 'Too High'; // replay with too high if the number is... too high
tries+=1;
return tries;
}else{
document.querySelector('.tooHighLow').innerHTML= 'You Got It, The Number, Good Job';
// replay with good job if your guessed number is the same as the real number
document.getElementByTagName('input').disabled=true; // disable all input tags, to stop furthur confrontation
}
}
function checkLose(tries) {
if(tries<=10) { // if tries are less than 10, return false
return false;
}else{
document.querySelector('.tooHighLow').innerHTML='Thats it, you lost the game because you have 11 tries'; // if tries are greater than 10, return true
return true;
}
}
HTML
<!DOCTYPE html>
<html>
<head>
<title>Number Guessing Game</title>
</head>
<body>
<h1>The Number Guessing Game</h1>
<hr>
<p>To play:</p>
<ul>
<li>Guess a Number</li>
<li>If your number is too high, try a lower one, vice versa if your number is too high</li>
<li>You have 10 tries to do such, after that, reload the page</li>
</ul>
<input type="text" class="chosenNum">
<p class="oldNum"> </p>
<p><b class="tooHighLow"> </b></p>
<input type="button" class="input" value="CLICK ONCE">
</body>
</html>
Please help me debug this, I really can’t find the issue.