我如何为我的井字游戏赢得胜利?我需要在玩家完成时也这样做,它会询问他们是否想要再玩一次。如果你想办法,请告诉我为什么会这样。这是我的代码:
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++;
}
}
}
答案 0 :(得分:0)
尝试使用此方法查找获胜者。
我已经提到了所有获胜的位置。您必须检查每次点击的所有位置。
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;
}
最后在actionPerformed()
方法中添加它。
public void actionPerformed(ActionEvent event) {
...
String winner = getWinner();
if (winner != null) {
System.out.println(winner + " is winner");
gameWindow.dispose();
}
}