Проверка Победы в Свинг Tic Tac Toe
Я пытаюсь создать игру в крестики-нолики, используя свинг, но у меня возникают проблемы с проверкой победителя. У меня есть три класса: один для проверки победы, один для самой игры и один для каждой кнопки. Я не знаю, как заставить проверку победы работать, если кто-то может помочь. Это будет очень цениться.
Tic Tac Toe Класс:
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TicTacToe extends JFrame {
JPanel panel = new JPanel();
public static boolean gameWon = false;
public static int o = 1;
public static int x = 0;
static JFrame frame = new JFrame();
//turn counter called in the button to switch between x and o
public static int turn = 0;
public static int[] totalTurns = new int[9];
static Victory vic = new Victory();
//the brackets are creating an array
//we need nine buttons so a total of 9 slots for buttons in the array
Button[] button = new Button[9];
public static void main(String[] args) {
new TicTacToe();
vic.checkWin();
}
public TicTacToe()
{
//making it so each square is 600x600
//can be resized, maybe change that?
//make the program stop when closed
setSize(800,800);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
//making a 3x3 grid within the panel in a grid layout
panel.setLayout(new GridLayout(3,3) );
//creating 9 buttons within the button array
for(int i = 0; i < 9; i++)
{
//creates button
System.out.println("creating button " + i);
button[i] = new Button();
button[i].setText("");
//adds button to the panel
panel.add(button[i]);
}
add(panel);
setVisible(true);
}
}
Класс кнопки:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.ImageIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Button extends JButton implements ActionListener{
//The two options aside from empty
ImageIcon X,O;
public String x = "X";
public String o = "O";
public Button()
{
X = new ImageIcon(this.getClass().getResource("x.jpg"));
O = new ImageIcon(this.getClass().getResource("o.jpg"));
this.addActionListener(this);
}
public void actionPerformed(ActionEvent event)
{
switch(TicTacToe.turn)
{
case 0: //turn is 0
setIcon(X);
setText(x);
System.out.println("printing X");
TicTacToe.turn++;
System.out.println("switching turn");
removeActionListener(this);
break;
case 1: //turn is 1 and then reduces back to case 0
setIcon(O);
setText(o);
System.out.println("printing O");
TicTacToe.turn--;
System.out.println("switching turn");
removeActionListener(this);
break;
}
}
}
Класс Победы:
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Victory extends TicTacToe {
JFrame frame = new JFrame();
public static boolean gameWon = false;
public void checkWin()
{
if (button[0].getText() == button[1].getText()
&& button[1] == button[2] && button[0].getText() != "") //top row
[x][x][x]
{
System.out.println("Victory condition met: top row");
gameWon = true;
Win();
}
else if (button[3].getText() == button[4].getText()
&& button[4].getText() == button[5].getText() && button[3].getText() != "") //mid row [x][x][x]
{
System.out.println("Victory condition met: mid row");
gameWon = true;
Win();
}
else if (button[6].getText() == button[7].getText()
&& button[7].getText() == button[8].getText() && button[6].getText() != "") //bot row [x][x][x]
{
System.out.println("Victory condition met: bot row");
gameWon = true;
Win();
}
else if (button[0].getText() == button[3].getText()
&& button[3].getText() == button[6].getText() && button[0].getText() != "") //first column [x][x][x]
{
System.out.println("Victory condition met: first col");
gameWon = true;
Win();
}
else if (button[1].getText() == button[4].getText()
&& button[4].getText() == button[7].getText() && button[1].getText() != "") //second column [x][x][x]
{
System.out.println("Victory condition met: second col");
gameWon = true;
Win();
}
else if (button[2].getText() == button[5].getText()
&& button[5].getText() == button[8].getText() && button[2].getText() != "") //last column [x][x][x]
{
System.out.println("Victory condition met: last col");
gameWon = true;
Win();
}
else if (button[0].getText() == button[4].getText()
&& button[4].getText() == button[8].getText() && button[0].getText() != "") //diag 1 [x][x][x]
{
System.out.println("Victory condition met: diag 1");
gameWon = true;
Win();
}
else if (button[2].getText() == button[4].getText()
&& button[4].getText() == button[6].getText() && button[2].getText() != "") //diag 2 [x][x][x]
{
System.out.println("Victory condition met: diag 2");
gameWon = true;
Win();
}
else if (turn == 9)
{
System.out.println("Victory conditions not met");
gameWon = false;
Win();
}
}
private void Win()
{
System.out.println("Win Called");
if(button[0].getText() == "O")
{
JOptionPane.showMessageDialog(frame, "O wins!");
System.out.println("O wins");
}
if(button[0].getText() == "X")
{
JOptionPane.showMessageDialog(frame, button[0].getText() + " wins!");
System.out.println("X wins");
}
else if (turn == 9 && gameWon == false)
{
JOptionPane.showMessageDialog(null, "Tie!");
System.out.println("Tie");
}
}
}
Я думаю, что я должен назвать победу после того, как TicTacToe будет создан в основном, однако это приводит к созданию двух плат TicTacToe. Что я делаю?
1 ответ
После того, как вы исправите это, вы, вероятно, должны принять это к обмену Code Review, потому что в нем ОЧЕНЬ много ошибок. Но что касается вашего вопроса о vic.checkWin();
:
Ваша проблема в том, что вы звоните только один раз. После того, как пользователь закрывает игровое окно. Вам нужно вызывать проверку победы после каждого хода.