Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Tic Tac Toe help

Im looking for the simpliest TTT source code, 3x3 matrix...Human vs Human. If anyone have it, please show me the script.
Any replyes will be really appreciated! ;)
[173 byte] By [rupa] at [2007-11-11 7:45:58]
# 1 Re: Tic Tac Toe help
Take a look:

http://forum.java.sun.com/thread.jspa?threadID=686472&messageID=3995002
nspils at 2007-11-11 22:37:25 >
# 2 Re: Tic Tac Toe help
"Take a look:

http://forum.java.sun.com/thread.js...ssageID=3995002"

Thank You, but it doesnt have 3x3 matrix and i would really appreciate if it had loops...
rupa at 2007-11-11 22:38:25 >
# 3 Re: Tic Tac Toe help
Take a look:
http://forum.java.sun.com/thread.jspa?threadID=698195
destin at 2007-11-11 22:39:24 >
# 4 Re: Tic Tac Toe help
This is a hybrid.
It acts like an applet in a browser and as an application when started from the command prompt.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
* A tictactoe button
*/
class TTTBtn extends JButton {
private int btnNo=-1;
private boolean hit=false;
private int value=-1;
public TTTBtn (int btnNo) {
super();
this.btnNo=btnNo;
}
public void setHit (boolean p1p2) {
super.setText(p1p2 ? "X" : "O");
value= p1p2 ? 1 : 4;
}
public int getValue() {
return value;
}
public boolean isHit () {
return value > 0;
}
public void reset() {
setText("");
value=-1;
}
public int getButtonNo () {
return btnNo;
}
}
/**
* A tictactoe applet
*/
public class TicTacToe
extends JApplet
implements ActionListener {

JLabel messagesLabel = new JLabel("X goes first");
JPanel displayPanel = new JPanel(new GridLayout(3, 3));
private TTTBtn[] bb = new TTTBtn[9];
private int [][] winLine={
{0,1,2}, // horizontal
{3,4,5},
{6,7,8},
{0,3,6}, // vertical
{1,4,7},
{2,5,8},
{0,4,8}, // diagonal
{6,4,2}
};
private JButton resetBtn=new JButton("Reset");
private boolean player1 = true;

public void init() {
messagesLabel.setOpaque(true);
messagesLabel.setHorizontalAlignment(SwingConstants.CENTER);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(messagesLabel, BorderLayout.NORTH);
getContentPane().add(resetBtn, BorderLayout.SOUTH);
getContentPane().add(displayPanel, BorderLayout.CENTER);

resetBtn.addActionListener(this);

for (int i = 0; i < 9; i++) {
bb[i] = new TTTBtn(i);
bb[i].addActionListener(this);
displayPanel.add(bb[i]);
}

}
public int getWinner() {
for (int i=0; i<winLine.length; i++) {
int ret = lineWin(winLine[i]);
if (ret > 0) return ret;
}
return -1;
}
private int lineWin(int [] pos) {
int sum=
bb[pos[0]].getValue()+
bb[pos[1]].getValue()+
bb[pos[2]].getValue();
if (sum==3) return 1;
if (sum==12) return 2;
return -1;
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == resetBtn) {
resetGame();
}
else if (e.getSource()instanceof TTTBtn) {
TTTBtn btn = (TTTBtn) e.getSource();
if (!btn.isHit()) {
if (haveWinner(btn)) {
enableButtons(false);
}
}
}
}

private void enableButtons(boolean enabled) {
for (int i=0; i<bb.length; i++) {
bb[i].setEnabled(enabled);
}
}

private boolean haveWinner(TTTBtn btn) {
bb[btn.getButtonNo()].setHit(player1);
int winner = getWinner();
if (winner > 0) {
messagesLabel.setBackground(Color.green);
messagesLabel.setText("Player " + winner + " wins");
return true;
}
else {
player1 = !player1;
return false;
}
}

