There's no such thing as a stupid question, but they're the easiest to answer.
JoinTour
Login
 
Tag Cloud
audio avg avg 8 bios boot browser bsod computer cpu crash css dell desktop driver dvd email error excel explorer firefox firefox 3 freeze game graphics hard drive hardware help please hijackthis hjt hjt log install internet internet explorer itunes javascript lan laptop malware missing monitor msn network networking openoffice outlook outlook 2003 outlook express php popups problem problems router seo slow sound sp3 spyware startup trojan usb video virtumonde virus vista vundo windows windows vista windows xp wireless word
Software Development
Search
Search in:
 
Advanced Search
Tech Support Guy Forums > Software & Hardware > Software Development >
Tic Tac Toe in Java


HELLO AND WELCOME! Before you can post your question, you'll have to register -- it's completely free! Click here to join today! We highly recommend that you print a copy of our Guide for New Members. Enjoy!

 
Thread Tools
lilLB's Avatar
Computer Specs
Senior Member with 184 posts.
 
Join Date: Mar 2006
Location: Massachusetts
Experience: Intermediate
17-May-2008, 10:30 AM #1
Cool Tic Tac Toe in Java
Gotta make a tic tac toe game in java
The user has to be allowed to choose a 3by3, 4by4, or 5by5 game board
i think i've got that part down and I've gotten the x's and o's to show when u click the board but... i can't figure out how to determine who wins
if anyone can think of a way to determine the winner no matter what size board (eg 3 in a row for 3by3 or 5 in a row for 5by5) don't need to write the code for me just give me an idea of a good way to do it
thanks here's my code:
Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class TicTacToe implements ActionListener {
	
	
	private JFrame window = new JFrame("Tic-Tac-Toe");
	private JPanel inputPanel = new JPanel();
	private JPanel boardPanel = new JPanel();
	private JButton button3 = new JButton("3 by 3");
	private JButton button4 = new JButton("4 by 4");
	private JButton button5 = new JButton("5 by 5");
	private JLabel label = new JLabel ("Click a button to choose game board size:");
	private JButton buttons[][];
	private int boardSize=0;
	private int count = -1;
	private String letter = "";
	private boolean win = false;

	public TicTacToe(){
	//Create Window
	window.setSize(500,500);
	window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	
	
	//Add Label and buttons to inputPanel
	inputPanel.add(label);
	inputPanel.add(button3);
	inputPanel.add(button4);
	inputPanel.add(button5);
	button3.addActionListener(this);
	button4.addActionListener(this);
	button5.addActionListener(this);
	inputPanel.setSize(500,200);
	window.add(inputPanel,"North");
	
	
	
	//Make The Window Visible
	window.setVisible(true);
	}
	
	/**
	 When an object is clicked, perform an action.
	 @param a action event object
	 */
	public void actionPerformed(ActionEvent a) {
		if(count==-1){
			letter="-";
			count=0;
		}
		else{
		count++;
		
		//Calculate whose turn it is
		
		if(count % 2 == 0){
			letter = "O";
		} else {
			letter = "X";
		}
		}
		
		if (a.getSource() == button3) {
			boardSize=3;
		}
		else if (a.getSource()== button4){
			boardSize=4;
		}
		else if (a.getSource() == button5){
			boardSize=5;
		}
		if ((a.getSource() == button3)||(a.getSource()==button4)||(a.getSource()==button5)){
			button3.setEnabled(false);
			button4.setEnabled(false);
			button5.setEnabled(false);
			buttons = new JButton[boardSize][boardSize];
			for(int i=0; i<boardSize; i++)
				for (int j=0; j<boardSize; j++){
					buttons[i][j] = new JButton();
					boardPanel.add(buttons[i][j]);
					buttons[i][j].addActionListener(this);
				}
			
			boardPanel.setSize(300,300);
			boardPanel.setLayout(new GridLayout(boardSize,boardSize));
			window.add(boardPanel,"Center");
		}
		
		//Write the letter to the button and deactivate it
		 JButton pressedButton = (JButton)a.getSource(); 
		 pressedButton.setText(letter);
		 pressedButton.setEnabled(false);
		
		//Determine winner
		
		
		//Show a dialog when game is over
		if(win == true){
			JOptionPane.showMessageDialog(null, letter + " wins the game!");
			System.exit(0);
		} else if(count == (boardSize*boardSize) && win == false){
			JOptionPane.showMessageDialog(null, "The game was tie!");
			System.exit(0);
		}	
		
	}
	
	public static void main(String[] args){
		TicTacToe starter = new TicTacToe();
	}
}
Chicon's Avatar
Computer Specs
Distinguished Member with 6,321 posts.
 
Join Date: Jul 2004
Location: 50° 34' 07.13" N - 04° 10' 23.
Experience: Second socks retriever
17-May-2008, 01:51 PM #2
Hi lilLB,

Just write a method that will pass as arguments the x and y of the last button pressed, that will browse the array of buttons (horizontally, vertically and diagonally) from the passed location and that will return a boolean set to true if the player won.
There's a getText method on the JButton you may use to compare the button letter.
Also, when you initialize the game buttons, you may use the setName method to give each button a specific name that may be used to determine its location on the board.
Example :
Code:

for (int i=0; i<boardSize; i++) {
    for (int j=0; j<boardSize; j++){
        buttons[i][j] = new JButton();
        boardPanel.add(buttons[i][j]);
        buttons[i][j].addActionListener(this);
        buttons[i][j].setName(String.valueOf((i*10)+j);
    }
}
In the actionPerformed method, you retrieve the x and y of the pressed button like this :
Code:

JButton pressedButton = (JButton)a.getSource(); 
pressedButton.setText(letter);
pressedButton.setEnabled(false);
int value = Integer.parseInt(pressedButton.getName());
int x = value / 10;
int y = value % 10; 
__________________
for ( ; ; ) ;

Examinations time is coming, take a Java beta exam and get a belt !
lilLB's Avatar
Computer Specs
Senior Member with 184 posts.
 
Join Date: Mar 2006
Location: Massachusetts
Experience: Intermediate
17-May-2008, 04:32 PM #3
awesome thanks for the help ill try it out
Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are Off
Refbacks are Off

You Are Using:
Server ID
Advertisements do not imply our endorsement of that product or service.
All times are GMT -4. The time now is 12:37 AM.
Copyright © 1996 - 2008 TechGuy, Inc. All rights reserved.
Powered by vBulletin, Copyright © 2000 - 2008, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0
Powered by Cermak Technologies, Inc.