I'm trying to make a thing for an assignment and I need to make it so basically two "dots" race and they move a random distance from 1-3. I have the random generator working but each time I press the button to advance the "dots" the value of how far they should be keeps resetting and I can't figure out how to fix it, and I can't get anything else to work if the values aren't declared as zero, and that's the problem because that's what is causing the values to reset each time I press the button. If someone could help me it would be greatly appreciated.
(This is what I have for my code, this is in HTML btw)
<!doctype html>
<html>
<head>
<title> Dot Race </title>
<h1> Dot Race </h1>
<body>
<script>
function dotAdvance()
{
var dot1F = 0, dot2F = 0;
dot1A =Math.floor(Math.random() * 4);
dot2A =Math.floor(Math.random() * 4);
if(dot1A == 0)
{
}
else if(dot1A == 1)
{
dot1F ;
}
else if(dot1A == 2)
{
dot1F ;
dot1F ;
}
else
{
dot1F ;
dot1F ;
dot1F ;
}
if(dot2A == 0)
{
}
else if(dot2A == 1)
{
dot2F ;
}
else if(dot2A == 2)
{
dot2F ;
dot2F ;
}
else
{
dot2F ;
dot2F ;
dot2F ;
}
goal= parseFloat(document.getElementById('goalDistance').value);
if(dot1F >= goal && dot2F >= goal)
{
alert("Test: Tie");
}
else if(dot1F >= goal)
{
alert("Test: Dot 1");
}
else if(dot2F >= goal)
{
alert("Test: Dot 2");
}
document.getElementById("outputDiv").innerHTML = "Test:" dot1F " Test2:" dot2F;
}
</script>
Enter Goal Distance: <input type="text" id="goalDistance" size=12 value="">
<button onclick="">Reset Race</button>
<button onclick="dotAdvance()">Take a Step</button>
<hr>
<div id="outputDiv"></div>
<body>
</html>
``
CodePudding user response:
Every time you call the function dotAdvance the variables dot1F and dot2F are reset. You should try to take them out from the function.