I have been doing an assignment for my my first year software course, in which we have to make a simple TicTacToe program in java.
For the final 30% mark, we have to add a GUI in. Apart fro a tutorial only teaching me the basics (how to make boxes and buttons), I am up a creek without a paddle.
My code:

import java.util.Random;
import javax.swing.JOptionPane;
public class tictac 
{

	public static void main (String[] args) {
		
		while (true){
			
			char computer = 'o';
			char player = 'x';
			char a[] = {'A','B','C','D','E','F','G','H','I'};
			char s;
			int x;
			int w = 0; 
			Random rand = new Random();
			// grid at the start
			System.out.println(" "+a[0]+"  |  "+a[1]+"  |  "+a[2]+" ");
			System.out.println(" "+a[3]+"  |  "+a[4]+"  |  "+a[5]+" ");
			System.out.println(" "+a[6]+"  |  "+a[7]+"  |  "+a[8]+" ");
			
			if(JOptionPane.showConfirmDialog(null," Go first?",null,JOptionPane.YES_NO_OPTION)==0){ //asks player to go first or not
				computer = 'o';	 //declares symbol for player
				player = 'x';
			}
			else{
				a[4]=computer; //computer automatically goes for the middle
				

				System.out.println(" "+a[0]+"  |  "+a[1]+"  |  "+a[2]+" ");
				System.out.println(" "+a[3]+"  |  "+a[4]+"  |  "+a[5]+" ");
				System.out.println(" "+a[6]+"  |  "+a[7]+"  |  "+a[8]+" ");
			}
				while(true){ //while continuing to play is possible
					s = new Character(JOptionPane.showInputDialog("Please choose a location").charAt(0));
					switch (s){
					case ('A'):
					case ('a'):
						if (a[0]!= computer&&a[0]!=player)
						{
							a[0]=player;
							}
							else {
								w=1;
							}
						break;
					    case ('B'):
						case ('b'):
							if (a[1]!= computer&&a[1]!=player){
								a[1]=player;
							}
							else {
								w=1;
							}
						break;
						case ('C'):
						case ('c'):
							if (a[2]!= computer&&a[2]!=player){
								a[2]=player;
						    }
							else {
								w=1;
							}
						break;
						case ('D'):
						case ('d'):
							if (a[3]!= computer&&a[3]!=player){
								a[3]=player;
							}
							else {
								w=1;
							}
						break;
						case ('E'):
						case ('e'):
							if (a[4]!= computer&&a[4]!=player){
								a[4]=player;
							}
							else {
								w=1;
							}
						break;
						case ('F'):
						case ('f'):
							if (a[5]!= computer&&a[5]!=player){
								a[5]=player;
							}
							else {
								w=1;
							}
						break;
						case ('G'):
						case ('g'):
							if (a[6]!= computer&&a[6]!=player){
								a[6]=player;
							}
							else {
								w=1;
							}
						break;
						case ('H'):
						case ('h'):
							if (a[7]!= computer&&a[7]!=player){
								a[7]=player;
							}
							else {
								w=1;
							}
						break;
						case ('I'):
						case ('i'):
							if (a[8]!= computer&&a[8]!=player){
								a[8]=player;
							}
							else {
								w=1;
							}
						break;
						
						default:
							w=1;
						break;
						
					} //bring back the grid with updated array
					System.out.println(" ");
					System.out.println(" "+a[0]+"  |  "+a[1]+"  |  "+a[2]+" ");
					System.out.println("----+-----+----");
					System.out.println(" "+a[3]+"  |  "+a[4]+"  |  "+a[5]+" ");
					System.out.println("----+-----+----");
					System.out.println(" "+a[6]+"  |  "+a[7]+"  |  "+a[8]+" ");
				
					if (w==1)
					{
						JOptionPane.showMessageDialog(null, "Invalid Selection");
						w=0;
						continue;
					}
					if (a[4]!=player&&a[4]!=computer) //human win conditions
					{
						a[4]=computer;
					}
					//computer movement conditions
					else if (a[0]==player&&a[1]==player&&a[2]!=player&&a[2]!=computer)
						a[2]=computer;
					else if (a[0]==player&&a[2]==player&&a[1]!=player&&a[1]!=computer)
						a[1]=computer;
					else if (a[2]==player&&a[1]==player&&a[0]!=player&&a[0]!=computer)
						a[0]=computer;
					else if (a[3]==player&&a[4]==player&&a[5]!=player&&a[5]!=computer)
						a[5]=computer;
					else if (a[4]==player&&a[5]==player&&a[3]!=player&&a[3]!=computer)
						a[3]=computer;
					else if (a[6]==player&&a[7]==player&&a[8]!=player&&a[8]!=computer)
						a[8]=computer;
					else if (a[6]==player&&a[8]==player&&a[7]!=player&&a[7]!=computer)
						a[7]=computer;
					else if (a[7]==player&&a[8]==player&&a[6]!=player&&a[6]!=computer)
						a[6]=computer;
					else if (a[0]==player&&a[3]==player&&a[6]!=player&&a[6]!=computer)
						a[6]=computer;
					else if (a[0]==player&&a[6]==player&&a[3]!=player&&a[3]!=computer)
						a[3]=computer;
					else if (a[3]==player&&a[6]==player&&a[0]!=player&&a[0]!=computer)
						a[0]=computer;
					else if (a[1]==player&&a[4]==player&&a[7]!=player&&a[7]!=computer)
						a[7]=computer;
					else if (a[4]==player&&a[7]==player&&a[1]!=player&&a[1]!=computer)
						a[1]=computer;
					else if (a[2]==player&&a[5]==player&&a[8]!=player&&a[8]!=computer)
						a[8]=computer;
					else if (a[2]==player&&a[8]==player&&a[5]!=player&&a[5]!=computer)
						a[5]=computer;
					else if (a[5]==player&&a[8]==player&&a[2]!=player&&a[2]!=computer)
						a[2]=computer;
					else if (a[0]==player&&a[4]==player&&a[8]!=player&&a[8]!=computer)
						a[8]=computer;
					else if (a[8]==player&&a[4]==player&&a[0]!=player&&a[0]!=computer)
						a[0]=computer;
					else if (a[2]==player&&a[4]==player&&a[6]!=player&&a[6]!=computer)
						a[6]=computer;
					else if (a[6]==player&&a[4]==player&&a[2]!=player&&a[2]!=computer)
						a[2]=computer;
					
				
					else if (a[0]==computer&&a[1]==computer&&a[2]!=player&&a[2]!=computer)
						a[2]=computer;
					else if (a[0]==computer&&a[2]==computer&&a[1]!=player&&a[1]!=computer)
						a[1]=computer;
					else if (a[2]==computer&&a[1]==computer&&a[0]!=player&&a[0]!=computer)
						a[0]=computer;
					else if (a[3]==computer&&a[4]==computer&&a[5]!=player&&a[5]!=computer)
						a[5]=computer;
					else if (a[4]==computer&&a[5]==computer&&a[3]!=player&&a[3]!=computer)
						a[3]=computer;
					else if (a[6]==computer&&a[7]==computer&&a[8]!=player&&a[8]!=computer)
						a[8]=computer;
					else if (a[6]==computer&&a[8]==computer&&a[7]!=player&&a[7]!=computer)
						a[7]=computer;
					else if (a[7]==computer&&a[8]==computer&&a[6]!=player&&a[6]!=computer)
						a[6]=computer;
					else if (a[0]==computer&&a[3]==computer&&a[6]!=player&&a[6]!=computer)
						a[6]=computer;
					else if (a[0]==computer&&a[6]==computer&&a[3]!=player&&a[3]!=computer)
						a[3]=computer;
					else if (a[3]==computer&&a[6]==computer&&a[0]!=player&&a[0]!=computer)
						a[0]=computer;
					else if (a[1]==computer&&a[4]==computer&&a[7]!=player&&a[7]!=computer)
						a[7]=computer;
					else if (a[4]==computer&&a[7]==computer&&a[1]!=player&&a[1]!=computer)
						a[1]=computer;
					else if (a[2]==computer&&a[5]==computer&&a[8]!=player&&a[8]!=computer)
						a[8]=computer;
					else if (a[2]==computer&&a[8]==computer&&a[5]!=player&&a[5]!=computer)
						a[5]=computer;
					else if (a[5]==computer&&a[8]==computer&&a[2]!=player&&a[2]!=computer)
						a[2]=computer;
					else if (a[0]==computer&&a[4]==computer&&a[8]!=player&&a[8]!=computer)
						a[8]=computer;
					else if (a[8]==computer&&a[4]==computer&&a[0]!=player&&a[0]!=computer)
						a[0]=computer;
					else if (a[2]==computer&&a[4]==computer&&a[6]!=player&&a[6]!=computer)
						a[6]=computer;
					else if (a[6]==computer&&a[4]==computer&&a[2]!=player&&a[2]!=computer)
						a[2]=computer;
					
					else if ((a[0]!=player&&a[0]!=computer)||(a[2]!=player&&a[2]!=computer)||(a[6]!=player&&a[6]!=computer)||(a[8]!=player&&a[8]!=computer))
					{
						while (true)
						{
							final int[] Choices = {0,2,6,8};
							x = Choices[rand.nextInt(Choices.length)];
							if (a[x]!=player&&a[x]!=computer)
							{
								a[x]=computer;
								break;
							}
						}
					}
					else if ((a[1]!=player&&a[1]!=computer)||(a[3]!=player&&a[3]!=computer)||(a[5]!=player&&a[5]!=computer)||(a[7]!=player&&a[7]!=computer))
						
					{
						while(true)
						{
					
							final int[] Choices = {1,3,5,7};
							x = Choices[rand.nextInt(Choices.length)];
							if (a[x]!=player&&a[x]!=computer)
							{
								a[x]=computer;
								break;
							}
						}
					}
					System.out.println(" ");
					System.out.println(" "+a[0]+"  |  "+a[1]+"  |  "+a[2]+" ");
					System.out.println(" "+a[3]+"  |  "+a[4]+"  |  "+a[5]+" ");
					System.out.println(" "+a[6]+"  |  "+a[7]+"  |  "+a[8]+" ");
					
					if ((a[0]==a[1]&&a[1]==a[2]&&a[2]==player)||(a[3]==a[4]&&a[4]==a[5]&&a[5]==player)||(a[6]==a[7]&&a[7]==a[8]&&a[8]==player)||(a[0]==a[4]&&a[4]==a[8]&&a[8]==player)||(a[2]==a[4]&&a[4]==a[6]&&a[6]==player)||(a[0]==a[3]&&a[3]==a[6]&&a[6]==player)||(a[1]==a[4]&&a[4]==a[7]&&a[7]==player)||(a[2]==a[5]&a[5]==a[8]&&a[8]==player))
					{
						System.out.print("You win!");
						
						break;
					}
					else if ((a[0]==a[1]&&a[1]==a[2]&&a[2]==computer)||(a[3]==a[4]&&a[4]==a[5]&&a[5]==computer)||(a[6]==a[7]&&a[7]==a[8]&&a[8]==computer)||(a[0]==a[4]&&a[4]==a[8]&&a[8]==computer)||(a[2]==a[4]&&a[4]==a[6]&&a[6]==computer)||(a[0]==a[3]&&a[3]==a[6]&&a[6]==computer)||(a[1]==a[4]&&a[4]==a[7]&&a[7]==computer)||(a[2]==a[5]&&a[5]==a[8]&&a[8]==computer))
					{
						System.out.print("Computer wins!");
						break;
					}
							
					//draw conditions
					else if((a[0]==player||a[0]==computer)&&(a[1]==player||a[1]==computer)&&(a[2]==player||a[2]==computer)&&(a[3]==player||a[3]==computer)&&(a[4]==player||a[4]==computer)&&(a[5]==player||a[5]==computer)&&(a[6]==player||a[6]==computer)&&(a[7]==player||a[7]==computer)&&(a[8]==player||a[8]==computer))
					{
						System.out.print("Draw!!");
						break;
					}
			}
			if (JOptionPane.showConfirmDialog(null, "Do you want to play again?", "Play again?", JOptionPane.YES_NO_OPTION)==1)
				break;//ask if he wants to play again
			
			}
			
		}
	}

