- Joined
- Jan 21, 2007
- Sythe Gold
- 1,234
- Messages
- 14,211
I made this as an example / because it was a good idea.
Its crappy coding, but it works.
Its crappy coding, but it works.
Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Game extends JFrame implements ActionListener
{
public JButton[] buttons = new JButton[9];
public JLabel info;
public JButton reset;
public boolean turn = true;// True = X's Turn, False = O's Turn
public int[][] wins =
{
{ 0, 1, 2 },
{ 0, 3, 6 },
{ 0, 4, 8 },
{ 1, 4, 7 },
{ 2, 4, 6 },
{ 2, 5, 8 },
{ 6, 7, 8 },
{ 3, 4, 5 } };
int tie = 0;
public static void main(String[] args)
{
new Game();
}
public Game()
{
loadGUI();
}
public void loadGUI()
{
this.setSize(137, 260);
this.setTitle("SuF's TicTacToe");
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setResizable(false);
JLabel title = new JLabel("SuF's TicTacToe");
info = new JLabel("It's X's turn!");
reset = new JButton("Reset");
reset.setFocusable(false);
reset.addActionListener(this);
JPanel a = new JPanel();
a.setLayout(new GridLayout(0, 3));
a.setBounds(0, 50, 129, 129);
for (int i = 0; i < 9; i++)
{
buttons[i] = new JButton(" ");
buttons[i].setFocusable(false);
buttons[i].addActionListener(this);
a.add(buttons[i]);
}
JPanel b = new JPanel();
b.add(title);
b.add(info);
b.setBounds(0, 0, 129, 50);
JPanel c = new JPanel();
c.setBounds(0, 180, 129, 35);
c.add(reset);
JPanel d = new JPanel();
d.setLayout(null);
d.add(a);
d.add(b);
d.add(c);
this.add(d);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == reset)
{
for (int b = 0; b < 9; b++)
{
buttons[b].setEnabled(true);
buttons[b].setText(" ");
}
info.setText("It's X's turn!");
tie = 0;
turn = true;
}
for (int i = 0; i < 9; i++)
{
if (e.getSource() == buttons[i])
{
if (turn)
{
buttons[i].setText("X");
buttons[i].setEnabled(false);
turn = false;
info.setText("It's O's turn!");
tie++;
boolean check = checkWin();
if(tie == 9 && !check)
{
info.setText("It's a tie!");
tie = 0;
}
}
else if (!turn)
{
buttons[i].setText("O");
buttons[i].setEnabled(false);
turn = true;
info.setText("It's X's turn!");
tie++;
boolean check = checkWin();
if(tie == 9 && !check)
{
info.setText("It's a tie!");
tie = 0;
}
}
buttons[i].setEnabled(false);
break;
}
}
}
public boolean checkWin()
{
int a = 0;
for (int i = 0; i < 8; i++)
{
a = 0;
if (buttons[wins[i][a]].getText().equals("O"))
{
a++;
if (buttons[wins[i][a]].getText().equals("O"))
{
a++;
if (buttons[wins[i][a]].getText().equals("O"))
{
info.setText("O is the winner!");
for (int b = 0; b < 9; b++)
{
buttons[b].setEnabled(false);
}
return true;
}
}
}
}
for (int i = 0; i < 8; i++)
{
a = 0;
if (buttons[wins[i][a]].getText().equals("X"))
{
a++;
if (buttons[wins[i][a]].getText().equals("X"))
{
a++;
if (buttons[wins[i][a]].getText().equals("X"))
{
info.setText("X is the winner!");
for (int b = 0; b < 9; b++)
{
buttons[b].setEnabled(false);
}
return true;
}
}
}
}
return false;
}
}











