I made this simple program for a 2 player TiCTacToe game.
But It doesnt seem to be working properly. I cant understand whats going wrong here!
Please help...
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MainFrame extends JFrame
{
JButton [][] buttons= new JButton[3][3];
JTextField statusBar;
GamePanel panel;
Integer turn;
GameListener listener=new GameListener();
public MainFrame()
{
setLayout(new BorderLayout());
panel=new GamePanel();
add(panel,BorderLayout.CENTER);
statusBar=new JTextField("Player1's Turn");
statusBar.setEditable(false);
add(statusBar,BorderLayout.SOUTH);
setTitle("Tic Tac Toe!");
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(400,400,300,300);
}
class GamePanel extends JPanel
{
public GamePanel()
{
setLayout(new GridLayout(3,3));
turn =1;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
{
buttons[i][j]=new JButton();
buttons[i][j].putClientProperty("INDEX", new Integer[]{i,j});
buttons[i][j].putClientProperty("OWNER", new Integer(i+10));
buttons[i][j].addActionListener(listener);
add(buttons[i][j]);
}
}
}
class GameListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
JButton b=(JButton)e.getSource();
System.out.println(turn); //turn
Integer[]index=(Integer[]) b.getClientProperty("INDEX");
buttons[index[0]][index[1]].putClientProperty("OWNER", turn);
b.setIcon(new ImageIcon(turn.toString()+".gif"));
b.setEnabled(false);
boolean result=checkVictoryCondition(index);
if(result)
{
JOptionPane.showMessageDialog(null, "Player "+turn.toString()+" Wins");
initComponents();
}
else
{
if(turn==1)
{
turn=2;
statusBar.setText("Player2's Turn");
}
else
{
assert turn==2;
turn=1;
statusBar.setText("Player2's Turn");
}
}
}
Integer getOwner(JButton b)
{
return (Integer)b.getClientProperty("OWNER");
}
boolean checkVictoryCondition(Integer [] index)
{
Integer[][]buttonMap=new Integer[][] {
{ getOwner(buttons[0][0]),getOwner(buttons[0][1]),getOwner(buttons[0][2])},
{ getOwner(buttons[1][0]),getOwner(buttons[1][1]),getOwner(buttons[1][2])},
{ getOwner(buttons[2][0]),getOwner(buttons[2][1]),getOwner(buttons[2][2])}
};
Integer a=index[0];
Integer b=index[1];
int i;
//check row
for(i=0;i<3;i++)
{
if(buttonMap[a][i]!=buttonMap[a][b])
break;
}
if(i==3)
return true;
//check column
for(i=0;i<3;i++)
{
if(buttonMap[i][b]!=buttonMap[a][b])
break;
}
if(i==3)
return true;
//check diagonal
if(a==2&&b==2)
{
//right diagonal
if((buttonMap[0][2]==buttonMap[a][b])&&(buttonMap[2][0]==buttonMap[a][b]))
return true;
//left diagonal
else if((buttonMap[0][0]==buttonMap[a][b])&&(buttonMap[2][2]==buttonMap[a][b]))
return true;
}
return false;
}
}
void initComponents()
{
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
{
buttons[i][j].putClientProperty("INDEX", new Integer[]{i,j});
buttons[i][j].putClientProperty("OWNER", new Integer(i+10));
buttons[i][j].setIcon(null);
buttons[i][j].setEnabled(true);
turn=1;
statusBar.setText("Player2's Turn");
}
}
}