private void resetGame() {
for (int i=0; i<bb.length; i++) {
bb[i].reset();
}
player1=true;
messagesLabel.setBackground(Color.lightGray);
messagesLabel.setText("X goes first");
enableButtons(true);
}
/**
* Test driver main
*/
public static void main(String[] args) {
JFrame f=new JFrame("Tic Tac Toe");
f.getContentPane().setLayout(new GridLayout());
TicTacToe ttt=new TicTacToe();
f.getContentPane().add(ttt);
f.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
System.exit(0);
}
});
ttt.init();
f.setBounds(100,100,300,270);
f.setVisible(true);
}
}
sjalle at 2007-11-11 22:40:24 >
# 5 Re: Tic Tac Toe help
This is a hybrid.
It acts like an applet in a browser and as an application when started from the command prompt.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
* A tictactoe button
*/
class TTTBtn extends JButton {
private int btnNo=-1;
private boolean hit=false;
private int value=-1;
public TTTBtn (int btnNo) {
super();
this.btnNo=btnNo;
}
public void setHit (boolean p1p2) {
super.setText(p1p2 ? "X" : "O");
value= p1p2 ? 1 : 4;
}
public int getValue() {
return value;
}
public boolean isHit () {
return value > 0;
}
public void reset() {
setText("");
value=-1;
}
public int getButtonNo () {
return btnNo;
}
}
/**
* A tictactoe applet
*/
public class TicTacToe
extends JApplet
implements ActionListener {

JLabel messagesLabel = new JLabel("X goes first");
JPanel displayPanel = new JPanel(new GridLayout(3, 3));
private TTTBtn[] bb = new TTTBtn[9];
private int [][] winLine={
{0,1,2}, // horizontal
{3,4,5},
{6,7,8},
{0,3,6}, // vertical
{1,4,7},
{2,5,8},
{0,4,8}, // diagonal
{6,4,2}
};
private JButton resetBtn=new JButton("Reset");
private boolean player1 = true;

public void init() {
messagesLabel.setOpaque(true);
messagesLabel.setHorizontalAlignment(SwingConstants.CENTER);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(messagesLabel, BorderLayout.NORTH);
getContentPane().add(resetBtn, BorderLayout.SOUTH);
getContentPane().add(displayPanel, BorderLayout.CENTER);

resetBtn.addActionListener(this);

for (int i = 0; i < 9; i++) {
bb[i] = new TTTBtn(i);
bb[i].addActionListener(this);
displayPanel.add(bb[i]);
}

}
public int getWinner() {
for (int i=0; i<winLine.length; i++) {
int ret = lineWin(winLine[i]);
if (ret > 0) return ret;
}
return -1;
}
private int lineWin(int [] pos) {
int sum=
bb[pos[0]].getValue()+
bb[pos[1]].getValue()+
bb[pos[2]].getValue();
if (sum==3) return 1;
if (sum==12) return 2;
return -1;
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == resetBtn) {
resetGame();
}
else if (e.getSource()instanceof TTTBtn) {
TTTBtn btn = (TTTBtn) e.getSource();
if (!btn.isHit()) {
if (haveWinner(btn)) {
enableButtons(false);
}
}
}
}

private void enableButtons(boolean enabled) {
for (int i=0; i<bb.length; i++) {
bb[i].setEnabled(enabled);
}
}

private boolean haveWinner(TTTBtn btn) {
bb[btn.getButtonNo()].setHit(player1);
int winner = getWinner();
if (winner > 0) {
messagesLabel.setBackground(Color.green);
messagesLabel.setText("Player " + winner + " wins");
return true;
}
else {
player1 = !player1;
return false;
}
}

private void resetGame() {
for (int i=0; i<bb.length; i++) {
bb[i].reset();
}
player1=true;
messagesLabel.setBackground(Color.lightGray);
messagesLabel.setText("X goes first");
enableButtons(true);
}
/**
* Test driver main
*/
public static void main(String[] args) {
JFrame f=new JFrame("Tic Tac Toe");
f.getContentPane().setLayout(new GridLayout());
TicTacToe ttt=new TicTacToe();
f.getContentPane().add(ttt);
f.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
System.exit(0);
}
});
ttt.init();
f.setBounds(100,100,300,270);
f.setVisible(true);
}
}

Thx man, but i want to use simpliest codes like these ones...What you wrote fot me is just to hard :)...I'm a begginer...

import java.awt.*;
import hsa.Console;

