Tic-Tac-Toe Simulator Create an application that simulates a game of tic-tac-toe
ID: 3809609 • Letter: T
Question
Tic-Tac-Toe Simulator Create an application that simulates a game of tic-tac-toe. Figure shows an example of the application's form. The form shown in the figure uses eight large Label controls to display the Xs and Os. The application should use a two-dimensional int array to simulate the game board in memory. When the user clicks the New Game button, the application should step through the array, storing a random number in the range of 0 through 1 in each element. The number 0 represents the letter O, and the number 1 represents the letter X. The form should then be updated to display the game board. The application should display a message indicating whether player X won, player Y won, or the game was a tie. Figure The Tic-Tac-Toe applicationExplanation / Answer
code in java
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class TicTacToeGame extends JPanel
{
JButton buttons[] = new JButton[9];
int alternate = 0;
public TicTacToeGame()
{
setLayout(new GridLayout(3,3));
initialize();
}
public void initialize()
{
for(int i = 0; i <= 8; i++)
{
buttons[i] = new JButton();
buttons[i].setText("");
buttons[i].addActionListener(new Listener());
add(buttons[i]);
}
}
public void resetButton()
{
for(int i = 0; i <= 8; i++)
{
buttons[i].setText("");
}
}
private class Listener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
JButton buttonClicked = (JButton)e.getSource();
if(alternate%2 == 0)
buttonClicked.setText("X");
else
buttonClicked.setText("O");
if(CheckIsSomeOneWin() == true)
{
JOptionPane.showConfirmDialog(null, "Game Over.");
resetButton();
}
alternate++;
}
public boolean CheckIsSomeOneWin()
{
if( checkAdjacent(0,1) && checkAdjacent(1,2) )
return true;
else if( checkAdjacent(3,4) && checkAdjacent(4,5) )
return true;
else if ( checkAdjacent(6,7) && checkAdjacent(7,8))
return true;
else if ( checkAdjacent(0,3) && checkAdjacent(3,6))
return true;
else if ( checkAdjacent(1,4) && checkAdjacent(4,7))
return true;
else if ( checkAdjacent(2,5) && checkAdjacent(5,8))
return true;
else if ( checkAdjacent(0,4) && checkAdjacent(4,8))
return true;
else if ( checkAdjacent(2,4) && checkAdjacent(4,6))
return true;
else
return false;
}
public boolean checkAdjacent(int a, int b)
{
if ( buttons[a].getText().equals(buttons[b].getText()) && !buttons[a].getText().equals("") )
return true;
else
return false;
}
}
public static void main(String[] args)
{
JFrame window = new JFrame("TicTacToeGame");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().add(new TicTacToeGame());
window.setBounds(300,200,300,300);
window.setVisible(true);
}
}