View Single Post
  #6 (permalink)  
Old 02-23-2007, 09:48 AM
pranky pranky is offline
D-Web Programmer
 
Join Date: Feb 2007
Posts: 51
pranky is on a distinguished road
Default Re: Java:Tutorial - Tic-Tac-Toe

Now we need to determine the winner. I created some logical statements to determine each possible case of winning. Ecentially if button1, button2, and button3 were all the same value, that person won, but you also have to account for the fact that when the program starts each button is null causing the winner to be null. However null is not a player and in your logical statements you must account for this. I created a Boolean win instance variable set to false by default and then added these logical statements to my actionPerformed method.

Code:

if( button1.getText() == button2.getText() && button2.getText() == button3.getText() && button1.getText() != ""){
win = true;
}
else if(button4.getText() == button5.getText() && button5.getText() == button6.getText() && button4.getText() != ""){
win = true;
}
else if(button7.getText() == button8.getText() && button8.getText() == button9.getText() && button7.getText() != ""){
win = true;
}

//virticle wins
else if(button1.getText() == button4.getText() && button4.getText() == button7.getText() && button1.getText() != ""){
win = true;
}
else if(button2.getText() == button5.getText() && button5.getText() == button8.getText() && button2.getText() != ""){
win = true;
}
else if(button3.getText() == button6.getText() && button6.getText() == button9.getText() && button3.getText() != ""){
win = true;
}

//diagonal wins
else if(button1.getText() == button5.getText() && button5.getText() == button9.getText() && button1.getText() != ""){
win = true;
}
else if(button3.getText() == button5.getText() && button5.getText() == button7.getText() && button3.getText() != ""){
win = true;
}
else {
win = false;
}

Which accounts for every possible win. Now that we have determined the winner, lets add a popup box announcing the winner. All we have to do is create a if statement and if there is a winner announce it, if there is no winner after nine clicks announce there is a tie. To create a popup box we are going to use showMessageDialog provided to us in the JOptionPane package.

Code:

if(win == true){
JOptionPane.showMessageDialog(null, letter + " WINS!");
} else if(count == 9 && win == false){
JOptionPane.showMessageDialog(null, "Tie Game!");
}
Reply With Quote