Yes, I know the code could be better. My problem is I dont exactly know where to start. Do I make a seperate class for the GUI or change the actual code?

Recommended Answers

All 10 Replies

Ohhh that is some code:). You could have used the AI algorithm given for Tic Tac Toe game. But i dont think you will have a problem with gui. Ofcourse your GUI class will be really different from this code, but if you are allowed to use netbean IDE then GUI is not a problem for you. As long as your algorithm works your GUI will not give you that much of a problem. Where as if you have to make it from scratch then, you can change the texts on the boxes and disable them when they are selected. Hope this helps

Ohhh that is some code:). You could have used the AI algorithm given for Tic Tac Toe game. But i dont think you will have a problem with gui. Ofcourse your GUI class will be really different from this code, but if you are allowed to use netbean IDE then GUI is not a problem for you. As long as your algorithm works your GUI will not give you that much of a problem. Where as if you have to make it from scratch then, you can change the texts on the boxes and disable them when they are selected. Hope this helps

I dont think we are allowed to use NetBean, So I can make a seperate classfor the GUI? My main problem is not knowing where to start, but ll give it another shot tmrrw.

I use eclipse BTW

Hi,
Eclipse has that feature, where you design the GUI and the code is written automatically in the background. The only code you have to write will be the "actionPerformed" codes for buttons. In this way you have nice looking GUI in no time.

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;



