#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2014
    Posts
    1
    Rep Power
    0

    Why is my Tic Tac Toe (naughts and crosses) game not working properly?


    Hi, I am attempting to create a Tic Tac Toe (naughts and crosses) game and I seem to be having problems with its functionality.

    *Firstly: when playing the game, the game randomly freezes.It highlights the last button grey before freezing after the player clicks on three buttons in a row and won. After the game freezes,it cannot be closed unless the coding application(Eclipse) is closed, and the application game functions normally after Eclipse is opened normally.

    *Secondly: the computer mostly mostly does not play or does not play properly. Sometimes the computer displays its symbol
    (0)at non-highlighted buttons at the same time after the player clicked on three buttons in a row and won.

    *Thirdly: sometimes the buttons that are not in a row are highlighted as won, which is not meant to happen.

    here is the code written below:

    Code:
     import java.applet.Applet;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.Font;
    import java.awt.GridLayout;
    import java.awt.LayoutManager;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.BorderLayout;
    import java.text.Format;
    import java.util.Random;
    
    import javax.swing.*;
    
    
    
    public class TicTacToe extends JApplet implements ActionListener
    {
    
    
    	JButton squares[];
    	JButton newGame;
    	JLabel score;
    	JLabel wins;
    	JLabel loses;
    	int RemainingSquares=9;
    	int gamesWon;
    	int gamesLost;
    
    
    	public static void main(String[] args){
    		//Create an initialise the applet.
    		JApplet Applet = new TicTacToe();
    
    		//called by browser or applet to notify that the applet has
    		//been loaded onto the system. 
    		Applet.init();
    
    		/*called by browser or applet to inform that the applet must
    		 * start its execution.*/
    		Applet.start();
    
    		//creating frame to add contents 
    		JFrame Winframe = new JFrame("Tic Tac Toe applet and application");
    
    		//setting the frame to add the applet in the TicTacToe();
    		Winframe.setContentPane(Applet);
    
    		//applet exits when the frame has been closed
    		Winframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    		//sets the visibility of the frame to true to be seen by 
    		//users.
    		Winframe.setVisible(true);
    
    		//end bracket for main	
    	}
    
    	//used to add a JLabel with a text in them.
    	public TicTacToe(){
    
    		add(new JLabel("this is both an Applet and Application"));
    
    		//end bracket for TicTacToe sub class	
    	}
    
    	//init called by browser/applet to inform that the applet has been loaded.
    	public void init(){
    
    		/*gets the applet's content pane so that the contents can 
    		 * be assigned to it.*/
    		Container appContent = this.getContentPane();
    
    		//setting the size of applet pane to 300 by 300.
    		resize(300,300);
    
    
    		//set content pane background to BorderLayout
    		appContent.setLayout(new BorderLayout());
    
    		//sets colour to cyan
    		appContent.setBackground(Color.CYAN);
    
    		//sets font to serif, style italic and size 40 
    		Font app = new Font("Serif", Font.ITALIC,40);
    
    		//apply the font to the appContent
    		appContent.setFont(app);
    
    
    
    		//calling newGame button and assigning it the name 'New Game'
    		newGame=new JButton("New Game");
    
    		//adding actionListener to newGame button
    		newGame.addActionListener(this);
    
    		//storing text in the label called wins
    		wins=new JLabel("Won: ");
    
    		//storing text within label called loses
    		loses=new JLabel("Lost ");
    
    		//created new panel called topPanel
    		JPanel topPanel=new JPanel();
    
    		//set layout of topPanel to GridLayout
    		topPanel.setLayout(new GridLayout());
    
    
    		//adding the button newGame into the panel called topPanel
    		topPanel.add(newGame);
    
    		//sets the newGame button to horizontal at the 'center' (centre) of the frame.
    		newGame.setHorizontalAlignment(JButton.CENTER);
    
    		//setting size of the newGame button to 3,3.
    		newGame.setSize (3,3);
    
    		//adding the topPanel on the north part appContent
    		appContent.add(topPanel,"North");
    
    		//Jpanel called centerPanel created.
    		JPanel centerPanel=new JPanel();
    
    
    
    
    		//created a borderlayout called lay
    		GridLayout lay = new GridLayout(3,3);
    
    
    		//centerPanel assigned with borderlaytout
    		centerPanel.setLayout(lay); // FIX THIS CODE
    
    
    
    		//centerPanel added to the center in the appContent.
    		appContent.add(centerPanel,"Center");
    
    		//score label added text
    		score=new JLabel("Your turn!");
    
    		//score label added to the appContent on the south side.
    		appContent.add(score,"South");
    		appContent.add(wins,"West");
    
    		//an array called squares to hold reference to the 9 button in the Tic Tac Toe Game.
    		squares=new JButton[9];
    
    		for(int i=0; i<9;i++){
    
    			//creating new button for the array button (squares).
    			squares[i]=new JButton();
    
    			JButton one = new JButton();
    			JButton two = new JButton();
    			JButton three = new JButton();
    			JButton four = new JButton();
    			JButton five = new JButton();
    			JButton six = new JButton();
    			JButton seven = new JButton();
    			JButton eight = new JButton();
    			JButton nine = new JButton();
    
    
    			squares[i]= one;
    			squares[i]= two;
    			squares[i]= three;
    			squares[i]= four;
    			squares[i]= five;
    			squares[i]= six;
    			squares[i]= seven;
    			squares[i]= eight;
    			squares[i]= nine;
    
    
    			squares[i].addActionListener(this);
    
    
    			//sets the colour of the array buttons to orange.
    			squares[i].setBackground(Color.ORANGE);
    
    			//adds the array buttons (for the game) to be added to the center panel.
    			centerPanel.add(squares[i]);
    
    			// Create the the frame and set it's content pane
    			JFrame frame = new JFrame("TicTacToe");
    
    			//end bracket for for loop.	
    		}
    
    
    
    
    
    		//end bracket for init.	
    	}
    
    
    
    	@Override
    	public void actionPerformed(ActionEvent e) {
    		// TODO Auto-generated method stub
    
    		JButton theButton = (JButton) e.getSource();
    
    		//  New Game button
    		if (theButton ==newGame){
    
    			for(int i=0;i<9;i++){
    				newGame.setEnabled(true);
    
    				//game squares are enabled, text are nothing and background to orange.
    				squares[i].setEnabled(true);
    				squares[i].setText("");
    				squares[i].setBackground(Color.ORANGE);
    				//end bracket for for loop
    			}
    
    			//games squares will be returned to normal. the game button will be enabled to
    			//play again. 
    			RemainingSquares=9;
    			score.setText("Your turn!");
    			newGame.setEnabled(true); 
    
    			return;
    		}
    
    		String winner="";
    
    		for(int i=0;i<9;i++){
    
    			//if the buttons function are all from the game buttons, then...
    			if(theButton==squares[i]){
    
    
    				//the square's text to 'X'.
    				squares[i].setText("X");
    
    				//the buttons are not enabled once it has been clicked once.
    				squares[i].setEnabled(false);
    
    
    				if(!"".equals(winner)){
    
    					endTheGame();
    				}
    				else
    				{
    
    
    					computerMove();
    					winner = lookForWinner();
    
    					if ( !"".equals(winner))
    					{
    						endTheGame();
    
    						//end bracket for if statement !"".equals(winner)
    					}
    					//end bracket for else statement
    				}
    				break;
    				//if statement for 'if theButton==squares[i].	
    			}
    
    			//for loop end bracket	
    		}
    		//if statement- winner=="x"	
    		if(winner=="x"){
    			score.setText("you win human");
    			//increment win counter
    			for(int i=0;i<9;i++)
    			{
    				gamesWon*=+1;
    			}
    			wins.setText(" Won: " +gamesWon);
    
    		}	
    
    
    		else if(winner.equals("O"))
    		{
    			score.setText("You lost!");
    			//increment lose counter
    			//INSERT YOUR CODE HERE
    			for(int i=0;i<9;i++)
    			{
    				gamesLost*=+1;
    			}
    
    			loses.setText("Lose:"+ gamesLost);
    
    			//end bracket for winner.equals("o")	
    		}
    		else if (winner.equals("T"))
    		{
    			//score text set to 'it's a tie!'
    			score.setText("It's a tie!");
    
    		}
    
    
    
    	}
    
    	String lookForWinner(){
    
    		String theWinner="";
    
    		RemainingSquares--;
    
    		if(RemainingSquares==0){
    
    			return "T";
    			//end if statement for RemainingSquares==0	
    		}
    
    
    
    
    		//checks three buttons in row. if they all have the same symbols then it will display
    		//a message as well as highlighting them in light blue.
    		if(!squares[0].getText().equals("") && squares[0].getText().equals(squares[1].getText()) && 
    				squares[0].getText().equals(squares[2].getText())){
    
    			//gets the text from the square with symbols in a row.
    			squares[0].getText();
    			//displays a message 
    			theWinner="the winner is:"+squares[0];
    
    			highlightWinner(0,1,2);
    
    		}
    
    		else if (!squares[2].getText().equals("") &&
    				squares[2].getText().equals(squares[3].getText()) &&
    				squares[2].getText().equals(squares[4].getText()) ) {
    
    
    			squares[2].getText();
    			theWinner="the winner is:"+squares[2];
    			highlightWinner(2,3,4);
    
    
    		}
    		else if (!squares[3].getText().equals("")
    				&& squares[3].getText().equals(squares[4].getText())
    				&& squares[3].getText().equals(squares[5].getText())) {
    
    			squares[3].getText();
    			theWinner="the winner is:"+ squares[3];
    			highlightWinner(3, 4, 5);
    		}
    
    		else if (!squares[6].getText().equals("")
    				&& squares[6].getText().equals(squares[7].getText())
    				&& squares[6].getText().equals(squares[8].getText())) {
    			squares[6].getText();
    			theWinner="the winner is:"+ squares[6];
    			highlightWinner(6, 7, 8);
    
    		} else if (!squares[0].getText().equals("")
    				&& squares[0].getText().equals(squares[3].getText())
    				&& squares[0].getText().equals(squares[6].getText())) {
    			squares[0].getText();
    			theWinner="the winner is:"+squares[0];
    			highlightWinner(0, 3, 6);
    
    		} else if (!squares[1].getText().equals("")
    				&& squares[1].getText().equals(squares[4].getText())
    				&& squares[1].getText().equals(squares[7].getText())) {
    			squares[1].getText();
    			theWinner="the winner is:"+squares[1];
    			highlightWinner(1, 4, 7);
    
    		} else if (!squares[2].getText().equals("")
    				&& squares[2].getText().equals(squares[5].getText())
    				&& squares[2].getText().equals(squares[8].getText())) {
    			squares[2].getText();
    			theWinner="the winner is:"+squares[2];;
    			highlightWinner(2, 5, 8);
    
    		} else if (!squares[0].getText().equals("")
    				&& squares[0].getText().equals(squares[4].getText())
    				&& squares[0].getText().equals(squares[8].getText())) {
    			squares[0].getText();
    			theWinner="the winner is:"+squares[0];
    			highlightWinner(0, 4, 8);
    
    		} else if (!squares[2].getText().equals("")
    				&& squares[2].getText().equals(squares[4].getText())
    				&& squares[2].getText().equals(squares[6].getText())) {
    
    			squares[2].getText();
    			theWinner="the winner is:"+ squares[2];
    			highlightWinner(2, 4, 6);
    		}
    
    
    		return theWinner;
    
    
    	}
    	//codes computer's moves in the 
    	public void computerMove(){
    		// TODO Auto-generated method stub
    
    		//chooses random square variable
    		Random choose=new Random();
    
    		//computer chooses 1 square at a time
    		int compChoose=1;
    
    		//computer can only choose from 1 up to 9 squares
    		compChoose= choose.nextInt(9);
    
    		for(int i =0;i<compChoose;i++)
    		{
    			int SelectedSquare;
    			//computer attemts to find an empty two '0' in a row.
    			SelectedSquare=findEmptySquare("0");
    
    			//prevents player by getting 3 squares by inserting 0 next to players 2 in row column/row.
    			if(SelectedSquare==0){
    				SelectedSquare=findEmptySquare("x");
    
    			}
    			//attempts to occupy cnetral square if selectedsquare is -1.
    			if(SelectedSquare==-1 && squares[4].getText().equals("")){
    				SelectedSquare=4;
    
    			}
    
    			//if central square cannot be chosen then choose random square. 
    			if(SelectedSquare==-1){
    
    				SelectedSquare=getRandomSquare();
    				squares[SelectedSquare].setText("0");
    				squares[SelectedSquare].setEnabled(false);
    			}
    		}
    	}
    
    
    	//checks for two squares with the same label and an empty square
    
    	//x - for user . Y - for computer.
    	int findEmptySquare(String Player){
    
    		int Weight[]= new int[9];
    
    
    		for(int i=0;i<9;i++){
    
    			if(squares[i].getText().equals("O")){
    				Weight[i]=-1;
    			}
    			else if(squares[i].getText().equals("X")){
    				Weight[i]=1;	
    			}
    			else{
    				Weight[i]=0;
    			}
    		}
    		int twoWeights = Player.equals("O") ? -2 : 2;
    
    		// See if row 1 has the same 2 squares and a blank
    		if ( Weight[0] + Weight[1] + Weight[2] == twoWeights ) {
    
    			if(Weight[0]==0){
    				return 0;	
    			}
    			else if(Weight[1]==1){
    				return 1;
    
    			}
    			else{
    				return 2;
    			}
    
    		}
    		// See if row 2 has the same 2 squares and a blank
    		if(Weight[3]+Weight[4]+Weight[5]==twoWeights){
    			if ( Weight[3] == 0 )
    				return 3;
    			else if ( Weight[4] == 0 )
    				return 4;
    			else
    				return 5;
    		}
    		// See if row 3 has the same 2 squares and a blank
    		if ( Weight[6] + Weight[7] +Weight[8] == twoWeights ) {
    			if ( Weight[6] == 0 )
    				return 6;
    			else if ( Weight[7] == 0 )
    				return 7;
    			else
    				return 8;
    
    		}
    		// See if column 1 has the same 2 squares and a blank
    		if ( Weight[0] + Weight[3] + Weight[6] == twoWeights ) {
    			if ( Weight[0] == 0 )
    				return 0;
    			else if ( Weight[3] == 0 )
    				return 3;
    			else
    				return 6;
    		}
    		// See if column 2 has the same 2 squares and a blank
    		if ( Weight[1] +Weight[4] + Weight[7] == twoWeights ) {
    			if ( Weight[1] == 0 )
    				return 1;
    			else if ( Weight[4] == 0 )
    				return 4;
    			else
    				return 7;
    		}
    		// See if column 3 has the same 2 squares and a blank
    		if ( Weight[2] + Weight[5] + Weight[8] == twoWeights ) {
    			if ( Weight[2] == 0 )
    				return 2;
    			else if ( Weight[5] == 0 )
    				return 5;
    			else
    				return 8;
    		}
    		// See if diagonal 1 has the same 2 squares and a blank
    		if ( Weight[0] + Weight[4] + Weight[8] == twoWeights ) {
    			if ( Weight[0] == 0 )
    				return 0;
    			else if ( Weight[4] == 0 )
    				return 4;
    			else
    				return 8;
    
    		}           // See if diagonal 1 has the same 2 squares and a blank
    		if ( Weight[2] + Weight[4] + Weight[6] == twoWeights ) {
    			if ( Weight[2] == 0 )
    				return 2;
    			else if ( Weight[4] == 0 )
    				return 4;
    			else
    				return 6;
    		}
    		// do not have the same two neighbors
    		return -1;
    
    	}
    
    
    	//selects an empty square and randomly returns a randomly selected squares.
    	int getRandomSquare()
    	{
    		boolean getEmptySquare=false;
    		int selectedSquare=-1;
    
    		do{
    			selectedSquare=(int) (Math.random()*9);
    
    			if(squares[selectedSquare].getText().equals("")){
    				getEmptySquare=true;
    
    			}
    
    		} while(!getEmptySquare);
    
    		return selectedSquare;
    
    
    
    	}
    
    	//highlights the colour to light blue when the a player wins.
    	void highlightWinner(int win1, int win2, int win3){
    		squares[win1].setBackground(Color.CYAN);
    		squares[win2].setBackground(Color.CYAN);
    		squares[win3].setBackground(Color.CYAN);
    	}
    
    	//Disables squares and enable New Game button	
    	void endTheGame(){
    		for(int i=0;i<9;i++){
    			squares[i].setEnabled(false);
    		}
    		// Enable the new game button
    		newGame.setEnabled(true);
    	}
    }
  2. #2
  3. Contributing User
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Aug 2010
    Location
    Eastern Florida
    Posts
    3,716
    Rep Power
    348
    the game randomly freezes
    Sounds like there is an infinite loop. Try debugging the code by adding some println() statements in all the loops to see which one is going forever.
  4. #3
  5. Lord of the Dance
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Oct 2003
    Posts
    3,696
    Rep Power
    1959
    I suggest you use the debugger in Eclipse and go through the program step-by-step.

    E.g. set a breakpoint where the function start when a the player win and then start the program in debug mode.

    This should hopefully tell where it goes wrong.

IMN logo majestic logo threadwatch logo seochat tools logo