Java TicTacToe


Hello people! Wow its been a while since I posted something here…! I must say I really miss writing stuff and I promise I wont get into a ‘writer’s block’ again. Hopefully :).. A helluva lot of things happened in the last two months and I’ve got loads to say. But in this post Im just gonna publish a small application that I wrote sometime ago. Its a TicTacToe game application. There’s not much to be learnt from this particular program but I really want to get outta this impasse and hence Im posting this today.

I actually wrote this code to show off some of the really cool features of Java to one of my friends who also wrote the same application in a “C++”-esque style. And btw that friend of mine even developed code for the computer player. But after completing his code he sadly realized the basic fact that you cannot win in TicTacToe if you play perfectly!! Hehe :D So I did not venture into that area. Well to be honest, Im not really interested in writing AI apps. But I thought of adding Network Multiplayer functionality to this application since I love network programming. But unfortunately I havent had the time to do so.

Anywaiz the application works like this – the game is autostarted once launched and the status bar indicates which player’s turn its now and rest is just simple tictactoe! And at the end of the game the app is automatically reset.

Onto the code..


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.logging.Logger;

/**
* TicTacToe Application
* @author Steve Robinson
* @version 1.0
*/

class TicTacToeFrame extends JFrame
{

	JButton [][] buttons= new JButton[3][3];
	JTextField statusBar;
	GamePanel panel;
	Integer turn;
	GameListener listener=new GameListener();
	Integer count;

	public TicTacToeFrame()
	{
		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;
			count=0;
			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", null);
					buttons[i][j].addActionListener(listener);
					add(buttons[i][j]);
				}
		}
	}

	class GameListener implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			count++;
			JButton b=(JButton)e.getSource();
			Integer[]index=(Integer[]) b.getClientProperty("INDEX");

			//System.out.println(turn);	//turn       											//			//System.out.println("["+index[0]+"]"+"["+index[1]+"]");  							//
			b.putClientProperty("OWNER", turn);
			Icon ico=new ImageIcon(turn.toString()+".gif");
			b.setIcon(ico);
			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
				{
					turn=1;
					statusBar.setText("Player1's Turn");
				}
			}
			if(count==9)
			{
				JOptionPane.showMessageDialog(null, "Match is a draw!");
				initComponents();

			}

		}

		Integer getOwner(JButton b)
		{
			return (Integer)b.getClientProperty("OWNER");
		}

		//PrintButtonMap for Diagnostics
		void printbuttonMap(Integer [][]bMap)
		{
			for(int i=0;i				for(int j=0;j					System.out.print(bMap[i][j]+" ");
				System.out.println("");
			}
		}

		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])}
			};

			printbuttonMap(buttonMap); */

			Integer a=index[0];
			Integer b=index[1];
			int i;

			//check row
			for(i=0;i<3;i++)		{
				if(getOwner(buttons[a][i])!=getOwner(buttons[a][b]))
					break;
			}
			if(i==3)
				return true;

			//check column
			for(i=0;i<3;i++)		{
				if(getOwner(buttons[i][b])!=getOwner(buttons[a][b]))
					break;
			}
			if(i==3)
				return true;

			//check diagonal
			if((a==2&&b==2)||(a==0&&b==0)||(a==1&&b==1)||(a==0&&b==2)||(a==2&&b==0))
			{
				//left diagonal
				for(i=0;i					if(getOwner(buttons[i][i])!=getOwner(buttons[a][b]))
						break;
				if(i==3)
					return true;

				//right diagonal
				if((getOwner(buttons[0][2])==getOwner(buttons[a][b]))&&(getOwner(buttons[1][1])==getOwner(buttons[a][b]))&&(getOwner(buttons[2][0])==getOwner(buttons[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",null);
				buttons[i][j].setIcon(null);
				buttons[i][j].setEnabled(true);
				turn=1;
				count=0;
				statusBar.setText("Player1's Turn");

			}
	}

}

class TicTacToe {

	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable(){
			public void run()
			{
				TicTacToeFrame frame=new TicTacToeFrame();
			}
		});

	}

}

The code is rather straightforward. Ive used two properties in the Buttons to store some information used for checking the winning condition. One is the “OWNER” property which indicates which user currently owns the square and the “INDEX” property which indicates the square’s index in the grid (ie [1,1], [1,2]… etc) Once any player clicks on a square, the OWNER property is updated and the victoryCondition is checked by using the OWNER properties of all the buttons. The rest of the code is self explanatory.

And adding keyboard support for the second player is a pretty easy job. As they say… “I leave that as an exercise”! Hahaha :D Well I really hope I get some time so that I can add network functionality to this application.
Cheers,
Steve.

—–

I forgot to attach the image icon files that will be used by the application. You can download it from here…

 http://www.mediafire.com/?d7d93v2342dxind

Just extract the contents to the folder that contains the code. Thanks to my friend “Gur Png” for telling me about this. 
-Steve

2 thoughts on “Java TicTacToe

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s