public class GUI implements ActionListener {
	private JFrame window = new JFrame("Tic-Tac-Toe");
	private JButton button1 = new JButton("A");
	private JButton button2 = new JButton("B");
	private JButton button3 = new JButton("C");
	private JButton button4 = new JButton("D");
	private JButton button5 = new JButton("E");
	private JButton button6 = new JButton("F");
	private JButton button7 = new JButton("G");
	private JButton button8 = new JButton("H");
	private JButton button9 = new JButton("I");
	
	public GUI(){
		/*Create Window*/
		window.setSize(300,300);
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		window.setLayout(new GridLayout(3,3));
		
		/*Add Buttons To The Window*/
		window.add(button1);
		window.add(button2);
		window.add(button3);
		window.add(button4);
		window.add(button5);
		window.add(button6);
		window.add(button7);
		window.add(button8);
		window.add(button9);
		
		/*Add The Action Listener To The Buttons*/
		button1.addActionListener(this);
		button2.addActionListener(this);
		button3.addActionListener(this);
		button4.addActionListener(this);
		button5.addActionListener(this);
		button6.addActionListener(this);
		button7.addActionListener(this);
		button8.addActionListener(this);
		button9.addActionListener(this);
		
		/*Make The Window Visible*/
		window.setVisible(true);
		}
	@Override
	public void actionPerformed(ActionEvent arg0) {
		
	}

}