public class MatrixMulty
{
static Console c; // The output console

public static void main (String[] args)
{
c = new Console ();

//Inputs
int[] [] m1 = new int [3] [3];
int[] [] m2 = new int [3] [3];
int[] [] m3 = new int [3] [3];

//Inputs Matrix A
for (int row = 0 ; row < 3 ; row++)
{
for (int col = 0 ; col < 3 ; col++)
{

c.println ("Please enter your numbers for Matrix A");
m1 [row] [col] = c.readInt ();

}
}
c.println ("");
c.println ("");

//Inputs Matrix B
for (int row = 0 ; row < 3 ; row++)
{
for (int col = 0 ; col < 3 ; col++)
{

c.println ("Please enter your numbers for Matrix B");
m2 [row] [col] = c.readInt ();

}
}
c.println ("");
c.println ("");

//Menu
while (true)
{
int choice;
c.println ("Enter 1 for Adding");
c.println ("Enter 2 for Subtraction");
c.println ("Enter 3 for Multiplication");
c.println ("Enter 4 EXIT");
choice = c.readInt ();

//Adding
if (choice == 1)
{
c.println ("Adding");
for (int a = 0 ; a < 3 ; a++)
{
for (int b = 0 ; b < 3 ; b++)
{
m3 [a] [b] = m1 [a] [b] + m2 [a] [b];

}
}
c.println (m3 [0] [0] + " " + m3 [0] [1] + " " + m3 [0] [2] + " ");
c.println (m3 [1] [0] + " " + m3 [1] [1] + " " + m3 [1] [2] + " ");
c.println (m3 [2] [0] + " " + m3 [2] [1] + " " + m3 [2] [2] + " ");

c.println ("");
c.println ("");

}

//Subtraction
else if (choice == 2)
{
c.println ("Subtraction");
for (int a = 0 ; a < 3 ; a++)
{
for (int b = 0 ; b < 3 ; b++)
{
m3 [a] [b] = m1 [a] [b] - m2 [a] [b];

}
}
c.println (m3 [0] [0] + " " + m3 [0] [1] + " " + m3 [0] [2] + " ");
c.println (m3 [1] [0] + " " + m3 [1] [1] + " " + m3 [1] [2] + " ");
c.println (m3 [2] [0] + " " + m3 [2] [1] + " " + m3 [2] [2] + " ");

c.println ("");
c.println ("");
}

//Multiplication
else if (choice == 3)
{
c.println ("Multiplication");
for (int a = 0 ; a < 3 ; a++)
{
for (int b = 0 ; b < 3 ; b++)
{
int sum = 0;
for (int i = 0 ; i < 3 ; i++)
{
sum += m1 [a] [i] * m2 [i] [b];

}
m3 [a] [b] = sum;
}
}

c.println (m3 [0] [0] + " " + m3 [0] [1] + " " + m3 [0] [2] + " ");
c.println (m3 [1] [0] + " " + m3 [1] [1] + " " + m3 [1] [2] + " ");
c.println (m3 [2] [0] + " " + m3 [2] [1] + " " + m3 [2] [2] + " ");

c.println ("");
c.println ("");

//EXIT
if (choice == 4)
{

System.exit (4);
}
rupa at 2007-11-11 22:41:28 >
# 6 Re: Tic Tac Toe help
Well, if you want to do this without a GUI then I don't think the code will be any simpler (plus the game will suck).
sjalle at 2007-11-11 22:42:32 >
# 7 Re: Tic Tac Toe help
Here's what you want in an application (don't know why you want an application though...)
import javax.swing.JOptionPane;

public class TicTacToe {
static final String PLAYER1 = "X";
static final String PLAYER2 = "O";
static final String EMPTY = "-";

static String[][] board = new String[3][3];

static int turn = 0;

static public void init() {
for (int x = 0; x < 3; x++) {
for (int y = 0; y < 3; y++) {
board[x][y] = new String(EMPTY);
}
}
}

static public void getMove(int row, int col) {
if (board[row][col].equals(EMPTY)) {
board[row][col] = (turn % 2 == 0 ? PLAYER1 : PLAYER2);
turn++;
}
}

static public void printBoard() {
for (int x = 0; x < 3; x++) {
for (int y = 0; y < 3; y++) {
System.out.print(board[x][y]);
}
System.out.println();
}
System.out.println();
}

static public String winner() {
for (int i = 0; i < board.length; i++) {
/** check horizontally */
if (board[i][0].equals(board[i][1]) &&
board[i][0].equals(board[i][2])) {
if (!board[i][0].equals(EMPTY)) {
return board[i][0];
}
}
/** check vertically */
if (board[0][i].equals(board[1][i]) &&
board[0][i].equals(board[2][i])) {
if (!board[0][i].equals(EMPTY)) {
return board[0][i];
}
}
}

/** check diagonally */
if (board[0][0].equals(board[1][1]) &&
board[0][0].equals(board[2][2])) {
if (!board[0][0].equals(EMPTY)) {
return board[0][0];
}
}
if (board[0][2].equals(board[1][1]) &&
board[0][2].equals(board[2][0])) {
if (!board[0][2].equals(EMPTY)) {
return board[0][2];
}
}
return EMPTY;
}

static public void main(String[] args) {
init();

System.out.println("Welcome to Tic-Tac-Toe.");

do {
int row = Integer.parseInt(JOptionPane.showInputDialog(
"Enter the row you wish to move in."));
int column = Integer.parseInt(JOptionPane.showInputDialog(
"Enter the column you wish to move in."));
getMove(row, column);
printBoard();
} while(winner().equals(EMPTY));

System.out.println("PLAYER " + ((turn - 1) % 2 + 1) + " WINS!!");
}
}
destin at 2007-11-11 22:43:30 >
# 8 Re: Tic Tac Toe help
Destin. Thank You man. Thats i really what i was looking for! But some parts i dont get though...
1)Can you explain briefly each Static Public, what it does ( i get it but i want to make sure :) )
2)System.out.println("PLAYER " + ((turn - 1) % 2 + 1) + " WINS!!"); Dont get the calculations inside the brackets)
3) If its not hard for you, state all methods that you have used

