Tic tac toe problem please help
hi,
My program consists of 4 classes but working bit by bit and currently using 2 classes. I've managed to get an 'X' to appear on the grid but I'm having problems arranging it like a tic tac toe grid and another number appears under the number selected by the player next to the grid, how do i get rid of it?? the output is like this.........
// output
Enter player's Name:
Name:
dave
dave to play
Enter move by selecting number from grid, or 0 to draw
Move entered:
1
1 0X23456789
it also says "String index out of range:-1 any ideas what this means?????
heres my source code for the program....
//Main program
public class TheTest1
public static void main( String [] args)
TheTest TT = new TheTest();
TT.gridSheet("0123456789", true);
// TheTest
import element.* ; // import the package that contains
// the ConsoleWindow class
public class TheTest
String name1;
String turn;
int cell, move;
final static char NOUGHT='O', CROSS='X';
public TheTest()
c.out.println("Enter player's Name:");
c.out.println("Name:");
name1 = c.input.readString();
turn = name1;
move();
public void move()
if(turn.compareTo(name1)==0)
c.out.println(name1 + " to play");
c.out.println("Enter move by selecting number from grid, or 0 to draw");
c.out.println("Move entered: ");
cell = c.input.readInt();
public void gridSheet(String fruit, boolean play)
for(int j = 1; j<9; j=j+3)
char index;
for(int i = j; i<(j+3); i++)
if(play==true)
index = fruit.charAt (i);
c.out.print (index + " ");
//index = fruit.charAt(i);
if(cell==1 && turn.compareTo(name1)==0)
cell=fruit.indexOf('1');
fruit=fruit.substring(0,cell) + CROSS + fruit.substring(cell+1);
c.out.println(fruit);
//move();
//c.out.println(" ");
Any help will be appreciated.
Many thanks
Dave
this is a tic tac toe console and you're having trouble displaying it as a grid?
if so, this is one way to simulate the board (some of the code is just for display in this example)
import java.io.*;
class TicTacToeConsole
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String[] board = new String[9];
public TicTacToeConsole()
for(int x = 0; x < board.length; x++) board[x] = " _ ";
try{playGame();}catch(Exception e){e.printStackTrace();}
public void playGame() throws IOException
System.out.println("Board at game start");
printBoard();
System.out.println("\nPlease select an available number to put your X");
printAvailableSquares();
int playerMove = Integer.parseInt(input.readLine()) -1;
board[playerMove] = " X ";
System.out.println("\nBoard after first move");
printBoard();
System.out.println("\nAvailable moves after first move");
printAvailableSquares();
public void printBoard()
System.out.println();
for(int x = 0; x < board.length; x++)
System.out.print(board[x]);
if(x%3 == 2) System.out.println("\n");
public void printAvailableSquares()
System.out.println();
for(int x = 0; x < board.length; x++)
if(board[x].equals(" _ ")) System.out.print(" " + (x+1) + " ");
else System.out.print(" ");
if(x%3 == 2) System.out.println("\n");
public static void main(String[] args){new TicTacToeConsole();}
}
Similar Messages
-
Tic - Tac - Toe Game - Please Help!
Hi everyone, I am attempting to create a tic - tac - toe game (O's & X's).
I would like there to be two playing modes to the game, the first mode will be one player where the user plays against the computer. The second mode is a two - player game, where two users play, one being X's and the other being O's.
Can anyone help me get started with this game, I know there is source code on the internet but I would rather not use this as I would like to learn as I create the game.
Thanks Everyoneits amazing how much code a simple game like tic-tac-toe can require.. well, only if you program the AI of the computer.. i wrote one in c++ last year, for my computer science class, and the whole class had trouble with it, mainly the AI.. a suggestion to you: write it in an object-oriented manner. i ended up writing it procedurally and in the end, it looked very bad, but it worked!
i would prob. setup some objects like: Board (the 3x3 grid), Mark (a user mark, such as an "x" or an "o")..
i dunno.. hope that helps some, if you need help with the AI at all.. i do have the tic-tac-toe program i wrote on my website (http://www.angelfire.com/blues/smb/ ) in the C++ section.. i used a graphics package, but the logic is all there and the code is well commented.
anyway, ill talk to ya later, good luck,
Steven Berardi -
I need help on a Tic Tac Toe game I am making for a class. I had finished a "2 Player" version and my instructor wants me to simulate a computer "AI" now. I cannot figure out what I'm doing wrong. The order of precedence is this:
1. X moves first (the player)
2. Computer moves to win.
3. If it can't win, it moves to block a win
4. If it can't block a win, it moves to the best possible spot to set up a win.
I think my problems are with several methods, but I cannot figure out what I'm doing wrong. Every time I look at my code, it just makes "sense". I think my problems could probably be found in 4 methods, setButtonText(), findOpen(), findBestOpen() and tempCheck(). I would like hints or maybe if I could get a second look at it for me.
public class VangTicTacToe extends javax.swing.JFrame {
private boolean isX;
private int turnCount;
private boolean gameWon;
private boolean isTemp;
/** Creates new form VangTicTacToe */
public VangTicTacToe() {
initComponents();
resetGame();
isX = true;
turnCount = 0;
private void checkWinner(String pressedButton){
//an multi-dimensional array of winning combinations
JButton[][] winningCombos = {{oneJButton, twoJButton,
threeJButton}, {oneJButton, fourJButton,
sevenJButton}, {oneJButton, fiveJButton, nineJButton},
{twoJButton, fiveJButton, eightJButton}, {threeJButton, sixJButton,
nineJButton}, {fourJButton, fiveJButton, sixJButton}, {sevenJButton,
eightJButton, nineJButton}, {sevenJButton, fiveJButton, threeJButton}};
String buttonPressed = pressedButton;
//loops and determines if any of the possible winning combinations have been
//met for X and displays output accordingly
for(JButton[] row : winningCombos){
for(JButton button : row){
if(button.getText().equals(buttonPressed)){
gameWon = true;
else{
gameWon = false;
break;
}//end inner for
if(gameWon == true && isTemp == false){
for(JButton button : row){
button.setBackground(Color.green);
}//end inner for
if(pressedButton.equals("X"))
outputJLabel.setText("Congratulations! Player 1 (\"X\") Wins!");
else
outputJLabel.setText("Sorry, computer wins.");
disableButtons();
break;
}//end if
else{
continue;//go to next outer loop and keep searching
}//end outer for
}//end method checkWinner
private void setButtonText(JButton buttonPressed){
if(isX == true){
buttonPressed.setText("X");
isX = false;
checkWinner("X");
outputJLabel.setText("Computer's turn");
isTemp = true; //sets isTemp to true so that the test is temporary
findOpen();//calls findOpen to start computer move
//disable the button so it cannot be pressed again
buttonPressed.setEnabled(false);
//increment the turn count number
turnCount++;
if(turnCount == 9)
outputJLabel.setText("Cats Game! You both are losers!");
}//end method setText
//the following 3 methods are for a computer move
//find next open space
private void findOpen(){
//array of buttons
JButton[] buttons = {oneJButton, twoJButton, threeJButton, fourJButton,
fiveJButton, sixJButton, sevenJButton, eightJButton, nineJButton};
//moves through array of buttons and looks for empty. If empty,
//it calls temporary select method.
for (int count = 0; count < buttons.length; count++){
if(buttons[count].getText().isEmpty())
tempCheck(buttons[count]);
}//end for loop
//if gameWon is false, call findBestButton to find the best open spot
if(gameWon == false){
findBestButton();
}//end method findOpen
private void findBestButton(){
//an multi-dimensional array of winning combinations
JButton[][] winningCombos = {{oneJButton, twoJButton,
threeJButton}, {oneJButton, fourJButton,
sevenJButton}, {oneJButton, fiveJButton, nineJButton},
{twoJButton, fiveJButton, eightJButton}, {threeJButton, sixJButton,
nineJButton}, {fourJButton, fiveJButton, sixJButton}, {sevenJButton,
eightJButton, nineJButton}, {sevenJButton, fiveJButton, threeJButton}};
boolean placeO = false;
int buttonCount = 0;
for(JButton[] row : winningCombos){
for(JButton button : row){
if(button.getText().equals("O") || button.getText().equals("")){
placeO = true;
else{
placeO = false;
buttonCount = 0;
if(placeO == true){
++buttonCount;
else{
break;
if(buttonCount == 3 && placeO == true){
button.setText("O");
}//end inner for
if(placeO == true){
isX = true;
break;
else{
continue;
}//end outer for
}//end method findBestButton
//checks if temp move would win
private void tempCheck(JButton tempButton){
//temporarily assigns "O" to a square and checks if it wins
tempButton.setText("O");
checkWinner("O");
if(gameWon == true){//if it wins then set temp to false and call
isTemp = false;//checkWinner();
checkWinner("0");
else{
tempButton.setText("");//else, set buttonText to empty
}//end if
if(gameWon == false){//if gameWon is false, check if "X" would win
tempButton.setText("X");
isTemp = true;
checkWinner("X");
if(gameWon == true){//if x is going to win,
tempButton.setText("O");//block the player from winning
else{
tempButton.setText("X");
}//end method tempCheck()
}touandcim wrote:
I click to make "X"'s (the player's move). X appears but O never does, although a button is highlighted. If I keep pressing the buttons, all X's appear until the last move, when an "O" appears.I don't know if it's the problem, but
checkWinner("0");looks suspicious. (2nd invocation in your tempCheck() method).
Your program seems awfully brittle. How would you do it if you had a 4 x 4 board? Or 5 x 5?
Also, your 'winningCombos' array is repeated everywhere it's used. There's no need for that; just make it an instance variable/constant.
Winston -
Test out this Tic Tac Toe game please
I know this is suppose to be a real java forum, but this is stripped down version of java, but it's still java. Before using real java I used this Judo. So can you guys download the stuff and play it a few times. Give me any suggestions or bug reports. This is v. 1.0 and there isn't a winner decider yet. Thanks and hope you have fun!
You will need to download JUDO
http://judo.sourceforge.net/#download
Open JUDO and paste this code into it and run.
void main () {
String Intro = "Tic Tac Toe v 1.0 only funcutions under lower case letters.";
String Start = "Execute y/n...";
drawString(Intro, 150,50);
drawString(Start, 150,70);
String Go = "y";
String go;
go = readString();
if(equal(go,Go)){
setColor(blue);
for(int loading = 0 ; loading < 460; loading++)
int lpercent = loading;
//printLine("Loading percent... "+lpercent/460+"%");
fillRectangle(loading*1,250, 25,25);
delay(0.01);
String complete = "Loading Complete...";
drawString(complete,0,235);
//Ask what user would like [X or O]
//get player name
String PlayerName;
String PlayerName2;
printLine("Enter Player 1 name...");
PlayerName = readString();
printLine("Enter Player 2 name...");
PlayerName2 = readString();
//Recycle program loop here
String execute = "y";
String yes = "y";
//While user would still like to run program
while(equal(execute, yes)) {
//decide player symbol
String PlayerOne;
String PlayerTwo;
printLine("Select player 1 character...[x or o]");
PlayerOne = readString();
String O = "o";
String X = "x";
if(equal(PlayerOne, X) ) {
PlayerTwo = O;
else{
PlayerTwo = X;
//Printout inputed data
printLine("Player 1 : ("+ PlayerOne +") " + PlayerName + " Player 2 : (" + PlayerTwo +") "+ PlayerName2);
//Draw playing board
String info = "Player 1 : ("+ PlayerOne +") " + PlayerName + " | Player 2 : (" + PlayerTwo +") "+ PlayerName2;
//clearDrawing();
for(int roundTime = 0 ; roundTime < 6; roundTime++) {
setBackgroundColor(azure);
drawString(info, 150,50);
//horizontal lines
setColor(black);
drawLine(100,100, 400,100);
drawLine(100,101, 400,101);
drawLine(100,141, 400,141);
drawLine(100,142, 400,142);
drawLine(100,182, 400,182);
drawLine(100,183, 400,183);
//verticle lines
drawLine(200,60, 200,223);
drawLine(201,60, 201,223);
drawLine(300,60, 300,223);
drawLine(301,60, 301,223);
//code boxed
String a = "A";
String b = "B";
String c = "C";
String d = "D";
String one = "1";
String two = "2";
String three = "3";
drawString(a, 100,80);
drawString(b, 100,120);
drawString(c, 100,160);
drawString(d, 100,200);
drawString(one, 150,230);
drawString(two, 250,230);
drawString(three, 350,230);
//Let X go first then O (continue alternating)
String pOne = PlayerName + "'s turn to move...";
String pTwo = PlayerName2 + "'s turn to move...";
if(equal(PlayerOne,X)) {
drawString(pOne, 50,243);
else{
drawString(pTwo, 50,243);
//ask user to make move here, then alternate character moves.
String move;
String move2;
String A1 = "a1";
String A2 = "a2";
String A3 = "a3";
String B1 = "b1";
String B2 = "b2";
String B3 = "b3";
String C1 = "c1";
String C2 = "c2";
String C3 = "c3";
String D1 = "d1";
String D2 = "d2";
String D3 = "d3";
printLine("Please enter your character position player(X)...");
move = readString();
String CX = "X";
String CO = "O";
if(equal(move,A1)) {
setColor(blue);
drawString(CX, 42, 140,99);
else{
//continue program execution
if(equal(move,A2)) {
setColor(blue);
drawString(CX, 42, 240,99);
else{
//continue program execution
if(equal(move,A3)) {
setColor(blue);
drawString(CX, 42, 340,99);
else{
//continue program execution
if(equal(move,B1)) {
setColor(blue);
drawString(CX, 42, 140,140);
else{
//continue program execution
if(equal(move,B2)) {
setColor(blue);
drawString(CX, 42, 240,140);
else{
//continue program execution
if(equal(move,B3)) {
setColor(blue);
drawString(CX, 42, 340,140);
else{
//continue program execution
if(equal(move,C1)) {
setColor(blue);
drawString(CX, 42, 140,181);
else{
//continue program execution
if(equal(move,C2)) {
setColor(blue);
drawString(CX, 42, 240,181);
else{
//continue program execution
if(equal(move,C3)) {
setColor(blue);
drawString(CX, 42, 340,181);
else{
//continue program execution
if(equal(move,D1)) {
setColor(blue);
drawString(CX, 42, 140,222);
else{
//continue program execution
if(equal(move,D2)) {
setColor(blue);
drawString(CX, 42, 240,222);
else{
//continue program execution
if(equal(move,D3)) {
setColor(blue);
drawString(CX, 42, 340,222);
else{
//continue program execution
//clearDrawing();
if(equal(PlayerOne,X)) {
drawString(pTwo, 50,243);
else{
drawString(pOne, 50,243);
//O 's movement here
printLine("Please enter your character position player(O)...");
move2 = readString();
if(equal(move2,A1)) {
setColor(red);
drawString(CO, 42, 140,99);
else{
//continue program execution
if(equal(move2,A2)) {
setColor(red);
drawString(CO, 42, 240,99);
else{
//continue program execution
if(equal(move2,A3)) {
setColor(red);
drawString(CO, 42, 340,99);
else{
//continue program execution
if(equal(move2,B1)) {
setColor(red);
drawString(CO, 42, 140,140);
else{
//continue program execution
if(equal(move2,B2)) {
setColor(red);
drawString(CO, 42, 240,140);
else{
//continue program execution
if(equal(move2,B3)) {
setColor(red);
drawString(CO, 42, 340,140);
else{
//continue program execution
if(equal(move2,C1)) {
setColor(red);
drawString(CO, 42, 140,181);
else{
//continue program execution
if(equal(move2,C2)) {
setColor(red);
drawString(CO, 42, 240,181);
else{
//continue program execution
if(equal(move2,C3)) {
setColor(red);
drawString(CO, 42, 340,181);
else{
//continue program execution
if(equal(move2,D1)) {
setColor(red);
drawString(CO, 42, 140,222);
else{
//continue program execution
if(equal(move2,D2)) {
setColor(red);
drawString(CO, 42, 240,222);
else{
//continue program execution
if(equal(move2,D3)) {
setColor(red);
drawString(CO, 42, 340,222);
else{
//continue program execution
/*setBackgroundColor(azure);
drawString(info, 150,50);
//horizontal lines
setColor(black);
drawLine(100,100, 400,100);
drawLine(100,101, 400,101);
drawLine(100,141, 400,141);
drawLine(100,142, 400,142);
drawLine(100,182, 400,182);
drawLine(100,183, 400,183);
//verticle lines
drawLine(200,60, 200,223);
drawLine(201,60, 201,223);
drawLine(300,60, 300,223);
drawLine(301,60, 301,223);
//code boxed
drawString(a, 100,80);
drawString(b, 100,120);
drawString(c, 100,160);
drawString(d, 100,200);
drawString(one, 150,230);
drawString(two, 250,230);
*/ drawString(three, 350,230);
printLine("would you like to execute program further? Y/N");
execute = readString();
else{
clearDrawing();
String Fail = "User declined program execution...";
drawString(Fail, 150,60);please format the code..
RK -
Basic Tic Tac Toe programming help please
I'm trying to make a seperate java class(there is another main that calls this using SWING interface) that makes mark on the board.
It's supposed to do the following
Method makeMark returns:
a null if the cell indicated by row and column has already been marked
an X if it is X's turn (X gets to go first)
a Y if it is Y's turn
Thus makeMark will have to keep of marks made previously and return the appropriate string
for the requested cell.
and here is what I got so far, but only getting empty clicks as a respond. Any help will be appreciated. thanks.
import javax.swing.JButton;
public class TicTacToeGame {
public String makeMark(int row, int column){
String player = "X";
String [][] Enum = new String [3][3];
for (row=0; row<=2; row++){
for (column=0; column<=2; column++)
if (Enum[row][column] == "")
if (player == "X"){
Enum[row][column] = "X";
player = "Y";
return "X";
if (player == "Y"){
Enum[row][column] = "O";
player = "X";
return "Y";
else
return null;
return player;
}ok is there a simpler codes that will just flip-flop between X and O? I had it working before but somehow it's not working anymore. Before I had
public String makeMark(int row, int column){
player = "X";
if (player = "X")
player = "O";
else if (player = "O")
player = "X";
or soemthing like this but it used to work, but I had to revise the code to do more things and it stopped even flip-flopping between X and O.
Here's main code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
* This class is the GUI for TicTacToe. It only handles user clicks on
* buttons, which represent X's and O's
* @author Hal Mendoza
* CSE 21 - Jan 18, 2011, 8:18:22 PM
* TicTacToe.java
public class TicTacToe extends JPanel implements ActionListener {
public final static int NUM_ROWS_COLUMNS = 3;
private JButton arrayofButtons[][] = new JButton[NUM_ROWS_COLUMNS][NUM_ROWS_COLUMNS];
TicTacToeGame board = new TicTacToeGame();
public TicTacToe() {
BoxLayout ourLayout = new BoxLayout(this, BoxLayout.Y_AXIS);
setLayout(ourLayout);
add(buildMainPanel());
* Builds the panel with buttons
* @return the panel with buttons
private JPanel buildMainPanel() {
JPanel panel = new JPanel();
GridLayout gridLayout = new GridLayout(0, NUM_ROWS_COLUMNS);
panel.setLayout(gridLayout);
for (int row = 0; row < arrayofButtons.length; ++row)
for (int column = 0; column < arrayofButtons[0].length; ++column) {
arrayofButtons[row][column] = new JButton();
arrayofButtons[row][column].setPreferredSize(new Dimension(50, 50));
arrayofButtons[row][column].addActionListener(this);
// Use actionCommand to store x,y location of button
arrayofButtons[row][column].setActionCommand(Integer.toString(row) + " " +
Integer.toString(column));
panel.add(arrayofButtons[row][column]);
return panel;
* Called when user clicks buttons with ActionListeners.
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
String xORo;
String rowColumn[] = button.getActionCommand().split(" ");
int row = Integer.parseInt(rowColumn[0]);
int column = Integer.parseInt(rowColumn[1]);
xORo = board.makeMark(row, column);
if (xORo != null)
button.setText(xORo);
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event dispatch thread.
private static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("Tic Tac Toe");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Add contents to the window.
frame.add(new TicTacToe());
// Display the window.
frame.pack();
frame.setVisible(true);
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
} -
hey all,
i am having problems creating a tic tac toe program. the program should create a board with NxN spaces, where N is obtained through user input.
I created a fully working program that does a 3x3 board, checks for diagonal, vertical, horizontal wins and also allows 1 vs computer or 2 players play, but i am struggling with the NxN board.
here is the code of what i have, can anyone point me in the right direction? all help is appreciated! please keep it simple as possible as i am just learning java!!
import java.util.Scanner;
import java.util.Random;
public class NoughtsCrosses
static final String PLAYER1 = "X";
static final String PLAYER2 = "O";
static final String EMPTY = "�";
static String[][] board = new String[][];
static int turn = 0;
static public void makeBoard(int boardSize)
for (int x = 0; x < boardSize; x++)
for (int y = 0; y < boardSize; y++)
board[x][y] = new String(EMPTY);
static public void playComputer()
Scanner scan = new Scanner(System.in);
Random generator = new Random();
int move;
printBoard();
System.out.println();
do {
if(turn%2 == 0)
System.out.println("Player 1, place your X");
System.out.print("Make a Move: ");
move = scan.nextInt();
else
System.out.print("Computer, place your O: ");
move = generator.nextInt(10);
System.out.println(move);
getMove(move);
System.out.println();
printBoard();
System.out.println();
} while(winner().equals(EMPTY) && turn < 9);
if (winner().equals(EMPTY))
System.out.println("The Game s a DRAW!");
else
System.out.println("PLAYER " + ((turn - 1) % 2 + 1) + " WINS!!");
static public void playHuman()
Scanner scan = new Scanner(System.in);
printBoard();
System.out.println();
do {
if(turn%2 == 0)
System.out.println("Player 1, place your X");
else
System.out.println("Player 2, place your O");
System.out.print("Make a Move: ");
int move = scan.nextInt();
getMove(move);
System.out.println();
printBoard();
System.out.println();
} while(winner().equals(EMPTY) && turn < 9);
if (winner().equals(EMPTY))
System.out.println("The Game s a DRAW!");
else
System.out.println("PLAYER " + ((turn - 1) % 2 + 1) + " WINS!!");
static public void getMove(int move)
int row = move/3;
int col = move%3;
if (board[row][col].equals(EMPTY))
board[row][col] = (turn % 2 == 0 ? PLAYER1 : PLAYER2);
turn++;
else
System.out.println("OCCUPIED FIELD! TRY AGAIN!");
static public void printBoard()
for (int x = 0; x < 3; x++)
for (int y = 0; y < 3; y++)
if(y == 0)
System.out.print(" ");
System.out.print(board[x][y]);
if(y < 2)
System.out.print(" | ");
System.out.println();
if(x < 2)
System.out.println(" ---|---|---");
static public String winner()
for (int i = 0; i < board.length; i++)
/** check horizontally */
if (board[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)
Scanner scan = new Scanner(System.in);
int boardSize;
System.out.println();
System.out.println("Welcome to Tic Tac Toe!");
System.out.println("�����������������������");
System.out.println("How big should the board be?");
boardSize = scan.nextInt();
makeBoard(boardSize);
int players = 0;
do{
System.out.println("How many players?");
System.out.println("1 (vs. Computer) or 2 (vs. another player)?");
players = scan.nextInt();
System.out.println();
}while(players < 1 || players > 2);
if (players == 1)
playComputer();
else
playHuman();well, i figured out how to do it all, thanks to the TREMENDOUS amount of help here...lol...
i just have one more (minor problem)...
i can't get an algorithm working to see if the two diagonals are occupied by x's or o's (see if someone won diagonally)
to check horizontally & vertically on an NxN board, i use following code:
int count = 0;
/** check horizontally */
for (int i = 0; i < myBoard.length; i++)
for (int j = 0; j < myBoard.length-1; j++)
if (myBoard[0].equals(myBoard[i][j+1]) && !myBoard[i][0].equals(EMPTY))
count++;
if (count >= myBoard.length-1)
return myBoard[i][0];
count = 0;
count = 0;
/** check vertically */
for (int i = 0; i < myBoard.length; i++)
for (int j = 0; j < myBoard.length-1; j++)
if (myBoard[j][0].equals(myBoard[j+1][i]) && !myBoard[0][i].equals(EMPTY))
count++;
if (count >= myBoard.length-1)
return myBoard[0][i];
count = 0;
now i was messing around ALOT and couldn't figure out how to get the diagonals showing! this is what i came up with:
count =0;
for (int j = 1; j < myBoard.length; j++)
if (myBoard[0][0].equals(myBoard[j][j]) && !myBoard[0][0].equals(EMPTY))
count++;
System.out.println(count);
if (count >= myBoard.length)
return myBoard[0][0];
count = 0;
for (int j = myBoard.length-1; j >= 0; j--)
if (myBoard[0][myBoard.length-1].equals(myBoard[j][j]) && !myBoard[0][myBoard.length-1].equals(EMPTY))
count++;
System.out.println(count);
if (count >= myBoard.length)
return myBoard[0][myBoard.length-1];
count = 0; -
Need some help with Tic Tac Toe game
hey. hope u guys can help me out...
having a problem with my tic tac toe program...
i have 2 problems.
1) got the "X" and "O" to appear using a flag(teacher didn't explain)
using code like this
if (jb == button[0]){
if (flag==0)
button[0].setText("X");
else
button[0].setText("O");
//toggle
flag = (flag==0)?1:0;
my problem is how do i get it to stop.(For example button[1] is selected as "X"..how do i stop it from albe to switch to "O")
2) found this code in javascript online and i want to do what it does in java code
if(button[0] == " X " && button[1] == " X " && button[2] == " X ")
alert("You Win!");
reset();
how would i do that?
thanks for the help.ok here's my code:
//TTT.java
import javax.swing.*;
import java.awt.*;
import java .awt.event.*;
public class TTT extends JFrame
implements WindowListener, ActionListener
private JFrame frFirst;
private Container cnFirst,cnSecond;
private JButton button[]=new JButton[9];
private JButton btnNewGame,btnExit;
private FlowLayout southLayout;
private JPanel southPanel;
private int flag;
public TTT()
frFirst=new JFrame ("Michael's Tic Tac Toe Game!");
cnFirst=frFirst.getContentPane();
cnFirst.setLayout (new GridLayout (4,4));
cnFirst.setBackground(Color.green);
for(int i=0;i<button.length;i++)
button[i] = new JButton();
cnFirst.add(button);
flag=0;
southPanel = new JPanel ();
btnNewGame = new JButton ("New Game");
southPanel.add (btnNewGame);
btnExit = new JButton ("EXIT");
southPanel.add (btnExit);
frFirst.add (southPanel,BorderLayout.SOUTH);
frFirst.setLocation(200, 200);
frFirst.setSize(400,400);
frFirst.setResizable(false);
frFirst.setVisible(true);
this.frFirst.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// listeners
frFirst.addWindowListener(this);
button[0].addActionListener(this);
button[1].addActionListener(this);
button[2].addActionListener(this);
button[3].addActionListener(this);
button[4].addActionListener(this);
button[5].addActionListener(this);
button[6].addActionListener(this);
button[7].addActionListener(this);
button[8].addActionListener(this);
btnNewGame.addActionListener (this);
btnExit.addActionListener (this);
//define methods of WindowListener
public void windowOpened(WindowEvent we)
public void windowClosing(WindowEvent we)
System.exit(0);
public void windowClosed(WindowEvent we)
public void windowIconified(WindowEvent we)
public void windowDeiconified(WindowEvent we)
public void windowActivated(WindowEvent we)
public void windowDeactivated(WindowEvent we)
public void actionPerformed(ActionEvent ae)
//making the X and O to appear on JButtons
Object obj = ae.getSource();
if (obj instanceof JButton){
JButton jb = (JButton)obj;
if (jb == button[0])
if (flag==0)
button[0].setText("X");
else
button[0].setText("O");
//toggle
flag = (flag==0)?1:0;
if(jb==button[1])
if (flag==0)
button[1].setText("X");
else
button[1].setText("O");
//toggle
flag = (flag==0)?1:0;
if(jb==button[2])
if (flag==0)
button[2].setText("X");
else
button[2].setText("O");
//toggle
flag = (flag==0)?1:0;
if(jb==button[3])
if (flag==0)
button[3].setText("X");
else
button[3].setText("O");
//toggle
flag = (flag==0)?1:0;
if(jb==button[4])
if (flag==0)
button[4].setText("X");
else
button[4].setText("O");
//toggle
flag = (flag==0)?1:0;
if(jb==button[5])
if (flag==0)
button[5].setText("X");
else
button[5].setText("O");
//toggle
flag = (flag==0)?1:0;
if(jb==button[6])
if (flag==0)
button[6].setText("X");
else
button[6].setText("O");
//toggle
flag = (flag==0)?1:0;
if(jb==button[7])
if (flag==0)
button[7].setText("X");
else
button[7].setText("O");
//toggle
flag = (flag==0)?1:0;
if(jb==button[8])
if (flag==0)
button[8].setText("X");
else
button[8].setText("O");
//toggle
flag = (flag==0)?1:0;
//New Game To Reset
if (ae.getSource () == btnNewGame)
/* String text = JOptionPane.showInputDialog(null,"Do You Want To Start A New Game?","Michael's Tic Tac Toe Game!",JOptionPane.WARNING_MESSAGE);
String YES;
if (text == YES)
JOptionPane.showMessageDialog(null,"Do You","Michael's Tic Tac Toe Game!",JOptionPane.WARNING_MESSAGE);
else{
add code to reset game
//Exit Button to Exit
if (ae.getSource () == btnExit)
JOptionPane.showMessageDialog(null,"Thanks For Playing!","Michael's Tic Tac Toe Game!",JOptionPane.INFORMATION_MESSAGE);
this.setVisible(false);
System.exit(0);
} //end of if instanceof
public static void main(String[]args)
//instantiate GUI
new TTT(); -
Why do I keep getting the following errors in a very simple, basic TIC TAC TOE program? Any help would be greatly appreciated. Thanks.
C:\Class\Teresa\TicTacToe017.java:114: 'else' without 'if'
else if (board[turnRow - 1][turnCol - 1] == 'X'
^
C:\Class\Teresa\TicTacToe017.java:185: 'else' without 'if'
else // Next player's turn
^
C:\Class\Teresa\TicTacToe017.java:39: cannot resolve symbol
symbol : method call ()
location: class TicTacToe017
call();
^
C:\Class\Teresa\TicTacToe017.java:145: cannot resolve symbol
symbol : method writeBoard ()
location: class TicTacToe017
writeBoard();
^
C:\Class\Teresa\TicTacToe017.java:165: cannot resolve symbol
symbol : method writeBoard ()
location: class TicTacToe017
writeBoard();
^
C:\Class\Teresa\TicTacToe017.java:181: cannot resolve symbol
symbol : method writeBoard ()
location: class TicTacToe017
writeBoard();
^
6 errors
Tool completed with exit code 1
Here is my code so far.
File name: TicTacToe.java
A class to play TicTacToe.
Entries cannot be changed once they are entered.
Written by: Lew Rakocy
email address: [email protected]
Date: 9/2/00
Changes: 03/13/2003 Made comments like text examples.
Added code to display board after win and draw.
public class TicTacToe017
// Use a 3 X 3 (two-dimensional) array for the game board.
private static char[][] board = new char[3][3];
private static char turn;
private static int row; // Loop controls to
private static int col; // display the board
private static int turnRow; // User input to
private static int turnCol; // select move
private static boolean entryError;
private static boolean anotherGame = true;
private static char repeat; // User input: y or Y to repeat
private static int entryCount = 0; // Game ends when board is full
// (when entryCount = 9);
public static void main(String[] args)
while(anotherGame)
newGame();
while(!winner())
//WRITE THE METHOD CALL TO DISPLAY THE "BOARD" HERE
call();
System.out.println("This is the game board.");
//WRITE THE METHOD CALL FOR THE "PLAY" OF THE GAME HERE
System.out.print("Welcome to Teresa's Tic Tac Toe!");
System.out.println("Another game? Enter Y or y for yes.");
repeat = SavitchIn.readLineNonwhiteChar();
//WRITE THE IF/ELSE STATEMENT TO PLAY ANOTHER GAME HERE
if ((repeat == 'Y') || (repeat == 'y'))
System.out.println("Play another game.");
else
System.out.println("End of game. Thanks for playing.");
//WRITE THE HEADER FOR THE writeBoard METHOD HERE
System.out.println("-----------------");
System.out.println("|R\\C| 1 | 2 | 3 |");
System.out.println("-----------------");
for(row = 0; row < 3; ++row)
System.out.println("| " + (row + 1)
+ " | " + board[row][0]
+ " | " + board[row][1]
+ " | " + board[row][2]
+ " |");
System.out.println("-----------------");
private static void getMove()
entryError = true; // Will change to false if valid row
// and column numbers are entered.
while(entryError)
System.out.println();
System.out.println(turn + "'s turn.");
System.out.println("Where do what your " + turn + " placed?");
System.out.println(
"Please enter row number and column number"
+ " separated by a space.");
System.out.println();
turnRow = SavitchIn.readInt();
turnCol = SavitchIn.readInt();
System.out.println("You have entered row #" + turnRow);
System.out.println(" and column #" + turnCol);
// Check for proper range (1, 2, or 3)
//WRITE THE IF STATEMENT HERE FOR AN INVALID ENTRY
if (board[turnRow - 1][turnCol - 1] > 3)
System.out.println("Invalid entry: try again.");
System.out.println(
"Row & column numbers must be either 1, 2, or 3.");
// Check to see if it is already occupied
// Adjust turnRow and turnCol for 0-numbering in array
else if (board[turnRow - 1][turnCol - 1] == 'X'
|| board[turnRow - 1][turnCol - 1] == 'O')
System.out.println("That cell is already taken.");
System.out.println("Please make another selection.");
else // Valid entry
entryError = false;
System.out.println("Thank you for your selection.");
board[turnRow - 1][turnCol - 1] = turn;
++entryCount;
private static boolean winner()
// Row checks
for(row = 0; row < 3; ++row)
if(board[row][0] == turn)
if(board[row][1] == turn)
if(board[row][2] == turn)
System.out.println();
System.out.println (turn + " IS THE WINNER!!!");
writeBoard();
return true;
// WRITE A FOR LOOP FOR THE COLUMN CHECKS HERE
// WRITE A FOR LOOP FOR THE DIAGONAL CHECKS HERE
if(board[0][2] == turn)
if(board[1][1] == turn)
if(board[2][0] == turn)
System.out.println();
System.out.println (turn + " IS THE WINNER!!!");
writeBoard();
return true;
// These lines execute only if there is no winner.
// End game if board is full
//WRITE THE IF STATEMENT TO CHECK IF THE BOARD IS FULL
if (entryCount == 9)
System.out.println();
System.out.println("Draw: no winner and board is full.");
writeBoard();
return true;
else // Next player's turn
//WRTITE THE IF/ELSE STATEMENT FOR THE NEXT PLAYER'S TURN
return false;
private static void newGame()
System.out.println();
System.out.println("New Game: X goes first.");
turn = 'O'; // Turn will change to X when winner() is called
// Clear the board
for(row = 0; row < 3; ++row)
for(col = 0; col < 3; ++col)
board[row][col] = ' ';
entryCount = 0;
System.out.println();the "else without if" means that you have an else statement that wasn't attached to an if statement. In your case, it seems to be because you had multiple statements following an if statement, and you didn't enclose them in a single block.
The "cannot resolve symbol" means that you referred to something that wasn't defined. Either it's your code, and you forgot to define it, or you were referring to someone else's code, in which case you probably forgot an import statement, or you're using their code incorrectly. -
Tic-Tac-Toe checkWinner method problem
there seems to be a problem with the check winner method that I have, and the game isnt exactly playing out the way its supposed to. Any idea? By the way the game is a grid so the top left spot is 0,0, and the bottom spot is 2,2. It will as you to input a row and a column so you can put 1,0. Thanks for the help.
import javax.swing.*;
import java.text.*;
import java.applet.*;
import java.io.*;
import java.awt.*;
import java.lang.*;
import java.util.*;
import java.math.*;
import java.sql.*;
import java.security.*;
import java.beans.*;
import javax.crypto.*;
import javax.net.*;
import org.omg.CORBA.*;
import java.awt.color.*;
import java.util.jar.*;
public class TwoDArray
String [] [] board=new String [3] [3];
int x;
public TwoDArray()
for(int x=0;x<3;x++)
for(int y=0;y<3;y++)
board[x][y]="";
public void getMove(int row, int col, String letter)
if(board[row][col].equalsIgnoreCase(""));
board[row][col]=letter;
x++;
public void printBoard()
for(int x=0;x<3;x++)
System.out.print("|");
for(int y=0;y<3;y++)
System.out.print(board[x][y]);
System.out.println("|");
public boolean checkWinner()
boolean win=false;
if(board[0][0].equalsIgnoreCase(board[0][1])&&board[0][0].equalsIgnoreCase(board[0][2]))
win=true;
return win;
if(board[0][0].equalsIgnoreCase(board[1][0])&&board[0][0].equalsIgnoreCase(board[2][0]))
win=true;
return win;
if(board[0][1].equalsIgnoreCase(board[1][1])&&board[0][1].equalsIgnoreCase(board[2][1]))
win=true;
return win;
if(board[0][2].equalsIgnoreCase(board[1][2])&&board[0][2].equalsIgnoreCase(board[2][2]))
win=true;
return win;
if(board[1][0].equalsIgnoreCase(board[1][1])&&board[1][0].equalsIgnoreCase(board[1][2]))
win=true;
return win;
if(board[2][0].equalsIgnoreCase(board[2][1])&&board[2][0].equalsIgnoreCase(board[2][2]))
win=true;
return win;
if(board[0][0].equals(board[1][1])&&board[0][0].equalsIgnoreCase(board[2][2]))
win=true;
return win;
if(board[2][0].equals(board[1][1])&&board[2][0].equalsIgnoreCase(board[0][2]))
win=true;
return win;
return win;
public static void main(String[] args)
boolean winner=false;
String player1="X";
String player2="O";
String instructions="Welcome to Tic-Tac-Toe.";
for (int i = 0;i<instructions.length() ;i++ )
System.out.print(instructions.charAt(i));
try
Thread.sleep(99);
}catch(InterruptedException e) {e.printStackTrace();}
System.out.println();
TwoDArray board=new TwoDArray();
String input1=JOptionPane.showInputDialog("Enter the row you wish to move in.");
int rowmove=Integer.parseInt(input1);
String input2=JOptionPane.showInputDialog("Enter the column you wish to move in.");
int colmove=Integer.parseInt(input2);
board.getMove(rowmove,colmove,player1);
board.printBoard();
while(winner==board.checkWinner())
String input3=JOptionPane.showInputDialog("Enter the row you wish to move in.");
int rowmove2=Integer.parseInt(input3);
String input4=JOptionPane.showInputDialog("Enter the column you wish to move in.");
int colmove2=Integer.parseInt(input4);
board.getMove(rowmove2,colmove2,player2);
board.printBoard();
String input5=JOptionPane.showInputDialog("Enter the row you wish to move in.");
int rowmove3=Integer.parseInt(input5);
String input6=JOptionPane.showInputDialog("Enter the column you wish to move in.");
int colmove3=Integer.parseInt(input6);
board.getMove(rowmove3,colmove3,player1);
board.printBoard();
System.out.println("YOU WON!!");
}Take a look at this code:
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 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, String letter) {
if (board[row][col].equals(EMPTY)) {
board[row][col] = letter;
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[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][0].equals(EMPTY)) {
return board[0][2];
return EMPTY;
static public void drawOutString(String str) {
for (int i = 0; i < str.length(); i++) {
System.out.print(str.charAt(i));
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
static public void main(String[] args) {
init();
drawOutString("Welcome to Tic-Tac-Toe.");
System.out.println();
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, PLAYER1);
printBoard();
} while(winner().equals(EMPTY));
System.out.println("YOU WON!!"); -
I am a beginner Java programmer, and I need help with my tic tac toe code.
import javax.swing.JOptionPane;
* Created on Nov 14, 2006
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
* @author jye
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
public class TicTacToe {
public static void main(String[] args) {
int[][]matrix = {{0,1,2},{3,4,5},{6,7,8}};
while (true)
System.out.println(); //keeps the tables seperate
for(int row = 0; row<matrix.length;row++)
for(int col = 0; col < matrix[row].length;col++)
if (matrix[row][col]!=-1 && matrix[row][col]!=-2) //Compares each element to -1 and and -2, if not, then it just prints out the regular number
System.out.print(matrix[row][col] + " ");
if (matrix[row][col]==-1)
System.out.print("X" + " ");
if (matrix[row][col]==-2)
System.out.print("O" + " ");
System.out.println();
int p1 = Integer.parseInt(JOptionPane.showInputDialog (null, "Enter number 1"));
int p2 = Integer.parseInt(JOptionPane.showInputDialog (null, "Enter number 2"));
for(int row = 0; row<matrix.length;row++) //this piece of code refers to above print code
for(int col = 0; col < matrix[row].length;col++)
if (p1==matrix[row][col]) //compares each element in array to the position inputted. If it is equal to the number inputted, then it changes that to -1. For example, the postition of 4 is [1][1], it will replace [1][1] with -1. The matrix[row][col] is a position.
matrix[row][col]=-1;
if(p2==matrix[row][col])
matrix[row][col]=-2;
for(int row = 0; row<matrix.length;row++)
for(int col = 0; col < matrix[row].length;col++)
if(matrix[0][0]==-1 && matrix[0][1]==-1 && matrix[0][2]==-1)
System.out.println("Player 1 wins.");break;
if(matrix[1][0]==-1 && matrix[1][1]==-1 && matrix[1][2]==-1)
System.out.println("Player 1 wins.");break;
if(matrix[2][0]==-1 && matrix[2][1]==-1 && matrix[2][2]==-1)
System.out.println("Player 1 wins.");break;
if(matrix[0][0]==-1 && matrix[1][0]==-1 && matrix[2][0]==-1)
System.out.println("Player 1 wins.");break;
if(matrix[0][1]==-1 && matrix[1][1]==-1 && matrix[2][1]==-1)
System.out.println("Player 1 wins.");break;
if(matrix[0][2]==-1 && matrix[1][2]==-1 && matrix[2][2]==-1)
System.out.println("Player 1 wins.");break;
if(matrix[0][0]==-1 && matrix[1][1]==-1 && matrix[2][2]==-1);
System.out.println("Player 1 wins.");break;
if(matrix[0][2]==-1 && matrix[1][1]==-1 && matrix[2][0]== -1)
System.out.println("Player 1 wins.");break; //I GET A "UNREACHEABLE CODE" ERROR HERE
if(matrix[0][0]==-2 && matrix[0][1]==-2 && matrix[0][2]==-2)
System.out.println("Player 2 wins.");break;
if(matrix[1][0]==-2 && matrix[1][1]==-2 && matrix[1][2]==-2)
System.out.println("Player 2 wins.");break;
if(matrix[2][0]==-2 && matrix[2][1]==-2 && matrix[2][2]==-2)
System.out.println("Player 2 wins.");break;
if(matrix[0][0]==-2 && matrix[1][0]==-2 && matrix[2][0]==-2)
System.out.println("Player 2 wins.");break;
if(matrix[0][1]==-2 && matrix[1][1]==-2 && matrix[2][1]==-2)
System.out.println("Player 2 wins.");break;
if(matrix[0][2]==-2 && matrix[1][2]==-2 && matrix[2][2]==-2)
System.out.println("Player 2 wins.");break;
if(matrix[0][0]==-2 && matrix[1][1]==-2 && matrix[2][2]==-2);
System.out.println("Player 2 wins.");break;
if(matrix[0][2]==-2 && matrix[1][1]==-2 && matrix[2][0]== -2)
System.out.println("Player 2 wins.");break;//I GET A "UNREACHEABLE CODE" ERROR HERE
}Why do I get a unreachable error code???
Thanks.Just in case you are tired I mean this (from the ending bit of your code)
if(matrix[0][0]==-2 && matrix[1][1]==-2 && matrix[2][2]==-2);// <== PROBLEM RIGHT HERE
System.out.println("Player 2 wins.");break;
if(matrix[0][2]==-2 && matrix[1][1]==-2 && matrix[2][0]== -2)
System.out.println("Player 2 wins.");break;//I GET A "UNREACHEABLE CODE" ERROR HERE
}And same earlier on. -
Hi, I have been trying to create a simple Tic Tac Toe game using Java. I'm currently having problems as to how to create the board using arrays (sorry I don't understand them very well). All I have so far is this,
public class ticTacToe {
private int [] [] theBoard = new int [3] [3];
// *'N' is no winner
// 'X' is X won
// 'O' is O won
// 'C' is a cat's game
public static char didSomeoneWin(int [] [] currentBoard)
int winForX = 8000, winForO = 1, checkIfItsAcatsGame = 1, product;
char winner = 'N';
for(int column = 0; column < 3; column++) // Check the columns
product = currentBoard [0] [column] * currentBoard [1] [column] * currentBoard [2] [column];
if(product == winForX) winner = 'X';
if(product == winForO) winner = 'O';
for(int row = 0; row < 3; row++) // Check the rows
product = currentBoard [row] [0] * currentBoard [row] [1] * currentBoard [row] [2];
if(product == winForX) winner = 'X';
if(product == winForO) winner = 'O';
product = currentBoard [0] [0] * currentBoard [1] [1] * currentBoard [2] [2]; // Check one diagonal
if(product == winForX) winner = 'X';
if(product == winForO) winner = 'O';
product = currentBoard [0] [2] * currentBoard [1] [1] * currentBoard [2] [0]; // Check the other diagonal
if(product == winForX) winner = 'X';
if(product == winForO) winner = 'O';
if(winner == 'N') // If nobody's won, Check for a cat's game
for(int row = 0; row < 3; row++)
for(int column = 0; column < 3; column++)
checkIfItsAcatsGame *=currentBoard [row] [column];
if(checkIfItsAcatsGame != 0) winner = 'C'; // any empty space is a zero. So product is zero if there is space left.
return winner;
public void markX(int row, int column)
myBoard [row] [column] = 20;
public void markO(int row, int column)
myBoard [row] [column] = 1;
That is all so far, could someone help me print out the board? And help me out on the arrays? I don't think they are quite right. Thanks in Advance!
Message was edited by:
matthews1.7.2.0Hi,
Do you need a GUI ?
If yes see http://java.sun.com/docs/books/tutorial/uiswing/index.html
You can also see this : http://www.apl.jhu.edu/~hall/java/Swing-Tutorial/Swing-Tutorial-Printing.html about printing.
--Marc (http://jnative.sf.net) -
Tic Tac Toe....HELP ME!!
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import java.util.Random;
public class TicTacToe extends JFrame {
private Board board;
static final char BLANK=' ', O='O', X='X';
private char position[]={ // Board position (BLANK, O, or X)
BLANK, BLANK, BLANK,
BLANK, BLANK, BLANK,
BLANK, BLANK, BLANK};
private int wins=0, losses=0, draws=0; // game count by user
// Start the game
public static void main(String args[]) {
new TicTacToe();
// Constructor of TicTacToe: Initialize settings
public TicTacToe() {
super("Tic Tac Toe");
add(board=new Board(), BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
setVisible(true);
// Board is what actually plays and displays the game
private class Board extends JPanel implements MouseListener {
// Constructor of Board
public Board() {
addMouseListener(this);
// Redraw the board
public void paintComponent(Graphics g) {
super.paintComponent(g);
int w=getWidth();
int h=getHeight();
Graphics2D g2d = (Graphics2D) g;
// Draw the grid
g2d.setPaint(Color.WHITE);
g2d.fill(new Rectangle2D.Double(0, 0, w, h));
g2d.setPaint(Color.BLACK);
g2d.setStroke(new BasicStroke(4));
g2d.draw(new Line2D.Double(0, h/3, w, h/3));
g2d.draw(new Line2D.Double(0, h*2/3, w, h*2/3));
g2d.draw(new Line2D.Double(w/3, 0, w/3, h));
g2d.draw(new Line2D.Double(w*2/3, 0, w*2/3, h));
// Draw the Os and Xs
for (int i=0; i<9; ++i) {
double xpos=(i%3+0.5)*w/3.0;
double ypos=(i/3+0.5)*h/3.0;
double xr=w/8.0;
double yr=h/8.0;
if (position==O) {
g2d.setPaint(Color.BLUE);
g2d.draw(new Ellipse2D.Double(xpos-xr, ypos-yr, xr*2, yr*2));
else if (position[i]==X) {
g2d.setPaint(Color.RED);
g2d.draw(new Line2D.Double(xpos-xr, ypos-yr, xpos+xr, ypos+yr));
g2d.draw(new Line2D.Double(xpos-xr, ypos+yr, xpos+xr, ypos-yr));
// Draw an O where the mouse is clicked
public void mouseClicked(MouseEvent e) {
int xpos=e.getX()*3/getWidth();
int ypos=e.getY()*3/getHeight();
int pos=xpos+3*ypos;
if (pos>=0 && pos<9 && position[pos]==BLANK) {
position[pos]=O;
repaint();
putX(); // computer plays
repaint();
// Ignore other mouse events
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
// Computer plays X
public void putX() {
// Check if game is over
if (won(O))
newGame(O);
else if (isDraw())
newGame(BLANK);
// Play X, possibly ending the game
else {
nextMove();
if (won(X))
newGame(X);
else if (isDraw())
newGame(BLANK);
// Play X in one of the empty spot
public void nextMove() {
int r;
do {
Random random=new Random();
r=random.nextInt(9); // move randomly
} while (position[r]!=BLANK);
position[r]=X;
// Return true if player has won
public boolean won(char player) {
bold// ********** put your code here **********
// ......if else
return false;
// Are all 9 spots filled? Return true if yes
public boolean isDraw() {
bold// ********** put your code here **********
// ......if else
return false;
// Start a new game
public void newGame(char winner) {
repaint();
// Announce result of last game. Ask user to play again.
String result;
if (winner==O) {
++wins;
result = "You Win!";
else if (winner==X) {
++losses;
result = "I Win!";
else {
result = "Tie";
++draws;
if (JOptionPane.showConfirmDialog(null,
"You have "+wins+ " wins, "+losses+" losses, "+draws+" draws\n"
+"Play again?", result, JOptionPane.YES_NO_OPTION)
!=JOptionPane.YES_OPTION) {
System.exit(0);
// Clear the board to start a new game
for (int j=0; j<9; ++j)
position[j]=BLANK;
// Computer starts first every other game
if ((wins+losses+draws)%2 == 1)
nextMove();
} // end inner class Board
} // end class TicTacToe
CAN YOU ALL PLEASE HELP ME TO FILL IN THE CODE AT THE MIDDLE??(put your code here)
THANK YOU SO MUCH><Multipost:
http://forum.java.sun.com/thread.jspa?threadID=5247071
Would you please shut the fsck up? -
Help with printing a tic tac toe board (using a loop to print)
hey im making the smiple game tic tac toe and im tryin to print out the board after each turn. I have a 2d array called char which is a 3 by 3 array and i dont know how i would make a for loop to print out the x's and o's in their right spot and still have the board look like a normal tic tac toe board. When the board is printing the x's and o's are already in the 2d char array board.So basically what i want to happen is after player 1's turn is up wherever he put the x replace the number on the board with an x and keep the rest the same and whenever player 2's turn is up wherever he put the o replace the number on the board with an o and keep the rest the same. Any help would be awesome thanks alot.
Here is the code to the program (i know i use if statements to much its a bad habit of mine)
import java.util.*;
public class Tictactoe
private char board [] [] = new board [3] [3];
private int X;
private int O;
private Scanner p1choice;
private Scanner p2choice;
Scanner input = new Scanner(System.in);
public Tictactoe()
p1choice = new Scanner(System.in);
p2choice = new Scanner(System.in);
play();
public void play()
printoriginalboard();
public void printoriginalboard()
System.out.println(" | | ");
System.out.println(" 3 | 2 | 1 ");
System.out.println("____|____|____");
System.out.println(" | | ");
System.out.println(" 6 | 5 | 4 ");
System.out.println(" | | ");
System.out.println("____|____|____");
System.out.println(" | | ");
System.out.println(" 9 | 8 | 7 ");
System.out.println(" | | ");
System.out.println("This is the classic game of tictactoe simply pick a number 1 through 9 to place an x or an o in that area.");
player1turn();
public void player1turn()
System.out.println("Player 1 pick an area to place an X");
int p1choice= p1choice.nextInt();
if(p1choice == 1 && p2choice == 1 || p1choice == 1){
System.out.println("This spot has already been taken");
else
board[0][2] = 'x';
pintboard();
if(p1choice == 2 && p2choice == 2 || p1choice == 2){
System.out.println("This spot has already been taken");
else
board[1][2] = 'x';
pintboard();
if(p1choice == 3 && p2choice == 3 || p1choice == 3){
System.out.println("This spot has already been taken");
else
board[2][2] = 'x';
pintboard();
if(p1choice == 4 && p2choice == 4 || p1choice == 4){
System.out.println("This spot has already been taken");
board[0][1] = 'x';
pintboard();
if(p1choice == 5 && p2choice == 5 || p1choice == 5){
System.out.println("This spot has already been taken");
else
board[1][1] = 'x';
pintboard();
if(p1choice == 6 && p2choice == 6 || p1choice == 6){
System.out.println("This spot has already been taken");
else
board[2][1] = 'x';
pintboard();
if(p1choice == 7 && p2choice == 7 || p1choice == 7){
System.out.println("This spot has already been taken");
else
board[0][0] = 'x';
pintboard();
if(p1choice ==8 && p2choice == 8 || p1choice == 8){
System.out.println("This spot has already been taken");
else
board[1][0] = 'x';
pintboard();
if(p1choice == 9 && p2choice == 9 || p1choice == 9){
System.out.println("This spot has already been taken");
else
board[2][0] = 'x';
pintboard();
public void p2turn()
System.out.println("Pick an area to place an O");
int p2choice = p2choice.nextInt();
if(p2choice == 1 && p1choice == 1 || p2choice == 1){
System.out.println("This spot has already been taken");
else
board[0][2] = 'o';
pintboard();
if(p2choice == 2 && p1choice == 2 || p2choice == 2){
System.out.println("This spot has already been taken");
else
board[1][2] = 'o';
pintboard();
if(p2choice == 3 && p1choice == 3 || p2choice == 3){
System.out.println("This spot has already been taken");
else
board[2][2] = 'o';
pintboard();
if(p2choice == 4 && p1choice == 4 || p2choice == 4){
System.out.println("This spot has already been taken");
else
board[0][1] = 'o';
pintboard();
if(p2choice == 5 && p1choice == 5 || p2choice == 5){
System.out.println("This spot has already been taken");
else
board[1][1] = 'o';
pintboard();
if(p2choice == 6 && p1choice == 6 || p2choice == 6){
System.out.println("This spot has already been taken");
else
board[2][1] = 'o';
pintboard();
if(p2choice == 7 && p1choice == 7 || p2choice == 7){
System.out.println("This spot has already been taken");
else
board[0][0] = 'o';
pintboard();
if(p2choice == 8 && p1choice == 8 || p2choice == 8){
System.out.println("This spot has already been taken");
else
board[1][0] = 'o';
pintboard();
if(p2choice == 9 && p1choice == 9 || p2choice == 9){
System.out.println("This spot has already been taken");
else
board[2][0] = 'o';
pintboard();
public void pintboard()
{Anyway the answer is that you are trying to create an array of char as there is no such thing as a board[3][3].
One of the best tools a programmer can do is learn how to break a big problem into little problems and work on each little problem in isolation, and then when finished combining the solutions together into the final program. You big mistake that I see here is trying to bite off more than you can chew: trying to create a whole functioning interactive program from just one class. Why give yourself a task that would be difficult even for an experienced java programmer? I suggest that you break this down into logical parts and try to solve the smaller problems before worrying about the whole. For instance, if I were doing something like this, I'd create a class called TTTBoard that encapsulated the tic tac toe board and nothing but the board. I'd think of it as an entity. When I wanted the current state of the board, I'd query the board via a method such as getCurrentState. I'd have methods for checking if position is free, for placing an x/o in a spot, for checking for win, etc... Then I'd create a user interface class where I'd give the users a choice and get their responses. I'd probably create a Game class to control it all. While this all seems daunting, you are trying to do essentially the same thing, but all in one huge class. My recommendation: study OOPs and learn to do it the smart way. Good luck. -
Help in swing app. tic tac toe
Trying to make this tic tac toe game. Need a little help. I want the newGameBUT to start the game over, and I would like turnTF to display if a tie occurs. (I tried using *if button.enabled(false) {* but it didn't work. If anyone could help me out, that'd be great. Oh, also, the new game button currently add's 1 to whoever won so far, which is really weird =x. Thanks beforehand.
import java.awt.*; //import
import javax.swing.*; //import
import java.awt.event.*; //import
import java.awt.Rectangle; //import
import java.awt.Font; //import
import javax.swing.BorderFactory; //import
import javax.swing.border.TitledBorder; //import
import java.awt.Color; //import
public class TicTacToeFrame extends JFrame implements ActionListener {
public TicTacToeFrame() {
try { //try the following
jbInit();
} catch (Exception ex) { // exit on [X]
ex.printStackTrace(); //exit and print errors
int xWon = 0; //counting how many times O has won
int oWon = 0; //counting how many times X has one
double i = 0; // loop variable to determine turn
public void actionPerformed(ActionEvent e) {
String turn = "null"; //current turn
String notTurn = "null"; //not current turn
newGameBUT.setEnabled(false); //disable new game button
if (i % 2 == 0) { // for determining who's turn it is
turn = "X"; // X's turn when counter is even
notTurn = "O"; //notTurn used to show who's turn it is in turnTF
if (i % 2 != 0) { // for determining who's turn it is
turn = "O"; // O's turn when counter is odd
notTurn = "X"; //notTurn used to show who's turn it is in turnTF
turnTF.setText("Currently " + notTurn + "'s turn"); // displays turn
if (e.getSource() == sqOneBUT) { //disable and print X or O to button
sqOneBUT.setText(turn); //printing players symbol
sqOneBUT.setEnabled(false); //disabling button
if (e.getSource() == sqTwoBUT) { //disable and print X or O to button
sqTwoBUT.setText(turn); //printing players symbol
sqTwoBUT.setEnabled(false); //disabling button
if (e.getSource() == sqThreeBUT) { //disable and print X or O to button
sqThreeBUT.setText(turn); //printing players symbol
sqThreeBUT.setEnabled(false); //disabling button
if (e.getSource() == sqFourBUT) { //disable and print X or O to button
sqFourBUT.setText(turn); //printing players symbol
sqFourBUT.setEnabled(false); //disabling button
if (e.getSource() == sqFiveBUT) { //disable and print X or O to button
sqFiveBUT.setText(turn); //printing players symbol
sqFiveBUT.setEnabled(false); //disabling button
if (e.getSource() == sqSixBUT) { //disable and print X or O to button
sqSixBUT.setText(turn); //printing players symbol
sqSixBUT.setEnabled(false); //disabling button
if (e.getSource() == sqSevenBUT) { //disable and print X or O to button
sqSevenBUT.setText(turn); //printing players symbol
sqSevenBUT.setEnabled(false); //disabling button
if (e.getSource() == sqEightBUT) { //disable and print X or O to button
sqEightBUT.setText(turn); //printing players symbol
sqEightBUT.setEnabled(false); //disabling button
if (e.getSource() == sqNineBUT) { //disable and print X or O to button
sqNineBUT.setText(turn); //printing players symbol
sqNineBUT.setEnabled(false); //disabling button
String sqOne = sqOneBUT.getText(); // Strings to read to find winner
String sqTwo = sqTwoBUT.getText(); // Strings to read to find winner
String sqThree = sqThreeBUT.getText(); // Strings to read to find winner
String sqFour = sqFourBUT.getText(); // Strings to read to find winner
String sqFive = sqFiveBUT.getText(); // Strings to read to find winner
String sqSix = sqSixBUT.getText(); // Strings to read to find winner
String sqSeven = sqSevenBUT.getText(); // Strings to read to find winner
String sqEight = sqEightBUT.getText(); // Strings to read to find winner
String sqNine = sqNineBUT.getText(); // Strings to read to find winner
OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~O WINS~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
//horizontal, top, o wins
if (sqOne == "O") { //checking too see if player O has won
if (sqFour == "O") {
if (sqSeven == "O") {
turnTF.setText("O wins!"); //O wins text
sqOneBUT.setEnabled(false); //disable all buttons
sqTwoBUT.setEnabled(false); //disable all buttons
sqThreeBUT.setEnabled(false); //disable all buttons
sqFourBUT.setEnabled(false); //disable all buttons
sqFiveBUT.setEnabled(false); //disable all buttons
sqSixBUT.setEnabled(false); //disable all buttons
sqSevenBUT.setEnabled(false); //disable all buttons
sqEightBUT.setEnabled(false); //disable all buttons
sqNineBUT.setEnabled(false); //disable all buttons
//vertical, left, o wins
if (sqOne == "O") { //checking too see if player O has won
if (sqTwo == "O") {
if (sqThree == "O") {
turnTF.setText("O wins!"); //O wins text
sqOneBUT.setEnabled(false); //disable all buttons
sqTwoBUT.setEnabled(false); //disable all buttons
sqThreeBUT.setEnabled(false); //disable all buttons
sqFourBUT.setEnabled(false); //disable all buttons
sqFiveBUT.setEnabled(false); //disable all buttons
sqSixBUT.setEnabled(false); //disable all buttons
sqSevenBUT.setEnabled(false); //disable all buttons
sqEightBUT.setEnabled(false); //disable all buttons
sqNineBUT.setEnabled(false); //disable all buttons
// diagonal, top left to bottom right, o wins
if (sqOne == "O") {
if (sqFive == "O") { //checking too see if player O has won
if (sqNine == "O") {
turnTF.setText("O wins!"); //O wins text
sqOneBUT.setEnabled(false); //disable all buttons
sqTwoBUT.setEnabled(false); //disable all buttons
sqThreeBUT.setEnabled(false); //disable all buttons
sqFourBUT.setEnabled(false); //disable all buttons
sqFiveBUT.setEnabled(false); //disable all buttons
sqSixBUT.setEnabled(false); //disable all buttons
sqSevenBUT.setEnabled(false); //disable all buttons
sqEightBUT.setEnabled(false); //disable all buttons
sqNineBUT.setEnabled(false); //disable all buttons
// horizontal, mid, o wins
if (sqTwo == "O") { //checking too see if player O has won
if (sqFive == "O") {
if (sqEight == "O") {
turnTF.setText("O wins!"); //O wins text
sqOneBUT.setEnabled(false); //disable all buttons
sqTwoBUT.setEnabled(false); //disable all buttons
sqThreeBUT.setEnabled(false); //disable all buttons
sqFourBUT.setEnabled(false); //disable all buttons
sqFiveBUT.setEnabled(false); //disable all buttons
sqSixBUT.setEnabled(false); //disable all buttons
sqSevenBUT.setEnabled(false); //disable all buttons
sqEightBUT.setEnabled(false); //disable all buttons
sqNineBUT.setEnabled(false); //disable all buttons
// horizontal, bottom, o wins
if (sqThree == "O") { //checking too see if player O has won
if (sqSix == "O") {
if (sqNine == "O") {
turnTF.setText("O wins!"); //O wins text
sqOneBUT.setEnabled(false); //disable all buttons
sqTwoBUT.setEnabled(false); //disable all buttons
sqThreeBUT.setEnabled(false); //disable all buttons
sqFourBUT.setEnabled(false); //disable all buttons
sqFiveBUT.setEnabled(false); //disable all buttons
sqSixBUT.setEnabled(false); //disable all buttons
sqSevenBUT.setEnabled(false); //disable all buttons
sqEightBUT.setEnabled(false); //disable all buttons
sqNineBUT.setEnabled(false); //disable all buttons
// diagonal, top right to bottom left, o wins
if (sqThree == "O") { //checking too see if player O has won
if (sqFive == "O") {
if (sqSeven == "O") {
turnTF.setText("O wins!"); //O wins text
sqOneBUT.setEnabled(false); //disable all buttons
sqTwoBUT.setEnabled(false); //disable all buttons
sqThreeBUT.setEnabled(false); //disable all buttons
sqFourBUT.setEnabled(false); //disable all buttons
sqFiveBUT.setEnabled(false); //disable all buttons
sqSixBUT.setEnabled(false); //disable all buttons
sqSevenBUT.setEnabled(false); //disable all buttons
sqEightBUT.setEnabled(false); //disable all buttons
sqNineBUT.setEnabled(false); //disable all buttons
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~X WINS~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
//horizontal, top, x wins
if (sqOne == "X") { //checking too see if player X has won
if (sqFour == "X") {
if (sqSeven == "X") {
turnTF.setText("X wins!"); //X wins text
sqOneBUT.setEnabled(false); //disable all buttons
sqTwoBUT.setEnabled(false); //disable all buttons
sqThreeBUT.setEnabled(false); //disable all buttons
sqFourBUT.setEnabled(false); //disable all buttons
sqFiveBUT.setEnabled(false); //disable all buttons
sqSixBUT.setEnabled(false); //disable all buttons
sqSevenBUT.setEnabled(false); //disable all buttons
sqEightBUT.setEnabled(false); //disable all buttons
sqNineBUT.setEnabled(false); //disable all buttons
//vertical, left, x wins
if (sqOne == "X") { //checking too see if player X has won
if (sqTwo == "X") {
if (sqThree == "X") {
turnTF.setText("X wins!"); //X wins text
sqOneBUT.setEnabled(false); //disable all buttons
sqTwoBUT.setEnabled(false); //disable all buttons
sqThreeBUT.setEnabled(false); //disable all buttons
sqFourBUT.setEnabled(false); //disable all buttons
sqFiveBUT.setEnabled(false); //disable all buttons
sqSixBUT.setEnabled(false); //disable all buttons
sqSevenBUT.setEnabled(false); //disable all buttons
sqEightBUT.setEnabled(false); //disable all buttons
sqNineBUT.setEnabled(false); //disable all buttons
// diagonal, top left to bottom right, x wins
if (sqOne == "X") { //checking too see if player X has won
if (sqFive == "X") {
if (sqNine == "X") {
turnTF.setText("X wins!"); //X wins text
sqOneBUT.setEnabled(false); //disable all buttons
sqTwoBUT.setEnabled(false); //disable all buttons
sqThreeBUT.setEnabled(false); //disable all buttons
sqFourBUT.setEnabled(false); //disable all buttons
sqFiveBUT.setEnabled(false); //disable all buttons
sqSixBUT.setEnabled(false); //disable all buttons
sqSevenBUT.setEnabled(false); //disable all buttons
sqEightBUT.setEnabled(false); //disable all buttons
sqNineBUT.setEnabled(false); //disable all buttons
// horizontal, mid, x wins
if (sqTwo == "X") { //checking too see if player X has won
if (sqFive == "X") {
if (sqEight == "X") {
turnTF.setText("X wins!"); //X wins text
sqOneBUT.setEnabled(false); //disable all buttons
sqTwoBUT.setEnabled(false); //disable all buttons
sqThreeBUT.setEnabled(false); //disable all buttons
sqFourBUT.setEnabled(false); //disable all buttons
sqFiveBUT.setEnabled(false); //disable all buttons
sqSixBUT.setEnabled(false); //disable all buttons
sqSevenBUT.setEnabled(false); //disable all buttons
sqEightBUT.setEnabled(false); //disable all buttons
sqNineBUT.setEnabled(false); //disable all buttons
// horizontal, bottom, x wins
if (sqThree == "X") { //checking too see if player X has won
if (sqSix == "X") {
if (sqNine == "X") {
turnTF.setText("X wins!"); //X wins text
sqOneBUT.setEnabled(false); //disable all buttons
sqTwoBUT.setEnabled(false); //disable all buttons
sqThreeBUT.setEnabled(false); //disable all buttons
sqFourBUT.setEnabled(false); //disable all buttons
sqFiveBUT.setEnabled(false); //disable all buttons
sqSixBUT.setEnabled(false); //disable all buttons
sqSevenBUT.setEnabled(false); //disable all buttons
sqEightBUT.setEnabled(false); //disable all buttons
sqNineBUT.setEnabled(false); //disable all buttons
// diagonal, top right to bottom left, x wins
if (sqThree == "X") { //checking too see if player X has won
if (sqFive == "X") {
if (sqSeven == "X") {
turnTF.setText("X wins!"); //X wins text
sqOneBUT.setEnabled(false); //disable all buttons
sqTwoBUT.setEnabled(false); //disable all buttons
sqThreeBUT.setEnabled(false); //disable all buttons
sqFourBUT.setEnabled(false); //disable all buttons
sqFiveBUT.setEnabled(false); //disable all buttons
sqSixBUT.setEnabled(false); //disable all buttons
sqSevenBUT.setEnabled(false); //disable all buttons
sqEightBUT.setEnabled(false); //disable all buttons
sqNineBUT.setEnabled(false); //disable all buttons
String wins = turnTF.getText(); //Reading who won to print win winTF
if (wins.equals("X wins!")) { //if X wins
xWon++; //adding 1 to X's amount of wins
String xWonString = Integer.toString(xWon); //converting to String
xWinsTF.setText(xWonString); //displaying # of wins
newGameBUT.setEnabled(true); //enable new game button
if (wins.equals("O wins!")) { //if O wins
oWon++; //adding 1 to O's amount of wins
String oWonString = Integer.toString(oWon); //converting to String
oWinsTF.setText(oWonString); //displaying # of wins
newGameBUT.setEnabled(true); //enable new game button
if (e.getSource() == newGameBUT) {
i++; // turn switch
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private void jbInit() throws Exception {
this.getContentPane().setLayout(null);
this.getContentPane().setBackground(Color.darkGray);
sqTwoBUT.setBounds(new Rectangle(2, 116, 115, 115));
sqTwoBUT.setFont(new java.awt.Font(
"Tw Cen MT Condensed Extra Bold",
Font.BOLD, 20));
sqFourBUT.setBounds(new Rectangle(118, 1, 115, 115));
sqFourBUT.setFont(new java.awt.Font(
"Tw Cen MT Condensed Extra Bold",
Font.BOLD, 20));
sqFiveBUT.setBounds(new Rectangle(118, 116, 115, 115));
sqFiveBUT.setFont(new java.awt.Font(
"Tw Cen MT Condensed Extra Bold",
Font.BOLD, 20));
sqSixBUT.setBounds(new Rectangle(118, 232, 115, 115));
sqSixBUT.setFont(new java.awt.Font(
"Tw Cen MT Condensed Extra Bold",
Font.BOLD, 20));
sqOneBUT.setBounds(new Rectangle(2, 1, 115, 115));
sqOneBUT.setFont(new java.awt.Font(
"Tw Cen MT Condensed Extra Bold",
Font.BOLD, 20));
sqEightBUT.setBounds(new Rectangle(233, 116, 115, 115));
sqEightBUT.setFont(new java.awt.Font(
"Tw Cen MT Condensed Extra Bold",
Font.BOLD, 20));
sqNineBUT.setBounds(new Rectangle(233, 232, 115, 115));
sqNineBUT.setFont(new java.awt.Font(
"Tw Cen MT Condensed Extra Bold",
Font.BOLD, 20));
sqSevenBUT.setBounds(new Rectangle(233, 1, 115, 115));
sqSevenBUT.setFont(new java.awt.Font(
"Tw Cen MT Condensed Extra Bold",
Font.BOLD, 20));
sqOneBUT.addActionListener(this);
sqTwoBUT.addActionListener(this);
sqThreeBUT.addActionListener(this);
sqFourBUT.addActionListener(this);
sqFiveBUT.addActionListener(this);
sqSixBUT.addActionListener(this);
sqSevenBUT.addActionListener(this);
sqEightBUT.addActionListener(this);
sqNineBUT.addActionListener(this);
newGameBUT.addActionListener(this);
sqThreeBUT.setFont(new java.awt.Font(
"Tw Cen MT Condensed Extra Bold",
Font.BOLD, 20));
turnTF.setFont(new java.awt.Font(
"Tw Cen MT Condensed Extra Bold",
Font.BOLD, 20));
turnTF.setEditable(false);
turnTF.setText("X goes first");
turnTF.setHorizontalAlignment(SwingConstants.CENTER);
turnTF.setBounds(new Rectangle(2, 346, 346, 35));
oWinsTF.setFont(new java.awt.Font("Tw Cen MT Condensed Extra Bold",
Font.BOLD, 18));
oWinsTF.setEditable(false);
oWinsTF.setHorizontalAlignment(SwingConstants.CENTER);
oWinsTF.setBounds(new Rectangle(256, 419, 79, 59));
xWinsTF.setFont(new java.awt.Font("Tw Cen MT Condensed Extra Bold",
Font.BOLD, 18));
xWinsTF.setEditable(false);
xWinsTF.setHorizontalAlignment(SwingConstants.CENTER);
xWinsTF.setBounds(new Rectangle(12, 419, 79, 59));
oWinsLBL.setFont(new java.awt.Font("Tw Cen MT Condensed Extra Bold",
Font.PLAIN, 16));
oWinsLBL.setForeground(Color.white);
oWinsLBL.setHorizontalAlignment(SwingConstants.CENTER);
oWinsLBL.setText("O wins:");
oWinsLBL.setBounds(new Rectangle(256, 399, 78, 21));
xWinsLBL.setFont(new java.awt.Font("Tw Cen MT Condensed Extra Bold",
Font.PLAIN, 16));
xWinsLBL.setForeground(Color.white);
xWinsLBL.setDisplayedMnemonic('0');
xWinsLBL.setHorizontalAlignment(SwingConstants.CENTER);
xWinsLBL.setText("X wins:");
xWinsLBL.setBounds(new Rectangle(12, 393, 78, 21));
newGameBUT.setBounds(new Rectangle(101, 455, 146, 23));
newGameBUT.setFont(new java.awt.Font("Tw Cen MT Condensed Extra Bold",
Font.BOLD, 14));
newGameBUT.setText("New Game");
this.getContentPane().add(sqFourBUT);
this.getContentPane().add(sqThreeBUT);
this.getContentPane().add(sqTwoBUT);
this.getContentPane().add(sqOneBUT);
this.getContentPane().add(sqFiveBUT);
this.getContentPane().add(sqSixBUT);
this.getContentPane().add(sqNineBUT);
this.getContentPane().add(sqEightBUT);
this.getContentPane().add(sqSevenBUT);
this.getContentPane().add(turnTF);
this.getContentPane().add(xWinsLBL);
this.getContentPane().add(xWinsTF);
this.getContentPane().add(oWinsLBL);
this.getContentPane().add(oWinsTF);
this.getContentPane().add(newGameBUT);
sqThreeBUT.setBounds(new Rectangle(2, 232, 115, 115));
JButton sqTwoBUT = new JButton();
JButton sqThreeBUT = new JButton();
JButton sqFourBUT = new JButton();
JButton sqFiveBUT = new JButton();
JButton sqSixBUT = new JButton();
JButton sqOneBUT = new JButton();
JButton sqEightBUT = new JButton();
JButton sqNineBUT = new JButton();
JButton sqSevenBUT = new JButton();
JTextField turnTF = new JTextField();
JTextField oWinsTF = new JTextField();
JTextField xWinsTF = new JTextField();
JLabel oWinsLBL = new JLabel();
JLabel xWinsLBL = new JLabel();
JButton newGameBUT = new JButton();
}This code should be the poster-child for every time we tell someone that repeated code can usually be replaced with collections or method calls.
if (e.getSource() == sqOneBUT) { //disable and print X or O to button
sqOneBUT.setText(turn); //printing players symbol
sqOneBUT.setEnabled(false); //disabling button
if (e.getSource() == sqTwoBUT) { //disable and print X or O to button
sqTwoBUT.setText(turn); //printing players symbol
sqTwoBUT.setEnabled(false); //disabling button
if (e.getSource() == sqThreeBUT) { //disable and print X or O to button
sqThreeBUT.setText(turn); //printing players symbol
sqThreeBUT.setEnabled(false); //disabling button
if (e.getSource() == sqFourBUT) { //disable and print X or O to button
sqFourBUT.setText(turn); //printing players symbol
sqFourBUT.setEnabled(false); //disabling button
if (e.getSource() == sqFiveBUT) { //disable and print X or O to button
sqFiveBUT.setText(turn); //printing players symbol
sqFiveBUT.setEnabled(false); //disabling button
if (e.getSource() == sqSixBUT) { //disable and print X or O to button
sqSixBUT.setText(turn); //printing players symbol
sqSixBUT.setEnabled(false); //disabling button
if (e.getSource() == sqSevenBUT) { //disable and print X or O to button
sqSevenBUT.setText(turn); //printing players symbol
sqSevenBUT.setEnabled(false); //disabling button
if (e.getSource() == sqEightBUT) { //disable and print X or O to button
sqEightBUT.setText(turn); //printing players symbol
sqEightBUT.setEnabled(false); //disabling button
if (e.getSource() == sqNineBUT) { //disable and print X or O to button
sqNineBUT.setText(turn); //printing players symbol
sqNineBUT.setEnabled(false); //disabling button
String sqOne = sqOneBUT.getText(); // Strings to read to find winner
String sqTwo = sqTwoBUT.getText(); // Strings to read to find winner
String sqThree = sqThreeBUT.getText(); // Strings to read to find winner
String sqFour = sqFourBUT.getText(); // Strings to read to find winner
String sqFive = sqFiveBUT.getText(); // Strings to read to find winner
String sqSix = sqSixBUT.getText(); // Strings to read to find winner
String sqSeven = sqSevenBUT.getText(); // Strings to read to find winner
String sqEight = sqEightBUT.getText(); // Strings to read to find winner
String sqNine = sqNineBUT.getText(); // Strings to read to find winner -
A Tic Tac Toe board is represented as an array of 9 chars. Write a program that will allow two users to play tic tac toe. The player should ask for moves alternately from players X and O. The program is too dumb to check whether anyone has won or lost and just stops after 9 turns. The program should display the game position as follows after each move.
The output should be somewhat as follows:
Choose a spot (1 to 9) for X: 1
X || ||
|| ||
|| ||
Basically i have to do this. I was wondering if anyone could lead me in the right direction please?class TicTacToe {
// instance variables
// constructor(s)
// method(s)
public static void main(String[] args) {
new TicTacToe();
}There you go. I got you started. Now all you need to do is finish.
Maybe you are looking for
-
Can't watch videos online... Do I need some flash player?
Can't watch videos online... Do I need some flash player?
-
Help need to recover corrupted ipad backup
I need help recovering a corrupted ipad backup. I was unable to restore my ipad from the backup when upgrading to ios 4.2. Does anyone know of a program that will allow me to decrypt the data from this backup?? Any hints or help would be greatly appr
-
Dear Experts, We are in the process of installing new netweaver 2004s server with BI 7 and would in the process like to utilize the latest features of BI 7 mainly the Bex Web and enhancements in Bex web like drag & Drop, Adobe Engine etc to name a fe
-
HP LaserJet P1102W Printing has recently become faint – not in lines but general faint all over. In the past I thought I received a warning informing how many copies to go before the cartridge was empty. To date I have received no warning. The pri
-
I have my catalog on my computer which is attached to our home network. I want my husband to be able to access this catalog from his computer. I have PSE7 installed on both computers. When I try to open the catalog on his computer I can get to the fo