TicTacToe

I am a noob to Java and i have to build this TicTacToe program. It doesn't need GUI or anything, juts a grid on a terminal. I don't have much yet. can anyone help me? I got the board part, but i am confused on how to assign a certain string like "X" or "O" to a coordinate of a 3by3 arrray and getting it to display in the board...can someone help me?

[360 byte] By [Razaaca] at [2007-11-27 3:09:20]
# 1

This is all i have so far, i don't get it at all.

// tic tac toe game

import java.util.Scanner;

public class TicTacToe

{

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

public static void main(String[] args)

{

Scanner input = new Scanner( System.in );

int boxNumber;

String name1;

String name2;

int turn = 0;

System.out.println ( "*******************************" );

for ( int gameBoard = 0; gameBoard != 3; gameBoard++ )

{

for ( int gameBoard2 = 0; gameBoard2 != 5; gameBoard2++ )

{

System.out.println ( "* * * *" );

}

System.out.println ( "*******************************" );

}

System.out.println( "Enter Player1's name: " );

name1 = input.nextLine();

System.out.println( "Enter Player2's name: " );

name2 = input.nextLine();

System.out.printf( "%s, please choose a box to place your mark.", name1 );

boxNumber = input.nextInt();

Razaaca at 2007-7-12 3:58:09 > top of Java-index,Java Essentials,New To Java...
# 2

You are off to a good start. I don't know how much you know about programming in general; apologies if I say something obvious.

For a simple program like this, it's not really necessary, but Java programmers usually put their programs in packages by inserting the statement

package packagename;

at the start of the program.

Also, you should comment your code and use more descriptive variable names. For example, before your first System.out.println statement, you could write the comment

// Draw Tic-Tac-Toe grid

Your variable names "gameBoard" and "gameBoard2" don't make sense, since they are integers, not game boards: for ( int gameBoard2 = 0; gameBoard2 != 5; gameBoard2++ ). Instead, it is customary to use the names i and j for variables in for-loops which can't have a specific description.

Now for the TicTacToe game algorithm:

I won't actually give you code; you really learn from thinking it through yourself.

Some ideas: First, the program must set up variables. You have already done this by declaring variables and prompting for names.

I suggest you create a char variable currentUser, initialized to whichever character (X or O) you want to go first.

After that, the program needs to repeatedly do the following:

1. Prompt current user for move

2. Display game board

3. Check if current user has won. (This is the condition that allows the program to terminate.)

What does this look like? A loop: it executes repeatedly until the condition becomes false. For the condition, you should write another static function that tests whether someone has won. You could use a while loop or a do loop.

You will need to switch the player between turns. You can do this with the line

currentUser = (currentUser == 'X' ? 'O' : 'X');

(If you are not familiar with the ? : operator, it is a shorthand way of writing:

if( currentUser == 'X' )

currentUser = 'O';

else

currentUser = 'X';

).

http://java.sun.com/docs/books/tutorial/ is a useful resource for learning how to use many Java language features.

If you need to look up how to use a specific function/class, see http://java.sun.com/javase/6/docs/api/index.html and click on the appropriate package name in the main pane.

Best wishes.

PCUa at 2007-7-12 3:58:09 > top of Java-index,Java Essentials,New To Java...
# 3

Thank you very much. You have given me some really helpful hints. The way to change between users solved one of my biggest problems. However, i am quite confused on how to make a lable for the box to appear inside the box and have X/O appear the same way, i tried piecing multiple small boxes together, like so:

System.out.println ( "*******" );

for ( int gameBoard = 0; gameBoard != 1; gameBoard++ )

{

for ( int gameBoard2 = 0; gameBoard2 != 3; gameBoard2++ )

{

System.out.printf ( "* %d *\n", boxNumber );

}

System.out.println ( "*******" );

}

In this case, i mad boxNumber a integer that equals to 1, but how can i piece 9 boxes together and have differen boxes display different numbers without using 9 different variables? I would use an 3by3 array, but i am not sure how to utilize that either.

Razaaca at 2007-7-12 3:58:09 > top of Java-index,Java Essentials,New To Java...
# 4
Isn't there a forum member (fastmike?) who likes to regularly post his TicTacToe code?
DrLaszloJamfa at 2007-7-12 3:58:09 > top of Java-index,Java Essentials,New To Java...
# 5
Ehhh...where would i find that? i am new to this forum. besides, his uses GUI, doesn't it? I can't use GUI.
Razaaca at 2007-7-12 3:58:09 > top of Java-index,Java Essentials,New To Java...
# 6
> Ehhh...where would i find that? i am new to this> forum. besides, his uses GUI, doesn't it? I can't use> GUI.Hopefully, he separates his model from his view. Try googling.
DrLaszloJamfa at 2007-7-12 3:58:09 > top of Java-index,Java Essentials,New To Java...
# 7
i did, everything that showed up are with GUI and internet connection. I just want a simple two-player game on a single terminal.
Razaaca at 2007-7-12 3:58:09 > top of Java-index,Java Essentials,New To Java...
# 8
> i did, everything that showed up are with GUI and> internet connection. I just want a simple two-player> game on a single terminal.In that case, you'll have to separate the code yourself, or come up with a solution from the very beginning.
DrLaszloJamfa at 2007-7-12 3:58:09 > top of Java-index,Java Essentials,New To Java...
# 9
which is precisely why i asked for help in the first place.so maybe you have some advice for me?
Razaaca at 2007-7-12 3:58:09 > top of Java-index,Java Essentials,New To Java...
# 10
Step 1: come up with a data structure or class to represent the tic-tac-toe board.
DrLaszloJamfa at 2007-7-12 3:58:09 > top of Java-index,Java Essentials,New To Java...
# 11
i do have a board if you read my code on reply #2, i don't know how to get stuff to display inside of the board, how to re-display it every new turn, or how to incorporate a 3by3 array into this.
Razaaca at 2007-7-12 3:58:09 > top of Java-index,Java Essentials,New To Java...
# 12
You are printing out the tic-tac-tow figure, but by "data structure or class" Imeant something that could remember where the X's and O's are, anddetect when the game is won, lost or a stalemate, etc...
DrLaszloJamfa at 2007-7-12 3:58:10 > top of Java-index,Java Essentials,New To Java...
# 13
yes, but one step at a time, i want the board in the begining to have 9 squares with the numbers 1-9 in them so the 1st player cna enter their choice and place a mark in it. I can;t get that board to happen.
Razaaca at 2007-7-12 3:58:10 > top of Java-index,Java Essentials,New To Java...
# 14

> yes, but one step at a time

I agree. Do and test one step at a time.

> I can;t get that board to happen.

To happen? Step 1 define:

class Board {

}

Or is that too object-oriented?

DrLaszloJamfa at 2007-7-12 3:58:10 > top of Java-index,Java Essentials,New To Java...
# 15

i have this segment of code

for (boxNumber = 1; boxNumber <= 9; boxNumber++)

{

System.out.println ( "*******" );

for ( int gameBoard = 0; gameBoard != 1; gameBoard++ )

{

for ( int gameBoard2 = 0; gameBoard2 != 3; gameBoard2++ )

{

System.out.printf ( "* %d *\n", boxNumber );

}

System.out.println ( "*******" );

}

}

It does what i want, except it displays them like this:

*******

* 1 *

* 1 *

* 1 *

*******

*******

* 2 *

* 2 *

* 2 *

*******

*******

* 3 *

* 3 *

* 3 *

*******

*******

* 4 *

* 4 *

* 4 *

*******

*******

* 5 *

* 5 *

* 5 *

*******

*******

* 6 *

* 6 *

* 6 *

*******

*******

* 7 *

* 7 *

* 7 *

*******

*******

* 8 *

* 8 *

* 8 *

*******

*******

* 9 *

* 9 *

* 9 *

*******

not side-by-side

Razaaca at 2007-7-21 20:41:57 > top of Java-index,Java Essentials,New To Java...
# 16
Okay. What starts a new line is the "ln" in println, and the \n (better %n) in printf.Take all those out and your output is 1 long horizontal line. The correctsolution is something in between. I suggest playing around with thecode until you get an insight.
DrLaszloJamfa at 2007-7-21 20:41:57 > top of Java-index,Java Essentials,New To Java...
# 17
yes, but it's impossible to get the result that i want in one loop, isn't it?
Razaaca at 2007-7-21 20:41:57 > top of Java-index,Java Essentials,New To Java...
# 18

Impossible? There's actually a theoretical result that any partially recusive

function can be written with exactly one loop!

Anyway, do what ever seems more natural to you. This occurs to me.

Think of the board as having three rows and three columns of cells, and

the cell being made up of some number of lines of text:

for every row

for every line on that row

for every col on that row

print that line for that cell

next

start a new line

next

next

There are many ways of doing this. Play around with your code until it works. It's not rocket science, it's a tic-tac-toe board.

DrLaszloJamfa at 2007-7-21 20:41:57 > top of Java-index,Java Essentials,New To Java...
# 19

I can't get it...it's just weird, i was never good with loops and i'm just more confused now.

I can't even get it to display horizontally so i can use three loops to do it. it's just messed up...

Let's move on to a different part of the problem.or can we if i don't have the board?

I'm pretty sure that i'll get the code going once i get the concepts on how to construct this program.

Someone PLZPLZ help me....i am really dying here.

Razaaca at 2007-7-21 20:41:57 > top of Java-index,Java Essentials,New To Java...
# 20

TicTacToe.java

public class TicTacToe

{

public TicTacToe()

{

board = new String[ROWS][COLUMNS];

// Fill with spaces

for (int i = 0; i < ROWS; i++)

for (int j = 0; j < COLUMNS; j++)

board[i][j] = " ";

}

public void set(int i, int j, String player)

{

if (board[i][j].equals(" "))

board[i][j] = player;

}

public String toString()

{

String r = "";

for (int i = 0; i < ROWS; i++)

{

r = r + "|";

for (int j = 0; j < COLUMNS; j++)

r = r + board[i][j];

r = r + "|\n";

}

return r;

}

private String[][] board;

private static final int ROWS = 3;

private static final int COLUMNS = 3;

}

TicTacToeTester

import java.util.Scanner;

public class TicTacToeTester

{

public static void main(String[] args)

{

Scanner in = new Scanner(System.in);

String player = "x";

TicTacToe game = new TicTacToe();

boolean done = false;

while (!done)

{

System.out.print(game.toString());

System.out.print(

"Row for " + player + " (-1 to exit): ");

int row = in.nextInt();

if (row < 0) done = true;

else

{

System.out.print("Column for " + player + ": ");

int column = in.nextInt();

game.set(row, column, player);

if (player.equals("x"))

player = "o";

else

player = "x";

}

}

}

}

fastmikea at 2007-7-21 20:41:57 > top of Java-index,Java Essentials,New To Java...
# 21
Hey hey, just like I predicted in reply #4!
DrLaszloJamfa at 2007-7-21 20:41:57 > top of Java-index,Java Essentials,New To Java...
# 22
Strangely enough - I coded a Tic Tac Toe game earlier today by pure coincidence. (practicing the MVC still) Shall I post mine, too? ;) hehe
JJCoolBa at 2007-7-21 20:41:57 > top of Java-index,Java Essentials,New To Java...
# 23
Well, we're missing code to detect the end of the game ...
DrLaszloJamfa at 2007-7-21 20:41:57 > top of Java-index,Java Essentials,New To Java...
# 24
Oh boy! Mine has that! (albiet, not the greatest, but it still works)...But then again, mine's also 218 lines long.
JJCoolBa at 2007-7-21 20:41:57 > top of Java-index,Java Essentials,New To Java...
# 25
I don't think Razaac will mind.
DrLaszloJamfa at 2007-7-21 20:41:57 > top of Java-index,Java Essentials,New To Java...
# 26

heh. Aight. Actually I really would appreciate it if you could comment on my implementation of MVC, Dr. (I want to know if I'm "doing it right" or at least "close to right") If you don't mind looking over the 218 lines or so.

import java.util.*;

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.event.*;

public class TicTacToe

{

public static void main(String[] args)

{

controller c = new controller();

model m = new model();

view v = new view(c);

v.setModel(m);

c.setModel(m);

c.setView(v);

m.addModelListener(v);

v.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

}

interface modelListener extends EventListener

{

void modelChanged(modelChangedEvent e);

}

class modelChangedEvent extends EventObject

{

int changedX;

int changedY;

int player;

Object source;

public modelChangedEvent(model m)

{

super(m);

}

public model getModel()

{

return (model) super.getSource();

}

public void setChanged(int x, int y)

{

changedX = x;

changedY = y;

}

public void setPlayer(int p)

{

player = p;

}

public int getX()

{

return changedX;

}

public int getY()

{

return changedY;

}

public int getP()

{

return player;

}

public void setSource(Object o)

{

source = o;

}

public Object getSource()

{

return source;

}

}

class model

{

EventListenerList list = new EventListenerList();

modelChangedEvent event = new modelChangedEvent(this);

int grid[][] = new int[3][3];

int currentPlayer = 1; // 1 for X, 2 for O

public model()

{

for (int i = 0; i < 3; i++)

for (int j = 0; j < 3; j++)

grid[i][j] = 0;

}

public void addModelListener(modelListener l)

{

list.add(modelListener.class, l);

}

public void removeModelListener(modelListener l)

{

list.remove(modelListener.class, l);

}

public void fireEvent()

{

Object[] listeners = list.getListenerList();

for (int i = listeners.length - 2; i >= 0; i -= 2)

{

if (listeners[i] == modelListener.class)

{

((modelListener)listeners[i+1]).modelChanged(event);

}

}

}

public void placePiece(int x, int y)

{

grid[x][y] = currentPlayer;

event.setChanged(x,y);

event.setPlayer(currentPlayer);

currentPlayer = currentPlayer % 2 + 1;

fireEvent();

}

public boolean testWin(int player)

{

boolean winFlag = false;

for (int i = 0; i < 3; i++)

{

if (grid[i][0] == grid[i][1] && grid[i][0] == grid[i][2] && grid[i][0] == player)

winFlag = true;

if (grid[0][i] == grid[1][i] && grid[0][i] == grid[2][i] && grid[0][i] == player)

winFlag = true;

}

if (grid[0][0] == grid[1][1] && grid[0][0] == grid[2][2] && grid[1][1] == player)

winFlag = true;

if (grid[0][2] == grid[1][1] && grid[0][2] == grid[2][0] && grid[1][1] == player)

winFlag = true;

return winFlag;

}

public void actionButton(JButton b)

{

event.setSource(b);

}

}

class view extends JFrame implements modelListener

{

model m;

public view(controller l)

{

setTitle("Tic Tac Toe!");

setLayout(new GridLayout(3,3));

for (int i = 0; i < 9; i++)

{

JButton b = new JButton("");

b.addActionListener(l);

b.setActionCommand(String.valueOf(i));

b.setPreferredSize(new Dimension(70,70));

b.setMargin(new Insets(0,0,0,0));

add(b);

}

pack();

setVisible(true);

}

public void setModel(model m)

{

this.m = m;

}

public void modelChanged(modelChangedEvent e)

{

JButton src = (JButton) e.getSource();

int player = e.getP();

if (player == 1)

src.setText("X");

else if (player == 2)

src.setText("O");

else

;

src.setEnabled(false);

if (m.testWin(player))

{

System.out.println("Player " + player + " wins!");

System.exit(0);

}

}

}

class controller implements ActionListener

{

model m;

view v;

public void setModel(model m)

{

this.m = m;

}

public void setView(view v)

{

this.v = v;

}

public void actionPerformed(ActionEvent e)

{

JButton b = (JButton) e.getSource();

m.actionButton(b);

int i = Integer.parseInt(e.getActionCommand());

m.placePiece(i % 3, i / 3);

}

}

JJCoolBa at 2007-7-21 20:41:57 > top of Java-index,Java Essentials,New To Java...
# 27

To FastMike, thank you very much, it is a great help, i will modle my code after part of yours.

To JJCoolB, thank you for your 218 line long code, i don't mind, just give me a second to find the section for checking winners.

To DrLasloJamf, nice prediction, you r right.

Thanks everyone!

If i encounter any problems, i will ask for help again...lol, bet u guys r tired of me right about now...i'm such a noob at this...

Razaaca at 2007-7-21 20:41:57 > top of Java-index,Java Essentials,New To Java...
# 28

// java final project

// tic tac toe game

import java.util.Scanner;

public class TicTacToe

{

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

public static void main(String[] args)

{

Scanner input = new Scanner( System.in );

int boxNumber;

String name1;

String name2;

String current = "X";

int choice;

int box = 0;

System.out.println( "Enter Player1's name: " );

name1 = input.nextLine();

System.out.println( "Enter Player2's name: " );

name2 = input.nextLine();

for ( int i = 0; i < 3; i++)

{

for ( int j = 0; j < 3; j++)

{

board[i][j] = " ";

}

}

System.out.println();

System.out.println ( "******************" );

for (boxNumber = 1; boxNumber <= 3; boxNumber++)

{

for ( int row = 0; row < 1; row++ )

{

for ( int column = 0; column < 3; column++ )

{

System.out.printf ( "****\n" );

}

System.out.println ( "******************" );

}

}

int winner = 0;

int display = 0;

while (winner == 0)

{

while ( display == 0)

{ // start of while loop

System.out.println();

System.out.println ( "******************" );

for (boxNumber = 1; boxNumber <= 3; boxNumber++)

{

for ( int row = 0; row < 1; row++ )

{

for ( int column = 0; column < 3; column++ )

{

System.out.printf ( "****\n" );

}

System.out.println ( "******************" );

}

}

System.out.printf( "%s, make your move.", name1 );

choice = input.nextInt();

if ( choice <= 0 || choice > 9 )

{

System.out.printf( "%s, can't do that homey.", name1 );

choice = input.nextInt();

}

else

{

xmark(choice);

if (current == ("X"))

{

current = "O";

System.out.println();

System.out.println ( "******************" );

for (boxNumber = 1; boxNumber <= 3; boxNumber++)

{

for ( int row = 0; row < 1; row++ )

{

for ( int column = 0; column < 3; column++ )

{

System.out.printf ( "****\n" );

}

System.out.println ( "******************" );

}

}

System.out.printf( "%s, make your move.", name2 );

omark(choice);

}

else

current = "X";

}

}//end of loop

}

}

public static void xmark ( int x )

{

int thingy = x;

switch ( thingy )

{

case 1:

board[0][0] = "X";

break;

case 2:

board[0][1] = "X";

break;

case 3:

board[0][2] = "X";

break;

case 4:

board[1][0] = "X";

break;

case 5:

board[1][1] = "X";

break;

case 6:

board[1][2] = "X";

break;

case 7:

board[2][0] = "X";

break;

case 8:

board[2][1] = "X";

break;

case 9:

board[2][2] = "X";

break;

}

}

public static void omark ( int o )

{

int thingy = o;

switch ( thingy )

{

case 1:

board[0][0] = "O";

break;

case 2:

board[0][1] = "O";

break;

case 3:

board[0][2] = "O";

break;

case 4:

board[1][0] = "O";

break;

case 5:

board[1][1] = "O";

break;

case 6:

board[1][2] = "O";

break;

case 7:

board[2][0] = "O";

break;

case 8:

board[2][1] = "O";

break;

case 9:

board[2][2] = "O";

break;

}

}

}//end

Guys, please help me with my code, i don't get it...i need help...please, it doesn't display the board with the X or O...please helpme.it dislays weird stuff, copy it and see for urselves...

Razaaca at 2007-7-21 20:41:57 > top of Java-index,Java Essentials,New To Java...