I would really appreciate your support for a newb like me :)
rupa at 2007-11-11 22:44:27 >
# 9 Re: Tic Tac Toe help
1. Can you explain briefly each Static Public, what it does
public makes it so other classes can access the methods
static is a bit harder to explain, but everything in the wrapper class needs to be static.

Useful links:
The Java(tm) Tutorial: Controlling Access to Members of a Class (http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html)
Java Glossary: public (http://mindprod.com/jgloss/public.html)
Java Glossary: static (http://mindprod.com/jgloss/static.html)

2.System.out.println("PLAYER " + ((turn - 1) % 2 + 1) + " WINS!!"); Dont get the calculations inside the brackets)
Yeah, it's ugly. Basically, the turn was just incremented, so we're one over. So we need to subtract 1. Then, % 2 will give us the remainder (0 if player 1 wins, 1 if player 2 wins) then, we need to add 1 so it will be 1 or 2 instead of 0 or 1.

3. If its not hard for you, state all methods that you have used
??
destin at 2007-11-11 22:45:36 >
# 10 Re: Tic Tac Toe help
Thank you again, but what if the game is a Tie? This script doesn't have a Tie :(
I am sorry fot these stupid questions, but i really want to understand the prog..i have a Q if you dont mind answering them..

1) What "static int turn = 0;" stand for??
rupa at 2007-11-11 22:46:31 >
# 11 Re: Tic Tac Toe help
@Thank you again, but what if the game is a Tie? This script doesn't have a Tie :(
So add it.

@What "static int turn = 0;" stand for??
It represents whose turn it is (ie. player1 or player2)

@I am sorry fot these stupid questions, but i really want to understand the prog..i have a Q if you dont mind answering them..
If you have a question, ask it. That's what this forum is for.
destin at 2007-11-11 22:47:34 >
# 12 Re: Tic Tac Toe help
How do write a Tie script to this prog?

Thank You Destin :WAVE:
rupa at 2007-11-11 22:48:32 >
# 13 Re: Tic Tac Toe help
Have you even thought about it yet? It's really not that hard. I've written the whole thing for you so far. At least post what you have tried.
destin at 2007-11-11 22:49:33 >
# 14 Re: Tic Tac Toe help
May be its something like this, but i think its not right...

