Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

if statements 1

Status
Not open for further replies.

killerg

Programmer
Dec 2, 2006
15
CY
Hello,
i have a question again will nested loops cause
a problem ? for example i have the following code

if(document.myForm.box6.value=="" && Math.random()<0.5){
document.myForm.box6.value="O";
document.myForm.box6.style.color="Blue"
}
else if(document.myForm.box6.value==""){
document.myForm.box6.value="X";
document.myForm.box6.style.color="Blue"
}
else if(document.myForm.box1.value=="" && Math.random()<0.5){
document.myForm.box1.value="O"
document.myForm.box1.style.color="Blue"
}
else if(document.myForm.box1.value==""){
document.myForm.box1.value="X";
document.myForm.box1.style.color="Blue"
}

and it gets bigger but when i click on the buttons they dont always show the value and that means that something is wrong and i dont understand the reason.

is it because of the nested if??
 
You don't have nested anything, and no loops at all.

You might find things a little clearer overall if you wrote the code like this:
Code:
//if this is a standard tictactoe board with 9 boxes
// named box1 through box9
var numboxes = 9;
for (var bi = 1; bi <= numboxes; bi++)
  {
  var onebox = document.forms['myForm'].elements['box' + bi];
  if(onebox.value == '')
    {
    if (Math.round(Math.random()) == 0)
      {
      onebox.value="O";
      onebox.style.color="Blue";
      }
    else
      {
      onebox.value="X";
      onebox.style.color="Blue";
      }
    //if this is the one then break out of the loop
    break;
    } 
  }

Have you done a Google search for Javascript tictactoe?

Lee
 
is not a tic tac toe game. but thanks i ll try the random method.
 
Comparing floating point numbers can often produce inaccurate results. That's why I used Math.round().

By using a loop, if you want to change some behavior of one of the text boxes, you only have to do it in one spot rather than in every place you have a text box. And if you make a mistake, changing it one place takes care of the whole routine.

Lee
 
yes i know is easier with loops thanks a lot it help me a lot!!!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top