I've done the layout of what I want the GUI to look like hre, but what I want to know is how to adapt the code in the frst post to work with ths GUI.

P.S I checked, netbean is a no-no
PPS Sorry if I am being difficult.

And I must apoligise yet again, turns out we did not have to make the GUI an add on to what I made but rather as an extension to a code that my lecturer gave me. Im terribly sorry.

import javax.swing.JOptionPane;

public class tictactoe {

	/**
	 * Method used to draw the current status of the board in each turn
	 */
	public static void drawBoard(char board[], boolean endBool)
	{
		//print out the current status of the board
		System.out.println("   " + board[0] + " | " + board[1] + " | " + board[2]);
		System.out.println("  ---+---+---");
		System.out.println("   " + board[3] + " | " + board[4] + " | " + board[5]);
		System.out.println("  ---+---+---");
		System.out.println("   " + board[6] + " | " + board[7] + " | " + board[8]);
		System.out.println();
		
		if (endBool == false) //prevents printing the below content after the game is resolved
		{
			//print out the input map for the player
			System.out.println(">  0 | 1 | 2  <");
			System.out.println("> ---+---+--- <");
			System.out.println(">  3 | 4 | 5  <");
			System.out.println("> ---+---+--- <");
			System.out.println(">  6 | 7 | 8  <");
			System.out.println();
		}
	}
	
