问题
How would I make a win condition to my tic-tac-toe game? I need to also make it so when the player is done, that it will ask them if they want to play again. If you figure out a way, can you please tell me why that is so. Here is my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class game extends JFrame{
JFrame gameWindow = new JFrame("Tic-Tac-Toe");
private JButton buttons[] = new JButton[9];
private String mark = "";
private int count = 0;
public static void main(String[] args){
new game();
}
public game(){
HandlerClass handler = new HandlerClass();
// Sets buttons on the screen
for(int i = 0; i < buttons.length; i++){
buttons[i] = new JButton(mark);
buttons[i].addActionListener(handler);
gameWindow.add(buttons[i]);
}
// Sets the looks of the window
gameWindow.setLayout(new GridLayout(3,3));
gameWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameWindow.setSize(300,300);
gameWindow.setVisible(true);
}
private class HandlerClass implements ActionListener{
@Override
public void actionPerformed(ActionEvent event) {
JButton click = (JButton) event.getSource();
if(count % 2 == 0){
mark = "X";
click.setBackground(Color.YELLOW);
}else{
mark = "O";
click.setBackground(Color.CYAN);
}
click.setText(mark);
click.setEnabled(false);
System.out.println(count + "\n" + (count % 2));
count++;
}
}
}
回答1:
Try this method to find out the winner.
I have mentioned all the winning positions. You have to check all the position on each click.
public String getWinner() {
int[][] winPositions = new int[][] { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 },
{ 0, 3, 6 }, { 1, 4, 7 }, { 2, 7, 8 },
{ 0, 4, 8 }, { 2, 4, 6 } };
for (int[] positions : winPositions) {
if (buttons[positions[0]].getText().length() > 0
&& buttons[positions[0]].getText().equals(buttons[positions[1]].getText())
&& buttons[positions[1]].getText().equals(buttons[positions[2]].getText())) {
return buttons[positions[0]].getText();
}
}
return null;
}
Add it in your actionPerformed()
method in the end.
public void actionPerformed(ActionEvent event) {
...
String winner = getWinner();
if (winner != null) {
System.out.println(winner + " is winner");
gameWindow.dispose();
}
}
来源:https://stackoverflow.com/questions/22947294/java-tictactoe-game-wincondition