Thursday, 25 September 2014

Tic Tac Toe Applet

Here is a simple two-player Tic Tac Toe applet, just to get familiar with ActionListeners and basic GridView. Hopefully, the code below is well-commented and self-explanatory.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
@SuppressWarnings("serial")
public class TicTacToe extends Applet implements ActionListener{
JButton button[][] = new JButton[3][3];
boolean isZero = true; //first turn is always 0
public void init(){
setSize(500, 500);
setLayout(new GridLayout(3,3));
//initialize the Grid and add ActionListener to each Button
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
button[i][j] = new JButton("");
add(button[i][j]);
button[i][j].addActionListener(this);
}
}
}
public void actionPerformed(ActionEvent event){
for(int i = 0; i < 3; i++)
for(int j = 0; j < 3; j++){
if((event.getSource() == button[i][j])){
if(isZero){
button[i][j].setText("O");
}
else{
button[i][j].setText("X");
}
button[i][j].removeActionListener(this); //you cannot click on one tile more than once
isZero = !isZero;
checkForWinners(); //check if any winner after each move
}
}
}
public void checkForWinners(){
//3 horizontal lines
for(int i = 0; i < 3; i++){
if(button[i][0].getText().equals(button[i][1].getText())
&& button[i][1].getText().equals(button[i][2].getText())
&& !button[i][0].getText().equals("")){
JOptionPane.showMessageDialog(null, button[i][0].getText() + " wins!");
return;
}
}
//3 vertical lines
for(int i = 0; i < 3; i++){
if(button[0][i].getText().equals(button[1][i].getText())
&& button[0][i].getText().equals(button[2][i].getText())
&& !button[0][i].getText().equals("")){
JOptionPane.showMessageDialog(null, button[0][i].getText() + " wins!");
return;
}
}
//top to bottom (rightwards) diagonal
if(button[0][0].getText().equals(button[1][1].getText())
&& button[1][1].getText().equals(button[2][2].getText())
&& !button[0][0].getText().equals("")){
JOptionPane.showMessageDialog(null, button[0][0].getText() + " wins!");
return;
}
//bottom to top (leftwards) diagonal
if(button[0][2].getText().equals(button[1][1].getText())
&& button[1][1].getText().equals(button[2][0].getText())
&& !button[2][0].getText().equals("")){
JOptionPane.showMessageDialog(null, button[2][0].getText() + " wins!");
return;
}
}
}

Here are some snaps of the output :


No comments:

Post a Comment