	/**
	 * Method used to check if input is within range (0-8) and if the cell is not occupied 
	 */
	public static boolean checkInput(int cell, char board[])
	{
		if (cell >= 0 && cell <= 8) //if within range
			if (board[cell] == ' ') //if the cell is empty
				return true;
		
		//otherwise display the message informing the player of incorrect input
		JOptionPane.showMessageDialog(null, "Incorrect value entered!");
		return false;
	}
	
	/**
	 * Method used to determine if anyone has made a line
	 */
	public static boolean checkWin(char board[], char token)
	{
		// [0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6] - win
		
		for (int i = 0; i <= 2; i++)
		{
			//horizontal lines
			if (board[i*3] == token && board[i*3+1] == token && board[i*3+2] == token) // ' X | X | X '
				return true;			
			
			//vertical lines
			else if (board[i] == token && board[i+3] == token && board[i+6] == token) // ' X - X - X '
				return true;
		}		
		
		//diagonal lines
		if (board[0] == token && board[4] == token && board[8] == token) // ' X \ X \ X '
			return true;
		else if (board[2] == token && board[4] == token && board[6] == token) // ' X / X / X '
			return true;
		
		//no line
		return false;		
	}
	
	/**
	 * Method used to calculate computer's move
	 */
	public static int compMove(char board[],char token)
	{
		//array of positions from the most wanted to the least desired
		int precedence[] = {4,0,2,6,8,1,3,5,7};		
		
		//runs twice, first to check if computer can complete a line, 
		//if not computer checks if it can block the player
		for (int twice = 1; twice <= 2; twice++)
		{
			for (int i = 0; i <= 2; i++) //used for vertical and horizontal lines check
			{
				//horizontal lines
				if (board[i*3] == token && board[i*3+1] == token && board[i*3+2] == ' ') // ' X | X | _ '
					return i*3+2; 
				else if (board[i*3] == token && board[i*3+1] == ' ' && board[i*3+2] == token) // ' X | _ | X '
					return i*3+1; 
				else if (board[i*3] == ' ' && board[i*3+1] == token && board[i*3+2] == token) // ' _ | X | X '
					return i*3;
				
				//vertical lines
				if (board[i] == token && board[i+3] == token && board[i+6] == ' ') // ' X - X - _ '
					return i+6;
				else if (board[i] == token && board[i+3] == ' ' && board[i+6] == token) // ' X - _ - X '
					return i+3;
				else if (board[i] == ' ' && board[i+3] == token && board[i+6] == token) // ' _ - X - X '
					return i;				
			} //end inner for
			
			//diagonal line '\'
			if (board[0] == token && board[4] == token && board[8] == ' ') // ' X \ X \ _ '
				return 8;
			else if (board[0] == token && board[4] == ' ' && board[8] == token) // ' X \ _ \ X '
				return 4;
			else if (board[0] == ' ' && board[4] == token && board[8] == token) // ' _ \ X \ X '
				return 0;
			
			//diagonal line '/'
			if (board[2] == token && board[4] == token && board[6] == ' ') // ' X / X / _ '
				return 6;
			else if (board[2] == token && board[4] == ' ' && board[6] == token) // ' X / _ / X '
				return 4;
			else if (board[2] == ' ' && board[4] == token && board[6] == token) // ' _ / X / X '
				return 2;
			
			//change over to check if computer needs to block player's potential lines
			if (token == 'O')
				token = 'X';
			else
				token = 'O';
		} //end outer for
		
		//if no line can be completed or blocked computer goes by the precedence array
		for (int i = 0; i < 9; i++) 
			if (board[precedence[i]] == ' ')
				return precedence[i];
		
		//all the positions are busy (a tie)
		return -1; 
	}
	
	/**
	 * Method used to output the final score and draw the board in its final state
	 */
	public static void showScore(int score, char board[])
	{
		System.out.println("***************\n");
		drawBoard(board, true); //draws the board in its final state
		switch (score)
		{
			case 0: //tie
				JOptionPane.showMessageDialog(null, "It is a tie!");
				break;
				
			case 1: //win
				JOptionPane.showMessageDialog(null, "Congratulations! You have won!");
				break;
				
			case 2: //loose
				JOptionPane.showMessageDialog(null, "Computer won! You loose!");
				break;
		}		
	}
	