static public String tie ()
{
for (int i = 0 ; i < board.length ; i++)
{
/** check horizontally */
if (board [i] [0] != (board [i] [1]) &&
board [i] [0] != (board [i] [2]))
{
if (!board [i] [0] != (EMPTY))
{
return board [i] [0];
}
}
/** check vertically */
if (board [0] [i] != (board [1] [i]) &&
board [0] [i] != (board [2] [i]))
{
if (!board [0] [i] != (EMPTY))
{
return board [0] [i];
}
}
}

/** check diagonally */
if (board [0] [0] != (board [1] [1]) &&
board [0] [0] != (board [2] [2]))
{
if (!board [0] [0] != (EMPTY))
{
return board [0] [0];
}
}
if (board [0] [2] != (board [1] [1]) &&
board [0] [2] != (board [2] [0]))
{
if (!board [0] [2] != (EMPTY))
{
return board [0] [2];
}
}
return EMPTY;
}
I think they should not be equal in order to get a Tie...Check if im on the right track if not, may be i need a hint...

Thank You!
rupa at 2007-11-11 22:50:39 >
# 15 Re: Tic Tac Toe help
I haven't even looked at what you're doing but I already know it's wayyy simpler than that. You don't even need to create a method to check for a tie. Use the turn variable.

if (turn == 9 && winner().equals(EMPTY)) {
System.out.println("Tie!");
}
destin at 2007-11-11 22:51:42 >
# 16 Re: Tic Tac Toe help
I haven't even looked at what you're doing but I already know it's wayyy simpler than that. You don't even need to create a method to check for a tie. Use the turn variable.

if (turn == 9 && winner().equals(EMPTY)) {
System.out.println("Tie!");
}

This code saves so much space and really makes sense but System.out.println("Tie!"); doesnt work, it doesnt outprint the actual word "Tie", may be i put it in the place where its not supposed to be, but i think i should be in the last Public Static...
Im sorry for such dumb things, but i really appreciate your help
Thank You :)
rupa at 2007-11-11 22:52:40 >
# 17 Re: Tic Tac Toe help
static public void main(String[] args) {
boolean tie = false;
init();

System.out.println("Welcome to Tic-Tac-Toe.");

do {
int row = Integer.parseInt(JOptionPane.showInputDialog(
"Enter the row you wish to move in."));
int column = Integer.parseInt(JOptionPane.showInputDialog(
"Enter the column you wish to move in."));
getMove(row, column);
printBoard();

if (turn == 9 && winner().equals(EMPTY)) {
tie = true;
break;
}
} while(winner().equals(EMPTY));

if (tie) {
System.out.println("TIE!");
} else {
System.out.println("PLAYER " + ((turn - 1) % 2 + 1) + " WINS!");
}
}
destin at 2007-11-11 22:53:42 >
# 18 Re: Tic Tac Toe help
Isn't a tie the situation when the board is full but has no winner lines ? :confused:

Anyway rupa, you said my solution was too complicated, and I agree that it may be so if you need to resort GUI-less and (nearly) sequantial programming (non-oop) methods.

My method is a combination of oop/tabledriven programming and a GUI. The whole game is controlled by the winLine matrix and the fact that player1 & 2 are awarded different scores for the placements (1 & 4).

As a java program, its not complicated at all, but hey, its your game.
sjalle at 2007-11-11 22:54:36 >
# 19 Re: Tic Tac Toe help
Isn't a tie the situation when the board is full but has no winner lines ? :confused:
Well, if turn == 9, the board is full, and if winner().equals(EMPTY), then there's no winner.
destin at 2007-11-11 22:55:39 >
# 20 Re: Tic Tac Toe help
...I will still argue that my tabledriven approach is more 'generic'; if I wanted to make a bigger gameboard and more complicated win patterns, and allow more players, I would only have to plot in these patterns into the win matrix and allocated a wider spectre of awards (so that no player sum could be equal).

As for problem analysis, my solution has dealt with the general concept of a game where players place dices in turn, and the object it to get some pattern first. Expanding the games complexity craves no programming effort and if it is supplied with a GUI for plotting in the win matrix, the player can make his 'own' game. And thats rather cool.
sjalle at 2007-11-11 22:56:46 >
# 21 Re: Tic Tac Toe help
I just want to THANK everyone for helping me, especially Destin!

Thank U Guys!
rupa at 2007-11-11 22:57:47 >