Page 745 - Introduction to Programming with Java: A Problem Solving Approach
P. 745
JButton btn = (JButton) e.getSource();
if (btn.getText().isEmpty())
{
btn.setText(xTurn ? "X" : "O");
if win() ⎫ ⎪
⎪ print winning player ⎬ ⎪ ⎪ } ⎭
17.7 Problem Solving: Winning at Tic-Tac-Toe (Optional) 711
from within the listener and have that update be remembered the next time the listener is called. Thus, you need to declare the buttons array as an instance variable.
You need to check for a win only when the user clicks a button. So add check-for-a-win code to the actionPerformed method inside the button’s listener. In adding the code, use top-down de- sign. In other words, don’t worry about the low-level details; just assume they work. Here’s the updated actionPerformed method. The added code is in pseudocode:
public void actionPerformed(ActionEvent e)
{
}
// end actionPerformed
}
{
else
{
}
xTurn = !xTurn;
Apago PDF Enhancer
prepare for new game
The pseudocode contains three tasks—checking for a win, printing the winner, and preparing for a new game. Checking for a win requires the most thought, so we’ll postpone that task for now. Let’s discuss the other two tasks first.
Printing the winner should be straightforward. Just call JOptionPane.showMessageDialog with a congratulatory message. The message should include the player’s name, X or O, which can be ob- tainedbyre-usingtheconditionaloperatorcode,xTurn ? "X" : "O".
Preparing for a new game should be straightforward as well. Just assign the empty string to the board’s button labels and assign true to the xTurn variable (X always goes first).
Feel free to implement the print-winning-player and prepare-for-new-game tasks as embedded code inside the if statement or as separate helper methods. Either way is fine. But the checking-for-a-win task should definitely be implemented as a separate helper method. Why? Note how cleanly win is called in the above pseudocode. You can retain that clean look in the final Java code only if you implement the checking- for-a-win task as a method, not as embedded code.
In implementing the win method, you need to check the two-dimensional buttons array for three in a row, three in a column, or three in a diagonal. Normally, when you access a group of elements in an array, you should use a for loop. So you might want to use a for loop to access the elements in the first row, use an- other for loop to access the elements in the second row, and so on. But that would require eight for loops:
for loop for first row
for loop for second row
...
for loop for second diagonal
p
p
s
s
e
e
u
ud
d
o
o
c
co
o
d
d
e
e