	/**
	 * The main method where program is executed
	 */
	public static void main(String[] args) 
	{
		do // do-while loop used to let user run the program multiple times
		{			
		
		//variables declaration
		char board[] = new char[9]; //logical board
		for (int i = 0; i < 9; i++)
			board[i] = ' '; //logical board filled with initial 'empty' values
		int cell; //used to read player's input
		int compCell; //computer's chosen cell
		int option; //used to determine player's chosen option at the beginning:
					//0 = Yes, 1 = No, 2 = Cancel
		char playToken = 'X'; //used to determine player's token, 'X' or 'O'
		char compToken = 'O'; //used to determine computer's token
		boolean endBool = false; //used to determine if the game has been resolved
		
		//welcome message and option if player wants to go first
		option = JOptionPane.showConfirmDialog(null,"Welcome to \"Tic Tac Toe\"!" +
				"\nWould you like to go first?");			
		
		if (option == 0) //player chose 'yes'
		{
			playToken = 'X'; //player chose to go first, his token is 'X'
			compToken = 'O'; //resolves computer's token based on the player's one
		}
		else if (option == 1) //player chose 'no'
		{
			playToken = 'O'; //player chose to go second, his token is 'O'
			compToken = 'X'; //resolves computer's token based on the player's one
			board[compMove(board,compToken)] = compToken; //stores the input of computer's move
		}
		else //player chose 'cancel', option = 2
			System.exit(0); //terminates the program		
		
		System.out.println("***************");
		
		//main loop, the core of the program
		while (endBool == false)
		{		
			System.out.println();
			drawBoard(board, endBool); //draws the board in its current state
			
			do //makes sure the input is correct
				cell = Integer.parseInt(JOptionPane.showInputDialog
					("Choose the desired cell (0-8):")); //read player's input
			while (checkInput(cell, board) == false); 
			board[cell] = playToken; //stores the input in the logical board
			
			if (checkWin(board, playToken)) //checks if player has made a line
			{
				endBool = true; //exits the while loop
				showScore(1,board); //shows the score, game is over				
			} //end if
			
			else
			{
				compCell = compMove(board,compToken); //computer's move
				
				if (compCell == -1)
				{
					endBool = true; //exits the while loop
					showScore(0,board); //shows the score, game is over
					break;
				}
				
				board[compCell] = compToken; //stores the input of computer's move
			
				//print out the message informing the player of computer's move
				System.out.println("Computer has put his token on the positon number: " 
						+ compCell);
				
				if (checkWin(board, compToken)) //checks if computer has made a line
				{
					endBool = true; //exits the while loop					
					showScore(2,board);	//shows the score, game is over
				} //end if
				
				else
				{
					endBool = true;
					//checks if there is an empty cell 
					for (int i = 0; i < 9; i++)
						if (board[i] == ' ')
							endBool = false;
					
					if (endBool) //if there is no empty cell, then it is a tie
					{
						showScore(0,board); //shows the score, game is over
					}
					else
						System.out.println("Your turn.");
				} //end else
				
				
			} //end else
									
		} //end while
		
		//player has an option to rerun the game
		} while (JOptionPane.showConfirmDialog(null, "Would You like to go again?") == 0);
		
	} // end main method

} //end class

Ok that's fine but... what problems are you having then? You just posted code with no additional information.

Ok that's fine but... what problems are you having then? You just posted code with no additional information.

See that GUI code I made up there? I want to make that work with the code I just posted, but I dont know what to do next.

Can anyone send me a finished project (tictactoe). I would be very grateful :)

commented: No one is going to do yout work ofr you! -1

Can anyone send me a finished project (tictactoe). I would be very grateful :)

Do your own homework cheater. We don't give away homework. We help others do it and learn by doing it themselves.

I'm just interested. It's not my homework. I tried but I could not do it alone. but if can no problem .. just asking :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.