I have an issue random number generating. I've made an AI for game "Guessing number game" and it works just fine until the Player hit number lower than searched number. After that Math.random(); may and it is very likely to generate negative numbers. If player hit the number lower than searched number. (Range of numbers gessing by AI is defined by two nums (the highest from array of nums lower[]; than searched and lowest from array higher[]; than searched).
Here is whole code on GitHub since its too large to put it in here: https://github.com/lkobylanski/Guessing-number-game-1P-AI/blob/master/PvAv1.2.js
My question is, how do I properly debug application to find this kind of issue. I was using console.log(functionName)
to display functions one by one in order they are executed. I've made alerts that are displaying arrays, arrays[0], arrays.length but it didn't help me and I got stuck. I have no more ideas what I can do.
Function starts to generate negatvies during executting this part of code:
else if(higher_l > 0 && lower_l > 0)
{ //losuje od 0 (ZERA) do (max-min+1) i dodaje + min;
guessed = Math.floor(Math.random()*((higher[0])-((lower[0]+1)+1))+(lower[0]+1));
if(guessed > drawn)
{
c2--;
document.getElementById("notes2").innerHTML = p2 + " remaining chances: " + c2;
higher.push(guessed);
higher_l = higher.length;
higher.sort(function(a, b) {return a-b;});
resultH = resultH + guessed + " ";
document.getElementById("higher").innerHTML = "Proper number is lower than: " + resultH;
counter = setTimeout(checkCounters, 100);
switch_trigger = setTimeout(switchPlayers, 2000);
return;
}
else if(guessed < drawn)
{
c2--;
document.getElementById("notes2").innerHTML = p2 + " remaining chances: " + c2;
lower.push(guessed);
lower_l = lower.length;
lower.sort(function(a, b) {return b-a});
resultL = resultL + guessed+ " ";
document.getElementById("lower").innerHTML = "Proper number is higher than: " + resultL;
counter = setTimeout(checkCounters, 100);
switch_trigger = setTimeout(switchPlayers, 2000);
return;
}
else if(guessed == drawn)
{
p2w++;
document.getElementById("all_wins").innerHTML = p1 + " wins: " + p1w + "/" + wins + "<br/>" + p2 + " wins " + p2w + "/" + wins;
if(p2w < wins)
{
document.getElementById("msg").innerHTML = "AI found the number: " + guessed + "first!<br/>" + currentp + " and gets a point!";
document.getElementById("next").disabled = false;
}
else if(p2w == wins)
{
alert("Winner is " + currentp + "!");
document.getElementById("msg").innerHTML = "AI found the number: " + guessed + " <br/> Player: " + currentp + " reached required number of: " + wins + " wins first!";
}
end = setTimeout(endMatch, 100);
return;
}
}
I know that the code itself could be a way better than this but I want to improve it when the whole thing will be working.