TicTacToe help
I am using Netbeans 4.0 to create a midlet app. The problem is that when I compile it tells me that java.text does not exist and I have a problem with Java.io. I will post code and output. PLEASE HELP!!!
CODE
package tictactoeserver;
import java.io.*;
import java.lang.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.text.*; //error
public class TTTServlet extends HttpServlet { //error
private Vector matches = new Vector();
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
int msg, iMatch, iPlayer;
String str;
// get parameters
str = request.getParameter("msg");
if (str != null)
msg = Integer.parseInt(str);
else
msg = Messages.NONE;
str = request.getParameter("mid");
if (str != null)
iMatch = Integer.parseInt(str);
else
iMatch = -1;
str = request.getParameter("pid");
if (str != null)
iPlayer = Integer.parseInt(str);
else
iPlayer = -1;
response.setContentType("text/html");
PrintWriter out = response.getWriter();//error
// output the return value from getResponse
out.print(getResponse(msg,iMatch,iPlayer));
* get the response to the message received in the request
* @param msg the message code
* @param iMatch index of the match in the matches vector
* @param iPlayer index of the player who sent the message
* @return String to send back to client
private String getResponse(int msg, int iMatch, int iPlayer) {
String res = (new Integer(Messages.ERROR)).toString();
// map to appropiate function according to the message
if (msg >= 0 && msg < 9) // play messages
res = doPlay(msg, iMatch, iPlayer);
// map service messages
switch (msg) {
case Messages.HELLO: // just logged in
res = doHello();
break;
case Messages.GOODBYE: // leaving the match
res = doGoodBye(iMatch, iPlayer);
break;
case Messages.CONTINUE: // opponent has left, but player wants to continue
res = doContinue(iMatch, iPlayer);
break;
case Messages.WIN: // the player has just won a game, update score and get first move
res = doWin(iMatch, iPlayer);
break;
case Messages.DRAW: // draw game, get first move in new match
res = doDraw(iMatch, iPlayer);
break;
case Messages.WAIT: // player is waiting for opponent, send current message
res = doWait(iMatch,iPlayer);
break;
case Messages.RESTARTSERVER: // for debugging
matches.removeAllElements();
res = "Server Restarted";
break;
return res;
* get a match where one player is waiting for the opponent
* @return a free match, or null if no free matches exist
private Match getFreeMatch() {
int i;
Match m;
// loop through matches Vector
for (i = 0; i < matches.size(); i++) {
m = (Match)matches.elementAt(i);
// check if the match is not empty (an empty match is a
// match where both of the players have left)
if (!m.getEmpty()) {
// check that the match is not full (a full match is a
// a match that already has two players)
if (!m.getFull()) {
return m;
return null;
* get an empty match (where both players have already left)
* @return an empty match, or null if there are no empty matches
private Match getEmptyMatch() {
int i;
Match m;
for (i = 0; i < matches.size(); i++) {
m = (Match)matches.elementAt(i);
if (m.getEmpty() && !m.getFull()) {
return m;
return null;
* process a new player logging in
* @return response to be sent to that player
private String doHello() {
int iMatch, iPlayer, msg;
// look for a free match
Match m = getFreeMatch();
if (m == null) { // no free matches
// look for an empty match
m = getEmptyMatch();
if (m == null) { // no empty match
// make a new match
m = new Match();
iMatch = matches.size();
matches.addElement(m);
else { // found an empty match
// get the match index
iMatch = matches.indexOf(m);
// set match as free
m.setEmpty(false);
m.setFull(false);
// first player to join the match plays X (0)
iPlayer = 0;
// msg = WAIT , need to wait for another player
msg = Messages.WAIT;
else { // found a free match, let's start the game
// second player to join the match plays O (0)
iPlayer = 1;
// get the match index
iMatch = matches.indexOf(m);
// msg = READY, ready to begin playing
msg = Messages.READY;
// set match as full (has 2 players)
m.setFull(true);
m.setMessage(msg);
return "mid=" + iMatch + "&pid=" + iPlayer + "&msg=" + m.getMessage();
* process a player logging out
* @return response to be sent to that player
private String doGoodBye(int iMatch, int iPlayer) {
Match m = (Match)matches.elementAt(iMatch);
if (m.getEmpty()) {
// second player to leave the match
m.setFull(false); // match is ready to be reused
m.setEmpty(true);
m.setMessage(Messages.GOODBYE);
return "msg=" + m.getMessage();
* process a player continuing
* just pass on the message to the next player
* @return response to be sent to that player
private String doContinue(int iMatch, int iPlayer) {
Match m = (Match)matches.elementAt(iMatch);
m.setMessage(Messages.CONTINUE);
return "msg=" + m.getMessage();
* process a player acknowlegding a win
* just pass on the message to the next player
* @return response to be sent to that player
private String doWin(int iMatch, int iPlayer) {
Match m = (Match)matches.elementAt(iMatch);
m.setMessage(Messages.WIN);
return "msg=" + m.getMessage();
* process a player acknowledging a draw
* just pass on the message to the next player
* @return response to be sent to that player
private String doDraw(int iMatch, int iPlayer) {
Match m = (Match)matches.elementAt(iMatch);
m.setMessage(Messages.DRAW);
return "msg=" + m.getMessage();
* process a regular move
* just pass on the message to the next player
* @return response to be sent to that player
private String doPlay(int msg, int iMatch, int iPlayer) {
Match m = (Match)matches.elementAt(iMatch);
if (m.getMessage() != Messages.WIN) {
m.setMessage(msg);
return "msg=" + m.getMessage();
else
return "msg=" + Messages.RESEND;
* process a WAIT message (the player is waiting for his opponent to move)
* just return the current message
* @return response to be sent to that player
private String doWait(int iMatch, int iPlayer) {
Match m = (Match)matches.elementAt(iMatch);
return "msg=" + m.getMessage();
OUTPUT
Compiling 7 source files to C:\Documents and Settings\obioku obotette\tictactoe\build\compiled
C:\Documents and Settings\obioku obotette\tictactoe\src\tictactoeserver\TTTServlet.java:8: package java.text does not exist
import java.text.*;
C:\Documents and Settings\obioku obotette\tictactoe\src\tictactoeserver\TTTServlet.java:10: cannot access java.io.Serializable
file java\io\Serializable.class not found
public class TTTServlet extends HttpServlet {
C:\Documents and Settings\obioku obotette\tictactoe\src\tictactoeserver\TTTServlet.java:38: cannot resolve symbol
symbol : class PrintWriter
location: class tictactoeserver.TTTServlet
PrintWriter out = response.getWriter();
3 errors
This is no j2me code, You should post your question in the servlet subforums....
Similar Messages
-
Help needed on a TicTacToe java program
I am very new to java and our teacher has given us a program
that i am having quite a bit of trouble with. I was wondering if anyone could help me out.
This is the program which i have bolded.
{You will write a Java class to play the TicTacToe game. This program will have at least two data members, one for the status of the board and one to keep track of whose turn it is. All data members must be private. You will create a user interface that allows client code to play the game.
The user interface must include:
� Boolean xPlay(int num) which allows x to play in the square labeled by num. This function will return true if that play caused the game to end and false otherwise.
� Boolean oPlay(int num) which allows o to play in the square labeled by num. This function will return true if that play caused the game to end and false otherwise.
� Boolean isEmpty(int num) will check to see if the square labeled by num is empty.
� Void display() which displays the current game status to the screen.
� Char whoWon() which will return X, O, or C depending on the outcome of the game.
� You must not allow the same player to play twice in a row. Should the client code attempt to, xPlay or oPlay should print an error and do nothing else.
� Also calling whoWon when the game is not over should produce an error message and return a character other than X, O, or C.
� Client code for the moment is up to you. Assume you have two human players that can enter the number of the square in which they want to play.
Verifying user input WILL be done by the client code.}Hi,
This forum is exclusively for discussions related to Sun Java Studio Creator. Please post your question at the Java Programming forum. The URL to this forum is:
http://forum.java.sun.com/forum.jspa?forumID=31
Cheers
Giri -
I wrote this code that works and does everything alright and plays the game, but i need the game to be able to check if a square is already occupied and tell the user to input again. I am not doing well there. here's what i have...
// tic tac toe game
import java.util.Scanner; // import the scanner
public class TicTacToe
{ // start of class
public static String board [][] = new String [3][3]; // create a 3x3 array called board
public static void main(String[] args) //main method
{ // start main
Scanner input = new Scanner( System.in ); // create scanner to read inputs
String name1; // player1's name
String name2; // player2's name
String current = "O";// the current mark
int choice;//the choice user inputs
int cheat; // cheatcode
int moveCount = 0; // count the number of moves made
int check = 0;
System.out.println( "Enter Player1's name: " );//prompt
name1 = input.nextLine();//read input
System.out.println( "Enter Player2's name: " );//prompt
name2 = input.nextLine();//read input
for ( int i = 0; i < 3; i++)
{ //start of loop
for ( int j = 0; j < 3; j++)
{//start of loop
board[i][j] = " "; // initializes board to empty spaces
}//end of loop
}//end of loop
System.out.println(); // the next few lines are dedicated to print a board
System.out.println ( " ************************" );
for ( int row = 0; row < 3; row++ )
{//start of loop
for ( int column = 0; column < 3; column++ )
{//start of loop
System.out.printf ( " * * * *\n" );
}//end of loop
System.out.println ( " ************************" );
}//end of loop
int winner = 0; // winner
while (winner == 0)
{//start of gignormous loop
if (current == ("O")) // switch between players
current = "X";
System.out.printf( "%s, make your move.", name1 );//prompt
choice = input.nextInt();//read input
++moveCount;
if ( moveCount == 9)
winner = 5;
if ( choice <= 0 || choice >9 )// prevent user from going crazy and input weird numbers
System.out.printf( "%s, can't do that homey.", name1 );//prompt
choice = input.nextInt();//read input
if ( choice == 333)
winner = 3;
else
xmark(choice); // mark x by passing choice to xmark
winner = CheckOneWin ( winner ); // check for win for player1...passes winner...blah blah
for ( int row1 = 0; row1 != 3; row1++ )
System.out.println ( " *************************" );
System.out.println ( " * * * *" );
for ( int column1 = 0; column1 != 3; column1++ )
System.out.printf ( "%4s%4s" , "*" , board[row1][column1] );
System.out.printf ( "%s\n%s\n" , " *" , " * * * *" );
System.out.println ( " *************************" );
else
current = "O"; // switch back to o
System.out.printf( "%s, make your move.", name2 );//prompt
choice = input.nextInt();//read input
++moveCount;
if ( moveCount == 9 )
winner = 5;
if ( choice <= 0 || choice > 9 ) // prevent user from going crazy
System.out.printf( "%s, can't do that homey.", name2 );//prompt
choice = input.nextInt();//read input
if ( choice == 333)
winner = 3;
omark(choice); // pass choice to method omark
winner = CheckTwoWin ( winner ); // check for winner by passing winner to method CheckTwoWin
for ( int row2 = 0; row2 != 3; row2++ )
System.out.println ( " *************************" );
System.out.println ( " * * * *" );
for ( int column2 = 0; column2 != 3; column2++ )
System.out.printf ( "%4s%4s" , "*" , board[row2][column2] );
System.out.printf ( "%s\n%s\n" , " *" , " * * * *" );
System.out.println ( " *************************" );
if (winner == 1) // tells that player1 has won
System.out.printf("\n%s wins, way to go homey!\n", name1);
if (winner == 3) // tells that player1 has won with cheat code
System.out.printf("\n%s wins...with a cheat...don't you have any real skills?\n", name1);
if (winner == 2) // tells that player2 has won
System.out.printf("\n%s wins, way to go homey!\n", name2);
if (winner == 4) // tells that player2 has won with cheat code
System.out.printf("\n%s wins...with a cheat...don't you have any real skills?\n", name2);
if (winner == 5) // tells that a tie occurs
System.out.printf("The game is tied, looks like %s and %s are evenly matched...\n", name1, name2);
}//end of hugmongus while loop
} // end method main
public static void xmark ( int x ) // use x to recieve choice
int thingy = x; // thingy is the private copy of x
switch ( thingy ) // switch for thingy
case 1:
if (board[0][0] == "O")
System.out.println("can't override dude...");
else
board[0][0] = "X"; // mark X on board [0][0] if case is
break;
case 2:
if (board[0][1] == "O")
System.out.println("can't override dude...");
else
board[0][1] = "X"; // mark X...board[0][1]...
break;
case 3:
if (board[0][2] == "O")
System.out.println("can't override dude...");
else
board[0][2] = "X"; // blah
break;
case 4:
if (board[1][0] == "O")
System.out.println("can't override dude...");
else
board[1][0] = "X"; //blah
break;
case 5:
if (board[1][1] == "O")
System.out.println("can't override dude...");
else
board[1][1] = "X"; // yadayadyada
break;
case 6:
if (board[1][2] == "O")
System.out.println("can't override dude...");
else
board[1][2] = "X";
break;
case 7:
if (board[2][0] == "O")
System.out.println("can't override dude...");
else
board[2][0] = "X";
break;
case 8:
if (board[2][1] == "O")
System.out.println("can't override dude...");
else
board[2][1] = "X";
break;
case 9:
if (board[2][2] == "O")
System.out.println("can't override dude...");
else
board[2][2] = "X";
break;
public static void omark ( int o ) // o recieves choice
int thingy = o; // same thing as last method
switch ( thingy ) // switch for thingy
case 1:
if (board[0][0] == "X")
System.out.println("can't override dude...");
else
board[0][0] = "O"; // mark X on board [0][0] if case is
break;
case 2:
if (board[0][1] == "X")
System.out.println("can't override dude...");
else
board[0][1] = "O"; // mark X...board[0][1]...
break;
case 3:
if (board[0][2] == "X")
System.out.println("can't override dude...");
else
board[0][2] = "O"; // blah
break;
case 4:
if (board[1][0] == "X")
System.out.println("can't override dude...");
else
board[1][0] = "O"; //blah
break;
case 5:
if (board[1][1] == "X")
System.out.println("can't override dude...");
else
board[1][1] = "O"; // yadayadyada
break;
case 6:
if (board[1][2] == "X")
System.out.println("can't override dude...");
else
board[1][2] = "O";
break;
case 7:
if (board[2][0] == "X")
System.out.println("can't override dude...");
else
board[2][0] = "O";
break;
case 8:
if (board[2][1] == "X")
System.out.println("can't override dude...");
else
board[2][1] = "O";
break;
case 9:
if (board[2][2] == "X")
System.out.println("can't override dude...");
else
board[2][2] = "O";
break;
public static int CheckOneWin( int win1 ) // recieves winner with win1
int win2 = win1; // win2 = new copy of win1
if ( ( board[0][0] == "X" ) && ( board [0][1] == "X" ) && ( board [0][2] == "X" ) ) // if these 3 spaces are all X
win2 = 1; // player1 wins and win2 is set to 1
if ( ( board[1][0] == "X" ) && ( board [1][1] == "X" ) && ( board [1][2] == "X" ) ) // same thing again
win2 = 1;
if ( ( board[2][0] == "X" ) && ( board [2][1] == "X" ) && ( board [2][2] == "X" ) )
win2 = 1;
if ( ( board[0][0] == "X" ) && ( board [1][0] == "X" ) && ( board [2][0] == "X") )
win2 = 1;
if ( ( board[0][1] == "X" ) && ( board [1][1] == "X" ) && ( board [2][1] == "X" ) )
win2 = 1;
if ( ( board[0][2] == "X" ) && ( board [1][2] == "X" ) && ( board [2][2] == "X" ) )
win2 = 1;
if ( ( board[0][0] == "X" ) && ( board [1][1] == "X" ) && ( board [2][2] == "X" ) )
win2 = 1;
if ( ( board[0][2] == "X" ) && ( board [1][1] == "X" ) && ( board [2][0] == "X" ) )
win2 = 1;
return win2; // returns win2
public static int CheckTwoWin( int win3 )// recieve winner with win3
int win4 = win3;//blah
if ( ( board[0][0] == "O" ) && ( board [0][1] == "O" ) && ( board [0][2] == "O" ) )//all that good stuff
win4 = 1;
if ( ( board[1][0] == "O" ) && ( board [1][1] == "O" ) && ( board [1][2] == "O" ) )
win4 = 1;
if ( ( board[2][0] == "O" ) && ( board [2][1] == "O" ) && ( board [2][2] == "O" ) )
win4 = 1;
if ( ( board[0][0] == "O" ) && ( board [1][0] == "O" ) && ( board [2][0] == "O" ) )
win4 = 1;
if ( ( board[0][1] == "O" ) && ( board [1][1] == "O" ) && ( board [2][1] == "O" ) )
win4 = 1;
if ( ( board[0][2] == "O" ) && ( board [1][2] == "O" ) && ( board [2][2] == "O" ) )
win4 = 1;
if ( ( board[0][0] == "O" ) && ( board [1][1] == "O" ) && ( board [2][2] == "O" ) )
win4 = 1;
if ( ( board[0][2] == "O" ) && ( board [1][1] == "O" ) && ( board [2][0] == "O" ) )
win4 = 1;
return win4; //returns win4
}//end of this huge and hard classNow if a user tries to override a already occupied square, it will say "dude, can't override..." and automically hand the move to next player without letting the user move again...someopne please help me...Boolean is a primitive that can have two values - true or false. Run this and see if you understand:
class OddsEvens {
int[] numbers = {1,2,4,5,7,8};
public void checkNumbers() {
for(int index = 0; index < numbers.length; index++) {
System.out.print(numbers[index] + " is ");
if(isEven(numbers[index])) {
System.out.println("even");
} else {
System.out.println("odd");
private boolean isEven(int value) {
if(value %2 == 0) {
return true;
} else {
return false;
public static void main(String[] args) {
OddsEvens oe = new OddsEvens();
oe.checkNumbers();
} -
Help with structure of TICTacToe grid
hi, I'm trying to get the tictactoe grid to print out...
123
456
789
but it keeps missing '1' in the grid output i.e.....
23
456
789
Please can anyone point out where I've gone wrong.
here is my code for the grid.....
String s = "0123456789";
public void printBoard(String s)
int i = 1;
while(i < s.length())
i++;
int pos = i%3;
if( pos !=0)
myPrint(Character.toString((s.charAt(i))));
else
myPrintln(Character.toString((s.charAt(i))));
myPrintln("");
Many thanks
DaveSorry, you had multiple errors. Try this (where I used System.out to print the data):
public static void printBoard(String s) {
int i = 0;
while (i < s.length()-1) {
i++;
int pos = i % 3;
if (pos != 0) {
System.out.print(Character.toString( (s.charAt(i))));
else {
System.out.println(Character.toString( (s.charAt(i))));
System.out.println("");
}/Kaj -
I need help with my Tictactoe. can't switch between players Please Please
You will be building a Tic Tac Toe program, I have provided a program shell that has four functions:
printBoard- Prints the board as shows in the comments at the top of the file.
hasWon - Takes in a player's marker and tells us if that player has won
markTheBoard - marks the given location with the player's marker
isTie - Tells if there are no more spots and no winner
The play starts with X, the variable turn will keep track of who's turn it is.
At the beginning you will display the board with position numbers so the player knows how to place his/her marker.
The code will ask each player where they would like to place their marker until either
there are no more spots to play or one of the players wins.
The shell program is here
import java.util.Scanner;
* Represents a tic tac toe board on the console, positions are shown below:
* | 1 | 2 | 3 |
* | 4 | 5 | 6 |
* | 7 | 8 | 9 |
* An example board in mid play looks like this:
* | X | | |
* | | O | |
* | O | | X |
public class TicTacToe {
public enum Marker
EMPTY,
X,
O
private static Marker position1 = Marker.EMPTY;
private static Marker position2 = Marker.EMPTY;
private static Marker position3 = Marker.EMPTY;
private static Marker position4 = Marker.EMPTY;
private static Marker position5 = Marker.EMPTY;
private static Marker position6 = Marker.EMPTY;
private static Marker position7 = Marker.EMPTY;
private static Marker position8 = Marker.EMPTY;
private static Marker position9 = Marker.EMPTY;
private static Marker turn = Marker.X;
public static void main(String[] args)
printBoard();
Scanner scan = new Scanner(System.in);
for (int j = 1; j < 9; j++) {
boolean validInput = false; // for input validation
while(!validInput) {
if (turn == Marker.X) {
System.out.print("Player 'X', enter your move: ");
} else {
System.out.print("Player 'O', enter your move: ");
int player = scan.nextInt();
if (j == 1 || j == 3 || j == 5 || j == 7 || j == 9) {
turn = Marker.X;
markTheBoard(turn, player);
} else if (j == 2 || j == 4 || j == 6 || j == 8) {
turn = Marker.O;
markTheBoard(turn, player);
}else {
System.out.println("This move at (" + j + ") is not valid. Try again...");
* This method will print the board as shown in the above example.
public static void printBoard()
System.out.println("Welcome! Tic Tac Toe is a two player game.");
System.out.println("Please Refer to the board below when asked to enter your values.");
System.out.println();
for (int x = 0; x < 1; x++) {
for (int i = 0; i < 9; i += 3) {
System.out.println(" -------------");
System.out.println(" | " + (i + 1) + " | " + (i + 2) + " | "
+ (i + 3) + " | ");
System.out.println(" -------------");
System.out.println();
* Checks if a particular player has won.
* @param m The player to check
* @return true if the player won, false if not
public static boolean hasWon(Marker m)
boolean hasWon = true;
System.out.println("Player " + m + " has won this game");
return hasWon;
* Checks if the board is full with no winner
* @return true if the board is full with no winner, false otherwise
public static boolean isTie()
boolean isTie = true;
System.out.println("This game is a tie!");
return isTie;
* Mark the given position with the given marker
* @param m The marker of the player given
* @param pos The position that we are marking
public static void markTheBoard(Marker m, int pos){
switch (pos) {
case 1:
position1 = m;
break;
case 2:
position2 = m;
break;
case 3:
position3 = m;
break;
case 4:
position4 = m;
break;
case 5:
position5 = m;
break;
case 6:
position6 = m;
break;
case 7:
position7 = m;
break;
case 8:
position8 = m;
break;
case 9:
position9 = m;
break;
default:
break;
System.out.println(" -------------");
System.out.println(" | " + position1 + " | " + position2 + " | "
+ position3 + " | ");
System.out.println(" -------------");
System.out.println(" | " + position4 + " | " + position5 + " | "
+ position6 + " | ");
System.out.println(" -------------");
System.out.println(" | " + position7 + " | " + position8 + " | "
+ position9 + " | ");
System.out.println(" -------------");
if (position1 == Marker.X && position2 == Marker.X
&& position3 == Marker.X || position4 == Marker.X
&& position5 == Marker.X && position6 == Marker.X
|| position7 == Marker.X && position8 == Marker.X
&& position9 == Marker.X) {
hasWon(Marker.X);
} else if (position1 == Marker.O && position2 == Marker.O
&& position3 == Marker.O || position4 == Marker.O
&& position5 == Marker.O && position6 == Marker.O
|| position7 == Marker.O && position8 == Marker.O
&& position9 == Marker.O) {
hasWon(Marker.O);
} else if (position1 == Marker.O && position2 == Marker.O
&& position3 == Marker.X || position4 == Marker.O
&& position5 == Marker.O && position6 == Marker.X
|| position7 == Marker.O && position8 == Marker.O
&& position9 == Marker.X) {
isTie();
if (position1 == Marker.X && position4 == Marker.X
&& position7 == Marker.X || position2 == Marker.X
&& position5 == Marker.X && position8 == Marker.X
|| position3 == Marker.X && position6 == Marker.X
&& position9 == Marker.X) {
hasWon(Marker.X);
} else if (position1 == Marker.O && position4 == Marker.O
&& position7 == Marker.O || position2 == Marker.O
&& position5 == Marker.O && position8 == Marker.O
|| position3 == Marker.O && position6 == Marker.O
&& position9 == Marker.O) {
hasWon(Marker.O);
if (position1 == Marker.X && position5 == Marker.X
&& position9 == Marker.X || position3 == Marker.X
&& position5 == Marker.X && position7 == Marker.X) {
hasWon(Marker.X);
} else if (position1 == Marker.O && position5 == Marker.O
&& position9 == Marker.O || position3 == Marker.O
&& position5 == Marker.O && position7 == Marker.O) {
hasWon(Marker.O);
}1006734 wrote:
You will be building a Tic Tac Toe program, I have provided a program shell that has four functions:No.
YOU+ will be doing that.
This is not a schoolwork cheat site.
You need to do your own work.
Post locked. -
Can you help me with mouse pressed method please?
hi
can you help me with my problem please, player label doesn't show up in the applet and the draw string method it doesn't draw any strings like X or O for the game I don't know what is the problem maybe it is with MousePressed method which is in Board class. I tried to write the code of the location many times I'm not sure if the problem comes from there.
there is no error in my code, but it doesn't work.
this is class Board which has the mouseListener
class Board extends JPanel implements MouseListener, MouseMotionListener
private JLabel playerlabel;
private boolean play;
private boolean start;
private int turn;
private Square squares[][];
private Player myplayer[][];
public Board()
setBackground( Color.WHITE );
playerlabel = new JLabel( "X player first" );
//playerlabel.setLayout(null);
// playerlabel.setLocation(500,500);
add( playerlabel );
play = true;
turn = 1;
squares = new Square[3][3];
myplayer = new Player[3][3];
int x = 40;
int y = 40;
for (int i=0; i<3; i++){
x = 40;
for (int j=0; j<3; j++){
Square s = new Square( x,y );
squares[i][j] = s;
x +=50;
y +=50;
this.addMouseListener(this);
this.addMouseMotionListener(this);
public void mouseClicked( MouseEvent event ){}
public void mouseMoved( MouseEvent event ){}
public void mouseEntered( MouseEvent event ){}
public void mouseExited( MouseEvent event ){}
public void mousePressed( MouseEvent event )
{int xPos = event.getX();
int yPos = event.getY();
if(play && turn ==1){
for (int i=0; i<3; i++){
for (int j=0; j<3; j++){
int x = squares[i][j].getX();
int y = squares[i][j].getY();
if(xPos> x && xPos<x+40&& yPos> y && yPos<y+40){
if( squares[i][j].getOccupied() ==0 ){
String ptext;
ptext = "X";
Player p = new Player(x, y,ptext);
myplayer[i][j] = p;
squares[i][j].setOccupied(1);
playerlabel.setText( "O Player Turn" );
turn = 2;
repaint();
Win();
else{
turn = 2;
playerlabel.setText( "O Player Turn" );
repaint();
if ( play && turn ==2 )
for (int i=0; i<3; i++){
for (int j=0; j<3; j++){
int x = squares[i][j].getX();
int y = squares[i][j].getY();
if(xPos> x && xPos<x+40&& yPos> y && yPos<y+40){
if( squares[i][j].getOccupied() ==0 ){
String ptext;
ptext = "O";
Player p = new Player(x, y,ptext);
myplayer[i][j] = p;
squares[i][j].setOccupied(2);
playerlabel.setText( "X Player Turn" );
turn = 1;
repaint();
Win();
else{
turn = 1;
playerlabel.setText( "X Player Turn" );
repaint();
public void mouseReleased( MouseEvent event )
public void mouseDragged( MouseEvent event )
public void Win(){
if(squares[0][0].getOccupied() == squares[0][1].getOccupied() &&squares[0][1].getOccupied()==squares[0][2].getOccupied() &&squares[0][2].getOccupied() == 1)
{playerlabel.setText("Player 1 X WON THE GAME!");
play =false; }
else if (squares[1][0].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[1][2].getOccupied() &&squares[1][2].getOccupied() == 1)
{playerlabel.setText("Player 1 X WON THE GAME!");
play =false; }
else if(squares[2][0].getOccupied() == squares[2][1].getOccupied() &&squares[2][1].getOccupied()==squares[2][2].getOccupied() &&squares[2][2].getOccupied() == 1)
{playerlabel.setText("Player 1 X WON THE GAME!");
play =false; }
if(squares[0][0].getOccupied() == squares[0][1].getOccupied() &&squares[0][1].getOccupied()==squares[0][2].getOccupied() &&squares[0][2].getOccupied() == 2)
{playerlabel.setText("Player 2 O WON THE GAME!");
play =false; }
else if (squares[1][0].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[1][2].getOccupied() &&squares[1][2].getOccupied() == 2)
{playerlabel.setText("Player 2 O WON THE GAME!");
play =false; }
else if(squares[2][0].getOccupied() == squares[2][1].getOccupied() &&squares[2][1].getOccupied()==squares[2][2].getOccupied() &&squares[2][2].getOccupied() == 2)
{playerlabel.setText("Player 2 O WON THE GAME!");
play =false; }
//Vertically win
if (squares[0][0].getOccupied() == squares[1][0].getOccupied() &&squares[1][0].getOccupied()==squares[2][0].getOccupied() &&squares[2][0].getOccupied() == 1)
{playerlabel.setText("Player 1 X WON THE GAME!");
play =false; }
else if (squares[0][1].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[2][1].getOccupied() &&squares[2][1].getOccupied() == 1)
{playerlabel.setText("Player 1 X WON THE GAME!");
play =false; }
else if(squares[0][2].getOccupied() == squares[1][2].getOccupied() &&squares[1][2].getOccupied()==squares[2][2].getOccupied() &&squares[2][2].getOccupied() == 1)
{playerlabel.setText("Player 1 X WON THE GAME!");
play =false; }
if (squares[0][0].getOccupied() == squares[1][0].getOccupied() &&squares[1][0].getOccupied()==squares[2][0].getOccupied() &&squares[2][0].getOccupied() == 2)
{playerlabel.setText("Player 2 O WON THE GAME!");
play =false; }
else if (squares[0][1].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[2][1].getOccupied() &&squares[2][1].getOccupied() == 2)
{playerlabel.setText("Player 2 O WON THE GAME!");
play =false; }
else if(squares[0][2].getOccupied() == squares[1][2].getOccupied() &&squares[1][2].getOccupied()==squares[2][2].getOccupied() &&squares[2][2].getOccupied() == 2)
{playerlabel.setText("Player 2 O WON THE GAME!");
play =false; }
//Diagonal win
if (squares[0][0].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[2][2].getOccupied() &&squares[2][2].getOccupied() == 1)
{playerlabel.setText("Player 1 X WON THE GAME!");
play =false; }
else if (squares[0][2].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[2][0].getOccupied() &&squares[2][0].getOccupied() == 1)
{playerlabel.setText("Player 1 X WON THE GAME!");
play =false; }
if (squares[0][0].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[2][2].getOccupied() &&squares[2][2].getOccupied() == 2)
{playerlabel.setText("Player 2 O WON THE GAME!");
play =false; }
else if (squares[0][2].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[2][0].getOccupied() &&squares[2][0].getOccupied() == 2)
{playerlabel.setText("Player 2 O WON THE GAME!");
play =false; }
}//end win
public void setTurn(int t)
turn = t;
playerlabel.setText( "X Player Plays First" );
public void paintComponent( Graphics g )
super.paintComponent( g );
this.setBackground( Color.WHITE );
for (int i=0; i<3; i++){
for (int j=0; j<3; j++){
g.setColor( Color.BLACK );
g.drawRect( squares[i][j].getX(), squares[i][j].getY(), 50, 50 );
for (int i=0; i<3; i++){
for (int j=0; j<3; j++){
myplayer[i][j].draw(g);
//End of paintComponent
}and this is the whole code of my program.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
class Player{
private int xCoordinate;
private int yCoordinate;
private String playerText;
public Player(int x, int y, String t)
playerText = t;
xCoordinate = x;
yCoordinate = y;
public void draw(Graphics g)
g.drawString(playerText, xCoordinate, yCoordinate);
public void SetText(String t)
{ playerText = t;
}//end player
class Square
private int x;
private int y;
private int occupied;
public Square(int x1, int y1)
x = x1;
y= y1;
occupied = 0;
public void setX(int x1)
x = x1;
public int getX()
return x;
public void setY(int y1)
y = y1;
public int getY()
return y;
public void setOccupied(int o)
occupied = o;
public int getOccupied()
return occupied;
public class TicTac extends JApplet implements ActionListener
{ private JPanel panel;
private JButton newgame;
private Board B;
public void init()
B = new Board();
add( B, BorderLayout.CENTER );
panel = new JPanel();
newgame = new JButton( "New Game" );
panel.add( newgame);
add( panel, BorderLayout.SOUTH );
newgame.addActionListener(this);
public void actionPerformed( ActionEvent ev)
{ Object source = ev.getSource();
if (source == newgame)
{remove(B);
repaint();
B = new Board();
add( B, BorderLayout.CENTER );
B.setTurn(1);
repaint();
validate();
}//end class TicTac
class Board extends JPanel implements MouseListener, MouseMotionListener
private JLabel playerlabel;
private boolean play;
private boolean start;
private int turn;
private Square squares[][];
private Player myplayer[][];
public Board()
setBackground( Color.WHITE );
playerlabel = new JLabel( "X player first" );
//playerlabel.setLayout(null);
// playerlabel.setLocation(500,500);
add( playerlabel );
play = true;
turn = 1;
squares = new Square[3][3];
myplayer = new Player[3][3];
int x = 40;
int y = 40;
for (int i=0; i<3; i++){
x = 40;
for (int j=0; j<3; j++){
Square s = new Square( x,y );
squares[i][j] = s;
x +=50;
y +=50;
this.addMouseListener(this);
this.addMouseMotionListener(this);
public void mouseClicked( MouseEvent event ){}
public void mouseMoved( MouseEvent event ){}
public void mouseEntered( MouseEvent event ){}
public void mouseExited( MouseEvent event ){}
public void mousePressed( MouseEvent event )
{int xPos = event.getX();
int yPos = event.getY();
if(play && turn ==1){
for (int i=0; i<3; i++){
for (int j=0; j<3; j++){
int x = squares[i][j].getX();
int y = squares[i][j].getY();
if(xPos> x && xPos<x+40&& yPos> y && yPos<y+40){
if( squares[i][j].getOccupied() ==0 ){
String ptext;
ptext = "X";
Player p = new Player(x, y,ptext);
myplayer[i][j] = p;
squares[i][j].setOccupied(1);
playerlabel.setText( "O Player Turn" );
turn = 2;
repaint();
Win();
else{
turn = 2;
playerlabel.setText( "O Player Turn" );
repaint();
if ( play && turn ==2 )
for (int i=0; i<3; i++){
for (int j=0; j<3; j++){
int x = squares[i][j].getX();
int y = squares[i][j].getY();
if(xPos> x && xPos<x+40&& yPos> y && yPos<y+40){
if( squares[i][j].getOccupied() ==0 ){
String ptext;
ptext = "O";
Player p = new Player(x, y,ptext);
myplayer[i][j] = p;
squares[i][j].setOccupied(2);
playerlabel.setText( "X Player Turn" );
turn = 1;
repaint();
Win();
else{
turn = 1;
playerlabel.setText( "X Player Turn" );
repaint();
public void mouseReleased( MouseEvent event )
public void mouseDragged( MouseEvent event )
public void Win(){
if(squares[0][0].getOccupied() == squares[0][1].getOccupied() &&squares[0][1].getOccupied()==squares[0][2].getOccupied() &&squares[0][2].getOccupied() == 1)
{playerlabel.setText("Player 1 X WON THE GAME!");
play =false; }
else if (squares[1][0].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[1][2].getOccupied() &&squares[1][2].getOccupied() == 1)
{playerlabel.setText("Player 1 X WON THE GAME!");
play =false; }
else if(squares[2][0].getOccupied() == squares[2][1].getOccupied() &&squares[2][1].getOccupied()==squares[2][2].getOccupied() &&squares[2][2].getOccupied() == 1)
{playerlabel.setText("Player 1 X WON THE GAME!");
play =false; }
if(squares[0][0].getOccupied() == squares[0][1].getOccupied() &&squares[0][1].getOccupied()==squares[0][2].getOccupied() &&squares[0][2].getOccupied() == 2)
{playerlabel.setText("Player 2 O WON THE GAME!");
play =false; }
else if (squares[1][0].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[1][2].getOccupied() &&squares[1][2].getOccupied() == 2)
{playerlabel.setText("Player 2 O WON THE GAME!");
play =false; }
else if(squares[2][0].getOccupied() == squares[2][1].getOccupied() &&squares[2][1].getOccupied()==squares[2][2].getOccupied() &&squares[2][2].getOccupied() == 2)
{playerlabel.setText("Player 2 O WON THE GAME!");
play =false; }
//Vertically win
if (squares[0][0].getOccupied() == squares[1][0].getOccupied() &&squares[1][0].getOccupied()==squares[2][0].getOccupied() &&squares[2][0].getOccupied() == 1)
{playerlabel.setText("Player 1 X WON THE GAME!");
play =false; }
else if (squares[0][1].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[2][1].getOccupied() &&squares[2][1].getOccupied() == 1)
{playerlabel.setText("Player 1 X WON THE GAME!");
play =false; }
else if(squares[0][2].getOccupied() == squares[1][2].getOccupied() &&squares[1][2].getOccupied()==squares[2][2].getOccupied() &&squares[2][2].getOccupied() == 1)
{playerlabel.setText("Player 1 X WON THE GAME!");
play =false; }
if (squares[0][0].getOccupied() == squares[1][0].getOccupied() &&squares[1][0].getOccupied()==squares[2][0].getOccupied() &&squares[2][0].getOccupied() == 2)
{playerlabel.setText("Player 2 O WON THE GAME!");
play =false; }
else if (squares[0][1].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[2][1].getOccupied() &&squares[2][1].getOccupied() == 2)
{playerlabel.setText("Player 2 O WON THE GAME!");
play =false; }
else if(squares[0][2].getOccupied() == squares[1][2].getOccupied() &&squares[1][2].getOccupied()==squares[2][2].getOccupied() &&squares[2][2].getOccupied() == 2)
{playerlabel.setText("Player 2 O WON THE GAME!");
play =false; }
//Diagonal win
if (squares[0][0].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[2][2].getOccupied() &&squares[2][2].getOccupied() == 1)
{playerlabel.setText("Player 1 X WON THE GAME!");
play =false; }
else if (squares[0][2].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[2][0].getOccupied() &&squares[2][0].getOccupied() == 1)
{playerlabel.setText("Player 1 X WON THE GAME!");
play =false; }
if (squares[0][0].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[2][2].getOccupied() &&squares[2][2].getOccupied() == 2)
{playerlabel.setText("Player 2 O WON THE GAME!");
play =false; }
else if (squares[0][2].getOccupied() == squares[1][1].getOccupied() &&squares[1][1].getOccupied()==squares[2][0].getOccupied() &&squares[2][0].getOccupied() == 2)
{playerlabel.setText("Player 2 O WON THE GAME!");
play =false; }
}//end win
public void setTurn(int t)
turn = t;
playerlabel.setText( "X Player Plays First" );
public void paintComponent( Graphics g )
super.paintComponent( g );
this.setBackground( Color.WHITE );
for (int i=0; i<3; i++){
for (int j=0; j<3; j++){
g.setColor( Color.BLACK );
g.drawRect( squares[i][j].getX(), squares[i][j].getY(), 50, 50 );
for (int i=0; i<3; i++){
for (int j=0; j<3; j++){
myplayer[i][j].draw(g);
//End of paintComponent
Edited by: mshadows on May 18, 2008 7:53 AMI was playing with this a little bit and came up with this game model, something that I'm sure can be improved upon greatly:
TttXO.java
an enum to encapsulate X vs O. I could use a boolean here since it has 2 states, but this seems more intuitive to me
package dy08.m05.ttt;
* tic tac toe encapsulation of X vs O
* @author Pete
public enum TttXO
X, O
}TttCell.java
encapsulates an individual cell in the tictactoe grid.
package dy08.m05.ttt;
* Tic Tac Toe Game cell
* can be occupied or not
* can hold TttXO X or O or null
* @author Pete
public class TttCell
private boolean occupied = false;
private TttXO xo = null;
public TttCell()
* sets a Square for either x or o
* @param TttXO
* @return true if successful, false if already occupied
public boolean setXO(TttXO xo)
if (occupied)
return false;
else
occupied = true;
this.xo = xo;
return true;
public void reset()
occupied = false;
xo = null;
public boolean isOccupied()
return occupied;
public TttXO getXO()
return xo;
// used to test and debug the class
public String toString()
if (occupied)
return xo.toString();
else
return "-";
package dy08.m05.ttt;
* Tic Tac Toe game model
* @author Pete
public class TttGameModel
private TttCell[][] cellGrid = new TttCell[3][3];
private boolean xTurn = true;
private boolean win = false;
public TttGameModel()
for (int i = 0; i < cellGrid.length; i++)
for (int j = 0; j < cellGrid.length; j++)
cellGrid[i][j] = new TttCell();
public void reset()
xTurn = true;
win = false;
for (int i = 0; i < cellGrid.length; i++)
for (int j = 0; j < cellGrid[i].length; j++)
cellGrid[i][j].reset();
public boolean isXTurn()
return xTurn;
public boolean isWin()
return win;
* @param row
* @param col
* @return true if valid move, false if game already over or cell occupied
public boolean takeTurn(int col, int row)
TttXO currentXO = TttXO.O;
TttCell cell = cellGrid[row][col];
if (win)
return false;
if (cell.isOccupied())
return false;
if (xTurn)
currentXO = TttXO.X;
cell.setXO(currentXO);
win = checkWin(col, row, currentXO);
xTurn = !xTurn; // toggle xturn
return true;
public boolean checkWin(int col, int row, TttXO xo)
boolean win = false;
// first rows and columns
boolean temp = true;
for (int i = 0; i < 3; i++)
temp &= cellGrid[row][i].getXO() == xo;
win |= temp;
temp = true;
for (int i = 0; i < 3; i++)
temp &= cellGrid[i][col].getXO() == xo;
win |= temp;
if (row == col) // if slash diagonal
temp = true;
for (int i = 0; i < 3; i++)
temp &= cellGrid[i][i].getXO() == xo;
win |= temp;
if (row + col == 2) // if backslash diagonal
temp = true;
for (int i = 0; i < 3; i++)
temp &= cellGrid[i][2 - i].getXO() == xo;
win |= temp;
return win;
// used to test and debug the class
public String toString()
StringBuilder sb = new StringBuilder();
for (int i = 0; i < cellGrid.length; i++)
for (int j = 0; j < cellGrid[i].length; j++)
sb.append(cellGrid[i][j] + " ");
sb.append("\n");
if (win)
sb.append("win! Game over");
else
sb.append("No winner yet");
return sb.toString();
// test the class
public static void main(String[] args)
TttGameModel model = new TttGameModel();
checkMove(model, 0, 0);
checkMove(model, 1, 0);
checkMove(model, 1, 1);
checkMove(model, 2, 0);
checkMove(model, 1, 0); // bad move
checkMove(model, 2, 2);
// to test the class
private static void checkMove(TttGameModel model, int i, int j)
System.out.println("OK move: " + model.takeTurn(i, j));
System.out.println(model + "\n"); -
Can someone help me figure out this problem in my program?
i cant get it to determine a winner, can someone help me? heres the program
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TicTacToe implements ActionListener {
private JFrame window = new JFrame("Tic-Tac-Toe");
private JPanel inputPanel = new JPanel();
private JPanel boardPanel = new JPanel();
private JButton button3 = new JButton("3 by 3");
private JButton button4 = new JButton("4 by 4");
private JButton button5 = new JButton("5 by 5");
private JLabel label = new JLabel ("Click a button to choose game board size:");
private JButton buttons[][];
private int boardSize=0;
private int count = -1;
private String letter = "";
private boolean win = false;
public TicTacToe(){
window.setSize(500,500);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
inputPanel.add(label);
inputPanel.add(button3);
inputPanel.add(button4);
inputPanel.add(button5);
button3.addActionListener(this);
button4.addActionListener(this);
button5.addActionListener(this);
inputPanel.setSize(500,200);
window.add(inputPanel,"North");
//Make The Window Visible
window.setVisible(true);
public void actionPerformed(ActionEvent a) {
if(count==-1){
letter="-";
count=0;
else{
count++;
if(count % 2 == 0){
letter = "O";
} else {
letter = "X";
if (a.getSource() == button3) {
boardSize=3;
else if (a.getSource()== button4){
boardSize=4;
else if (a.getSource() == button5){
boardSize=5;
if ((a.getSource() == button3)||(a.getSource()==button4)||(a.getSource()==button5)){
button3.setEnabled(false);
button4.setEnabled(false);
button5.setEnabled(false);
buttons = new JButton[boardSize][boardSize];
for(int i=0; i<boardSize; i++)
for (int j=0; j<boardSize; j++){
buttons[i][j] = new JButton();
boardPanel.add(buttons[i][j]);
buttons[i][j].addActionListener(this);
boardPanel.setSize(300,300);
boardPanel.setLayout(new GridLayout(boardSize,boardSize));
window.add(boardPanel,"Center");
JButton pressedButton = (JButton)a.getSource();
pressedButton.setText(letter);
pressedButton.setEnabled(false);
if(win == true){
JOptionPane.showMessageDialog(null, letter + " wins the game!");
System.exit(0);
} else if(count == (boardSize*boardSize) && win == false){
JOptionPane.showMessageDialog(null, "The game was tie!");
System.exit(0);
}You never even do anything that tries to set "win" to true. So you haven't even tried determining a winner. We aren't here to do your work for you.
-
Hi
I used Deitel's code of TicTacToe program that creats a server and have 2 clients playing TicTacToe. When the game is over one of the client has to click on new game and a new game will begin. I don't know how to do this.
Please Help.
Here's the code for the server
import java.awt.BorderLayout;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
import java.util.Formatter;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.Condition;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class TicTacToeServer extends JFrame
private String[] board = new String[ 9 ]; // tic-tac-toe board
private JTextArea outputArea; // for outputting moves
private Player[] players; // array of Players
private ServerSocket server; // server socket to connect with clients
private int currentPlayer; // keeps track of player with current move
private final static int PLAYER_X = 0; // constant for first player
private final static int PLAYER_O = 1; // constant for second player
private final static String[] MARKS = { "X", "O" }; // array of marks
private ExecutorService runGame; // will run players
private Lock gameLock; // to lock game for synchronization
private Condition otherPlayerConnected; // to wait for other player
private Condition otherPlayerTurn; // to wait for other player's turn
// set up tic-tac-toe server and GUI that displays messages
public TicTacToeServer()
super( "Tic-Tac-Toe Server" ); // set title of window
// create ExecutorService with a thread for each player
runGame = Executors.newFixedThreadPool( 2 );
gameLock = new ReentrantLock(); // create lock for game
// condition variable for both players being connected
otherPlayerConnected = gameLock.newCondition();
// condition variable for the other player's turn
otherPlayerTurn = gameLock.newCondition();
for ( int i = 0; i < 9; i++ )
board[ i ] = new String( "" ); // create tic-tac-toe board
players = new Player[ 2 ]; // create array of players
currentPlayer = PLAYER_X; // set current player to first player
try
server = new ServerSocket( 12345, 2 ); // set up ServerSocket
} // end try
catch ( IOException ioException )
ioException.printStackTrace();
System.exit( 1 );
} // end catch
outputArea = new JTextArea(); // create JTextArea for output
add( outputArea, BorderLayout.CENTER );
outputArea.setText( "Server awaiting connections\n" );
setSize( 300, 300 ); // set size of window
setVisible( true ); // show window
} // end TicTacToeServer constructor
// wait for two connections so game can be played
public void execute()
// wait for each client to connect
for ( int i = 0; i < players.length; i++ )
try // wait for connection, create Player, start runnable
players[ i ] = new Player( server.accept(), i );
runGame.execute( players[ i ] ); // execute player runnable
} // end try
catch ( IOException ioException )
ioException.printStackTrace();
System.exit( 1 );
} // end catch
} // end for
gameLock.lock(); // lock game to signal player X's thread
try
players[ PLAYER_X ].setSuspended( false ); // resume player X
otherPlayerConnected.signal(); // wake up player X's thread
} // end try
finally
gameLock.unlock(); // unlock game after signalling player X
} // end finally
} // end method execute
// display message in outputArea
private void displayMessage( final String messageToDisplay )
// display message from event-dispatch thread of execution
SwingUtilities.invokeLater(
new Runnable()
public void run() // updates outputArea
outputArea.append( messageToDisplay ); // add message
} // end method run
} // end inner class
); // end call to SwingUtilities.invokeLater
} // end method displayMessage
// determine if move is valid
public boolean validateAndMove( int location, int player )
// while not current player, must wait for turn
while ( player != currentPlayer )
gameLock.lock(); // lock game to wait for other player to go
try
otherPlayerTurn.await(); // wait for player's turn
} // end try
catch ( InterruptedException exception )
exception.printStackTrace();
} // end catch
finally
gameLock.unlock(); // unlock game after waiting
} // end finally
} // end while
// if location not occupied, make move
if ( !isOccupied( location ) )
board[ location ] = MARKS[ currentPlayer ]; // set move on board
currentPlayer = ( currentPlayer + 1 ) % 2; // change player
// let new current player know that move occurred
players[ currentPlayer ].otherPlayerMoved( location );
gameLock.lock(); // lock game to signal other player to go
try
otherPlayerTurn.signal(); // signal other player to continue
} // end try
finally
gameLock.unlock(); // unlock game after signaling
} // end finally
return true; // notify player that move was valid
} // end if
else // move was not valid
return false; // notify player that move was invalid
} // end method validateAndMove
// determine whether location is occupied
public boolean isOccupied( int location )
if ( board[ location ].equals( MARKS[ PLAYER_X ] ) ||
board [ location ].equals( MARKS[ PLAYER_O ] ) )
return true; // location is occupied
else
return false; // location is not occupied
} // end method isOccupied
// place code in this method to determine whether game over
public boolean isGameOver()
if( ( !board[ 0 ].equals( "" ) &&
!board[ 1 ].equals( "" ) &&
!board[ 2 ].equals( "" ) &&
!board[ 3 ].equals( "" ) &&
!board[ 4 ].equals( "" ) &&
!board[ 5 ].equals( "" ) &&
!board[ 6 ].equals( "" ) &&
!board[ 7 ].equals( "" ) &&
!board[ 8 ].equals( "" ) ) )
players[0].gameOver("Game Over, no winner");
players[1].gameOver("Game Over, no winner");
return true;
else if( board[ 0 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 1 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 2 ].equals( MARKS[ PLAYER_X ] ) )
players[0].gameOver("Player X wins");
players[1].gameOver("Player X wins");
return true;
else if( board [ 0 ].equals( MARKS[ PLAYER_O ]) &&
board [ 1 ].equals( MARKS[ PLAYER_O ]) &&
board [ 2 ].equals( MARKS[ PLAYER_O ]) )
players[0].gameOver("Player O wins");
players[1].gameOver("Player O wins");
return true;
else if( board[ 3 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 4 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 5 ].equals( MARKS[ PLAYER_X ] ) )
players[0].gameOver("Player X wins");
players[1].gameOver("Player X wins");
return true;
else if( board [ 3 ].equals( MARKS[ PLAYER_O ]) &&
board [ 4 ].equals( MARKS[ PLAYER_O ]) &&
board [ 5 ].equals( MARKS[ PLAYER_O ]) )
players[0].gameOver("Player O wins");
players[1].gameOver("Player O wins");
return true;
else if( board[ 6 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 7 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 8 ].equals( MARKS[ PLAYER_X ] ) )
players[0].gameOver("Player X wins");
players[1].gameOver("Player X wins");
return true;
else if( board [ 6 ].equals( MARKS[ PLAYER_O ]) &&
board [ 7 ].equals( MARKS[ PLAYER_O ]) &&
board [ 8 ].equals( MARKS[ PLAYER_O ]) )
players[0].gameOver("Player O wins");
players[1].gameOver("Player O wins");
return true;
else if( board[ 0 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 3 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 6 ].equals( MARKS[ PLAYER_X ] ) )
players[0].gameOver("Player X wins");
players[1].gameOver("Player X wins");
return true;
else if( board[ 0 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 3 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 6 ].equals( MARKS[ PLAYER_X ] ) )
players[0].gameOver("Player O wins");
players[1].gameOver("Player O wins");
return true;
else if( board[ 1 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 4 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 7 ].equals( MARKS[ PLAYER_X ] ) )
players[0].gameOver("Player X wins");
players[1].gameOver("Player X wins");
return true;
else if( board [ 1 ].equals( MARKS[ PLAYER_O ]) &&
board [ 4 ].equals( MARKS[ PLAYER_O ]) &&
board [ 7 ].equals( MARKS[ PLAYER_O ]) )
players[0].gameOver("Player O wins");
players[1].gameOver("Player O wins");
return true;
else if( board[ 2 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 5 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 8 ].equals( MARKS[ PLAYER_X ] ) )
players[0].gameOver("Player X wins");
players[1].gameOver("Player X wins");
return true;
else if( board [ 2 ].equals( MARKS[ PLAYER_O ]) &&
board [ 5 ].equals( MARKS[ PLAYER_O ]) &&
board [ 8 ].equals( MARKS[ PLAYER_O ]) )
players[0].gameOver("Player O wins");
players[1].gameOver("Player O wins");
return true;
else if( board[ 0 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 4 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 8 ].equals( MARKS[ PLAYER_X ] ) )
players[0].gameOver("Player X wins");
players[1].gameOver("Player X wins");
return true;
else if( board [ 0 ].equals( MARKS[ PLAYER_O ]) &&
board [ 4 ].equals( MARKS[ PLAYER_O ]) &&
board [ 8 ].equals( MARKS[ PLAYER_O ]) )
players[0].gameOver("Player O wins");
players[1].gameOver("Player O wins");
return true;
else if( board[ 2 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 4 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 8 ].equals( MARKS[ PLAYER_X ] ) )
players[0].gameOver("Player X wins");
players[1].gameOver("Player X wins");
return true;
else if( board [ 2 ].equals( MARKS[ PLAYER_O ]) &&
board [ 4 ].equals( MARKS[ PLAYER_O ]) &&
board [ 8 ].equals( MARKS[ PLAYER_O ]) )
players[0].gameOver("Player O wins");
players[1].gameOver("Player O wins");
return true;
else
return false; // this is left as an exercise
} // end method isGameOver
// private inner class Player manages each Player as a runnable
private class Player implements Runnable
private Socket connection; // connection to client
private Scanner input; // input from client
private Formatter output; // output to client
private int playerNumber; // tracks which player this is
private String mark; // mark for this player
private boolean suspended = true; // whether thread is suspended
// set up Player thread
public Player( Socket socket, int number )
playerNumber = number; // store this player's number
mark = MARKS[ playerNumber ]; // specify player's mark
connection = socket; // store socket for client
try // obtain streams from Socket
input = new Scanner( connection.getInputStream() );
output = new Formatter( connection.getOutputStream() );
} // end try
catch ( IOException ioException )
ioException.printStackTrace();
System.exit( 1 );
} // end catch
} // end Player constructor
// send message that other player moved
public void otherPlayerMoved( int location )
output.format( "Opponent moved\n" );
output.format( "%d\n", location ); // send location of move
output.flush(); // flush output
} // end method otherPlayerMoved
// control thread's execution
public void run()
// send client its mark (X or O), process messages from client
try
displayMessage( "Player " + mark + " connected\n" );
output.format( "%s\n", mark ); // send player's mark
output.flush(); // flush output
// if player X, wait for another player to arrive
if ( playerNumber == PLAYER_X )
output.format( "%s\n%s", "Player X connected",
"Waiting for another player\n" );
output.flush(); // flush output
gameLock.lock(); // lock game to wait for second player
try
while( suspended )
otherPlayerConnected.await(); // wait for player O
} // end while
} // end try
catch ( InterruptedException exception )
exception.printStackTrace();
} // end catch
finally
gameLock.unlock(); // unlock game after second player
} // end finally
// send message that other player connected
output.format( "Other player connected. Your move.\n" );
output.flush(); // flush output
} // end if
else
output.format( "Player O connected, please wait\n" );
output.flush(); // flush output
} // end else
// while game not over
while ( !isGameOver() )
int location = 0; // initialize move location
if ( input.hasNext() )
location = input.nextInt(); // get move location
// check for valid move
if ( validateAndMove( location, playerNumber ) )
displayMessage( "\nlocation: " + location );
output.format( "Valid move.\n" ); // notify client
output.flush(); // flush output
} // end if
else // move was invalid
output.format( "Invalid move, try again\n" );
output.flush(); // flush output
} // end else
} // end while
} // end try
finally
try
connection.close(); // close connection to client
} // end try
catch ( IOException ioException )
ioException.printStackTrace();
System.exit( 1 );
} // end catch
} // end finally
} // end method run
// set whether or not thread is suspended
public void setSuspended( boolean status )
suspended = status; // set value of suspended
} // end method setSuspended
public void gameOver(String msg)
if(msg.equals("Game Over, no winner"))
if ( playerNumber == PLAYER_X )
output.format( "no winner, you loose\n" );
output.flush(); // flush output
} // end if
else
output.format( "no winner, you loose\n" );
output.flush(); // flush output
} // end else
gameLock.lock();
else if(msg.equals("Player X wins"))
if ( playerNumber == PLAYER_X )
output.format(msg + "\n" );
output.flush(); // flush output
} // end if
else
output.format(msg + ", you loose\n" );
output.flush(); // flush output
} // end else
gameLock.lock();
else if(msg.equals("Player O wins"))
if ( playerNumber == PLAYER_X )
//players[1].
output.format(msg + ", you loose\n" );
output.flush(); // flush output
} // end if
else
output.format(msg + "\n" );
output.flush(); // flush output
} // end else
gameLock.lock();
else
} // end class Player
} // end class TicTacToeServer
*****and here's the code for the client
// Fig. 24.15: TicTacToeClient.java
// Client that let a user play Tic-Tac-Toe with another across a network.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.*;
import java.net.Socket;
import java.net.InetAddress;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
import java.util.Formatter;
import java.util.Scanner;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
public class TicTacToeClient extends JFrame implements Runnable
private JTextField idField; // textfield to display player's mark
private JTextArea displayArea; // JTextArea to display output
private JPanel boardPanel; // panel for tic-tac-toe board
private JPanel panel2; // panel to hold board
private JButton btnNew;
private Square board[][]; // tic-tac-toe board
private Square currentSquare; // current square
private Socket connection; // connection to server
private Scanner input; // input from server
private Formatter output; // output to server
private String ticTacToeHost; // host name for server
private String myMark; // this client's mark
private boolean myTurn; // determines which client's turn it is
private final String X_MARK = "X"; // mark for first client
private final String O_MARK = "O"; // mark for second client
// set up user-interface and board
public TicTacToeClient( String host )
ticTacToeHost = host; // set name of server
displayArea = new JTextArea( 4, 30 ); // set up JTextArea
displayArea.setEditable( false );
add( new JScrollPane( displayArea ), BorderLayout.SOUTH );
boardPanel = new JPanel(); // set up panel for squares in board
boardPanel.setLayout( new GridLayout( 3, 3, 0, 0 ) );
board = new Square[ 3 ][ 3 ]; // create board
// loop over the rows in the board
for ( int row = 0; row < board.length; row++ )
// loop over the columns in the board
for ( int column = 0; column < board[ row ].length; column++ )
// create square
board[ row ][ column ] = new Square( " ", row * 3 + column );
boardPanel.add( board[ row ][ column ] ); // add square
} // end inner for
} // end outer for
idField = new JTextField(); // set up textfield
idField.setEditable( false );
add( idField, BorderLayout.NORTH );
panel2 = new JPanel(); // set up panel to contain boardPanel
btnNew = new JButton("New Game");
panel2.add(btnNew, BorderLayout.NORTH);
panel2.add( boardPanel, BorderLayout.CENTER ); // add board panel
add( panel2, BorderLayout.CENTER ); // add container panel
btnNew.setEnabled(false);
btnNew.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
newGame();
setSize( 300, 225 ); // set size of window
setVisible( true ); // show window
startClient();
} // end TicTacToeClient constructor
// start the client thread
public void startClient()
try // connect to server, get streams and start outputThread
// make connection to server
connection = new Socket(
InetAddress.getByName( ticTacToeHost ), 12345 );
// get streams for input and output
input = new Scanner( connection.getInputStream() );
output = new Formatter( connection.getOutputStream() );
} // end try
catch ( IOException ioException )
ioException.printStackTrace();
} // end catch
// create and start worker thread for this client
ExecutorService worker = Executors.newFixedThreadPool( 1 );
worker.execute( this ); // execute client
} // end method startClient
// control thread that allows continuous update of displayArea
public void run()
myMark = input.nextLine(); // get player's mark (X or O)
SwingUtilities.invokeLater(
new Runnable()
public void run()
// display player's mark
idField.setText( "You are player \"" + myMark + "\"" );
} // end method run
} // end anonymous inner class
); // end call to SwingUtilities.invokeLater
myTurn = ( myMark.equals( X_MARK ) ); // determine if client's turn
// receive messages sent to client and output them
while ( true )
if ( input.hasNextLine() )
processMessage( input.nextLine() );
} // end while
} // end method run
// process messages received by client
private void processMessage( String message )
// valid move occurred
if ( message.equals( "Valid move." ) )
displayMessage( "Valid move, please wait.\n" );
setMark( currentSquare, myMark ); // set mark in square
} // end if
else if ( message.equals( "Invalid move, try again" ) )
displayMessage( message + "\n" ); // display invalid move
myTurn = true; // still this client's turn
} // end else if
else if ( message.equals( "Opponent moved" ) )
int location = input.nextInt(); // get move location
input.nextLine(); // skip newline after int location
int row = location / 3; // calculate row
int column = location % 3; // calculate column
setMark( board[ row ][ column ],
( myMark.equals( X_MARK ) ? O_MARK : X_MARK ) ); // mark move
displayMessage( "Opponent moved. Your turn.\n" );
myTurn = true; // now this client's turn
} // end else if
//Game Over #*********Here**********#
else if ( message.equals( "no winner, you loose" ) )
btnNew.setEnabled(true);
myTurn = false;
} // end else if
else if ( message.equals( "Player X wins" ) ||
message.equals( "Player X wins, you loose" ) )
btnNew.setEnabled(true);
myTurn = false;
} // end else if
else if ( message.equals( "Player O wins" ) ||
message.equals( "Player O wins, you loose" ) )
btnNew.setEnabled(true);
myTurn = false;
} // end else if
else
displayMessage( message + "\n" ); // display the message
} // end method processMessage
//start a new game here
private void newGame()
// manipulate outputArea in event-dispatch thread
private void displayMessage( final String messageToDisplay )
SwingUtilities.invokeLater(
new Runnable()
public void run()
displayArea.append( messageToDisplay ); // updates output
} // end method run
} // end inner class
); // end call to SwingUtilities.invokeLater
} // end method displayMessage
// utility method to set mark on board in event-dispatch thread
private void setMark( final Square squareToMark, final String mark )
SwingUtilities.invokeLater(
new Runnable()
public void run()
squareToMark.setMark( mark ); // set mark in square
} // end method run
} // end anonymous inner class
); // end call to SwingUtilities.invokeLater
} // end method setMark
// send message to server indicating clicked square
public void sendClickedSquare( int location )
// if it is my turn
if ( myTurn )
output.format( "%d\n", location ); // send location to server
output.flush();
myTurn = false; // not my turn anymore
} // end if
} // end method sendClickedSquare
// set current Square
public void setCurrentSquare( Square square )
currentSquare = square; // set current square to argument
} // end method setCurrentSquare
// private inner class for the squares on the board
private class Square extends JPanel
private String mark; // mark to be drawn in this square
private int location; // location of square
public Square( String squareMark, int squareLocation )
mark = squareMark; // set mark for this square
location = squareLocation; // set location of this square
addMouseListener(
new MouseAdapter() {
public void mouseReleased( MouseEvent e )
setCurrentSquare( Square.this ); // set current square
// send location of this square
sendClickedSquare( getSquareLocation() );
} // end method mouseReleased
} // end anonymous inner class
); // end call to addMouseListener
} // end Square constructor
// return preferred size of Square
public Dimension getPreferredSize()
return new Dimension( 30, 30 ); // return preferred size
} // end method getPreferredSize
// return minimum size of Square
public Dimension getMinimumSize()
return getPreferredSize(); // return preferred size
} // end method getMinimumSize
// set mark for Square
public void setMark( String newMark )
mark = newMark; // set mark of square
repaint(); // repaint square
} // end method setMark
// return Square location
public int getSquareLocation()
return location; // return location of square
} // end method getSquareLocation
// draw Square
public void paintComponent( Graphics g )
super.paintComponent( g );
g.drawRect( 0, 0, 29, 29 ); // draw square
g.drawString( mark, 11, 20 ); // draw mark
} // end method paintComponent
} // end inner-class Square
} // end class TicTacToeClient
Please any kind of help will be appreciated.
HELP!!!I would be happy to help you, but I've decided not to contribute here anymore because of the poor way in which this site is being administered.
Others are still helping, but more may leave if things don't improve. May I recommend devshed or javaranch?
http://www.devshed.com/
http://www.javaranch.com/
If you would like to complain to the amdins of this forum, either click the "Report Abuse" link or the "Feedback" link. -
Hi
I used Deitel's code of TicTacToe program that creats a server and have 2 clients playing TicTacToe. When the game is over one of the client has to click on new game and a new game will begin. I don't know how to do this.
Please Help.
Here's the code for the server
import java.awt.BorderLayout;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
import java.util.Formatter;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.Condition;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class TicTacToeServer extends JFrame
private String[] board = new String[ 9 ]; // tic-tac-toe board
private JTextArea outputArea; // for outputting moves
private Player[] players; // array of Players
private ServerSocket server; // server socket to connect with clients
private int currentPlayer; // keeps track of player with current move
private final static int PLAYER_X = 0; // constant for first player
private final static int PLAYER_O = 1; // constant for second player
private final static String[] MARKS = { "X", "O" }; // array of marks
private ExecutorService runGame; // will run players
private Lock gameLock; // to lock game for synchronization
private Condition otherPlayerConnected; // to wait for other player
private Condition otherPlayerTurn; // to wait for other player's turn
// set up tic-tac-toe server and GUI that displays messages
public TicTacToeServer()
super( "Tic-Tac-Toe Server" ); // set title of window
// create ExecutorService with a thread for each player
runGame = Executors.newFixedThreadPool( 2 );
gameLock = new ReentrantLock(); // create lock for game
// condition variable for both players being connected
otherPlayerConnected = gameLock.newCondition();
// condition variable for the other player's turn
otherPlayerTurn = gameLock.newCondition();
for ( int i = 0; i < 9; i++ )
board[ i ] = new String( "" ); // create tic-tac-toe board
players = new Player[ 2 ]; // create array of players
currentPlayer = PLAYER_X; // set current player to first player
try
server = new ServerSocket( 12345, 2 ); // set up ServerSocket
} // end try
catch ( IOException ioException )
ioException.printStackTrace();
System.exit( 1 );
} // end catch
outputArea = new JTextArea(); // create JTextArea for output
add( outputArea, BorderLayout.CENTER );
outputArea.setText( "Server awaiting connections\n" );
setSize( 300, 300 ); // set size of window
setVisible( true ); // show window
} // end TicTacToeServer constructor
// wait for two connections so game can be played
public void execute()
// wait for each client to connect
for ( int i = 0; i < players.length; i++ )
try // wait for connection, create Player, start runnable
players[ i ] = new Player( server.accept(), i );
runGame.execute( players[ i ] ); // execute player runnable
} // end try
catch ( IOException ioException )
ioException.printStackTrace();
System.exit( 1 );
} // end catch
} // end for
gameLock.lock(); // lock game to signal player X's thread
try
players[ PLAYER_X ].setSuspended( false ); // resume player X
otherPlayerConnected.signal(); // wake up player X's thread
} // end try
finally
gameLock.unlock(); // unlock game after signalling player X
} // end finally
} // end method execute
// display message in outputArea
private void displayMessage( final String messageToDisplay )
// display message from event-dispatch thread of execution
SwingUtilities.invokeLater(
new Runnable()
public void run() // updates outputArea
outputArea.append( messageToDisplay ); // add message
} // end method run
} // end inner class
); // end call to SwingUtilities.invokeLater
} // end method displayMessage
// determine if move is valid
public boolean validateAndMove( int location, int player )
// while not current player, must wait for turn
while ( player != currentPlayer )
gameLock.lock(); // lock game to wait for other player to go
try
otherPlayerTurn.await(); // wait for player's turn
} // end try
catch ( InterruptedException exception )
exception.printStackTrace();
} // end catch
finally
gameLock.unlock(); // unlock game after waiting
} // end finally
} // end while
// if location not occupied, make move
if ( !isOccupied( location ) )
board[ location ] = MARKS[ currentPlayer ]; // set move on board
currentPlayer = ( currentPlayer + 1 ) % 2; // change player
// let new current player know that move occurred
players[ currentPlayer ].otherPlayerMoved( location );
gameLock.lock(); // lock game to signal other player to go
try
otherPlayerTurn.signal(); // signal other player to continue
} // end try
finally
gameLock.unlock(); // unlock game after signaling
} // end finally
return true; // notify player that move was valid
} // end if
else // move was not valid
return false; // notify player that move was invalid
} // end method validateAndMove
// determine whether location is occupied
public boolean isOccupied( int location )
if ( board[ location ].equals( MARKS[ PLAYER_X ] ) ||
board [ location ].equals( MARKS[ PLAYER_O ] ) )
return true; // location is occupied
else
return false; // location is not occupied
} // end method isOccupied
// place code in this method to determine whether game over
public boolean isGameOver()
if( ( !board[ 0 ].equals( "" ) &&
!board[ 1 ].equals( "" ) &&
!board[ 2 ].equals( "" ) &&
!board[ 3 ].equals( "" ) &&
!board[ 4 ].equals( "" ) &&
!board[ 5 ].equals( "" ) &&
!board[ 6 ].equals( "" ) &&
!board[ 7 ].equals( "" ) &&
!board[ 8 ].equals( "" ) ) )
players[0].gameOver("Game Over, no winner");
players[1].gameOver("Game Over, no winner");
return true;
else if( board[ 0 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 1 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 2 ].equals( MARKS[ PLAYER_X ] ) )
players[0].gameOver("Player X wins");
players[1].gameOver("Player X wins");
return true;
else if( board [ 0 ].equals( MARKS[ PLAYER_O ]) &&
board [ 1 ].equals( MARKS[ PLAYER_O ]) &&
board [ 2 ].equals( MARKS[ PLAYER_O ]) )
players[0].gameOver("Player O wins");
players[1].gameOver("Player O wins");
return true;
else if( board[ 3 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 4 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 5 ].equals( MARKS[ PLAYER_X ] ) )
players[0].gameOver("Player X wins");
players[1].gameOver("Player X wins");
return true;
else if( board [ 3 ].equals( MARKS[ PLAYER_O ]) &&
board [ 4 ].equals( MARKS[ PLAYER_O ]) &&
board [ 5 ].equals( MARKS[ PLAYER_O ]) )
players[0].gameOver("Player O wins");
players[1].gameOver("Player O wins");
return true;
else if( board[ 6 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 7 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 8 ].equals( MARKS[ PLAYER_X ] ) )
players[0].gameOver("Player X wins");
players[1].gameOver("Player X wins");
return true;
else if( board [ 6 ].equals( MARKS[ PLAYER_O ]) &&
board [ 7 ].equals( MARKS[ PLAYER_O ]) &&
board [ 8 ].equals( MARKS[ PLAYER_O ]) )
players[0].gameOver("Player O wins");
players[1].gameOver("Player O wins");
return true;
else if( board[ 0 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 3 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 6 ].equals( MARKS[ PLAYER_X ] ) )
players[0].gameOver("Player X wins");
players[1].gameOver("Player X wins");
return true;
else if( board[ 0 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 3 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 6 ].equals( MARKS[ PLAYER_X ] ) )
players[0].gameOver("Player O wins");
players[1].gameOver("Player O wins");
return true;
else if( board[ 1 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 4 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 7 ].equals( MARKS[ PLAYER_X ] ) )
players[0].gameOver("Player X wins");
players[1].gameOver("Player X wins");
return true;
else if( board [ 1 ].equals( MARKS[ PLAYER_O ]) &&
board [ 4 ].equals( MARKS[ PLAYER_O ]) &&
board [ 7 ].equals( MARKS[ PLAYER_O ]) )
players[0].gameOver("Player O wins");
players[1].gameOver("Player O wins");
return true;
else if( board[ 2 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 5 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 8 ].equals( MARKS[ PLAYER_X ] ) )
players[0].gameOver("Player X wins");
players[1].gameOver("Player X wins");
return true;
else if( board [ 2 ].equals( MARKS[ PLAYER_O ]) &&
board [ 5 ].equals( MARKS[ PLAYER_O ]) &&
board [ 8 ].equals( MARKS[ PLAYER_O ]) )
players[0].gameOver("Player O wins");
players[1].gameOver("Player O wins");
return true;
else if( board[ 0 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 4 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 8 ].equals( MARKS[ PLAYER_X ] ) )
players[0].gameOver("Player X wins");
players[1].gameOver("Player X wins");
return true;
else if( board [ 0 ].equals( MARKS[ PLAYER_O ]) &&
board [ 4 ].equals( MARKS[ PLAYER_O ]) &&
board [ 8 ].equals( MARKS[ PLAYER_O ]) )
players[0].gameOver("Player O wins");
players[1].gameOver("Player O wins");
return true;
else if( board[ 2 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 4 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 8 ].equals( MARKS[ PLAYER_X ] ) )
players[0].gameOver("Player X wins");
players[1].gameOver("Player X wins");
return true;
else if( board [ 2 ].equals( MARKS[ PLAYER_O ]) &&
board [ 4 ].equals( MARKS[ PLAYER_O ]) &&
board [ 8 ].equals( MARKS[ PLAYER_O ]) )
players[0].gameOver("Player O wins");
players[1].gameOver("Player O wins");
return true;
else
return false; // this is left as an exercise
} // end method isGameOver
// private inner class Player manages each Player as a runnable
private class Player implements Runnable
private Socket connection; // connection to client
private Scanner input; // input from client
private Formatter output; // output to client
private int playerNumber; // tracks which player this is
private String mark; // mark for this player
private boolean suspended = true; // whether thread is suspended
// set up Player thread
public Player( Socket socket, int number )
playerNumber = number; // store this player's number
mark = MARKS[ playerNumber ]; // specify player's mark
connection = socket; // store socket for client
try // obtain streams from Socket
input = new Scanner( connection.getInputStream() );
output = new Formatter( connection.getOutputStream() );
} // end try
catch ( IOException ioException )
ioException.printStackTrace();
System.exit( 1 );
} // end catch
} // end Player constructor
// send message that other player moved
public void otherPlayerMoved( int location )
output.format( "Opponent moved\n" );
output.format( "%d\n", location ); // send location of move
output.flush(); // flush output
} // end method otherPlayerMoved
// control thread's execution
public void run()
// send client its mark (X or O), process messages from client
try
displayMessage( "Player " + mark + " connected\n" );
output.format( "%s\n", mark ); // send player's mark
output.flush(); // flush output
// if player X, wait for another player to arrive
if ( playerNumber == PLAYER_X )
output.format( "%s\n%s", "Player X connected",
"Waiting for another player\n" );
output.flush(); // flush output
gameLock.lock(); // lock game to wait for second player
try
while( suspended )
otherPlayerConnected.await(); // wait for player O
} // end while
} // end try
catch ( InterruptedException exception )
exception.printStackTrace();
} // end catch
finally
gameLock.unlock(); // unlock game after second player
} // end finally
// send message that other player connected
output.format( "Other player connected. Your move.\n" );
output.flush(); // flush output
} // end if
else
output.format( "Player O connected, please wait\n" );
output.flush(); // flush output
} // end else
// while game not over
while ( !isGameOver() )
int location = 0; // initialize move location
if ( input.hasNext() )
location = input.nextInt(); // get move location
// check for valid move
if ( validateAndMove( location, playerNumber ) )
displayMessage( "\nlocation: " + location );
output.format( "Valid move.\n" ); // notify client
output.flush(); // flush output
} // end if
else // move was invalid
output.format( "Invalid move, try again\n" );
output.flush(); // flush output
} // end else
} // end while
} // end try
finally
try
connection.close(); // close connection to client
} // end try
catch ( IOException ioException )
ioException.printStackTrace();
System.exit( 1 );
} // end catch
} // end finally
} // end method run
// set whether or not thread is suspended
public void setSuspended( boolean status )
suspended = status; // set value of suspended
} // end method setSuspended
public void gameOver(String msg)
if(msg.equals("Game Over, no winner"))
if ( playerNumber == PLAYER_X )
output.format( "no winner, you loose\n" );
output.flush(); // flush output
} // end if
else
output.format( "no winner, you loose\n" );
output.flush(); // flush output
} // end else
gameLock.lock();
else if(msg.equals("Player X wins"))
if ( playerNumber == PLAYER_X )
output.format(msg + "\n" );
output.flush(); // flush output
} // end if
else
output.format(msg + ", you loose\n" );
output.flush(); // flush output
} // end else
gameLock.lock();
else if(msg.equals("Player O wins"))
if ( playerNumber == PLAYER_X )
//players[1].
output.format(msg + ", you loose\n" );
output.flush(); // flush output
} // end if
else
output.format(msg + "\n" );
output.flush(); // flush output
} // end else
gameLock.lock();
else
} // end class Player
} // end class TicTacToeServer
*****and here's the code for the client
// Fig. 24.15: TicTacToeClient.java
// Client that let a user play Tic-Tac-Toe with another across a network.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.*;
import java.net.Socket;
import java.net.InetAddress;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
import java.util.Formatter;
import java.util.Scanner;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
public class TicTacToeClient extends JFrame implements Runnable
private JTextField idField; // textfield to display player's mark
private JTextArea displayArea; // JTextArea to display output
private JPanel boardPanel; // panel for tic-tac-toe board
private JPanel panel2; // panel to hold board
private JButton btnNew;
private Square board[][]; // tic-tac-toe board
private Square currentSquare; // current square
private Socket connection; // connection to server
private Scanner input; // input from server
private Formatter output; // output to server
private String ticTacToeHost; // host name for server
private String myMark; // this client's mark
private boolean myTurn; // determines which client's turn it is
private final String X_MARK = "X"; // mark for first client
private final String O_MARK = "O"; // mark for second client
// set up user-interface and board
public TicTacToeClient( String host )
ticTacToeHost = host; // set name of server
displayArea = new JTextArea( 4, 30 ); // set up JTextArea
displayArea.setEditable( false );
add( new JScrollPane( displayArea ), BorderLayout.SOUTH );
boardPanel = new JPanel(); // set up panel for squares in board
boardPanel.setLayout( new GridLayout( 3, 3, 0, 0 ) );
board = new Square[ 3 ][ 3 ]; // create board
// loop over the rows in the board
for ( int row = 0; row < board.length; row++ )
// loop over the columns in the board
for ( int column = 0; column < board[ row ].length; column++ )
// create square
board[ row ][ column ] = new Square( " ", row * 3 + column );
boardPanel.add( board[ row ][ column ] ); // add square
} // end inner for
} // end outer for
idField = new JTextField(); // set up textfield
idField.setEditable( false );
add( idField, BorderLayout.NORTH );
panel2 = new JPanel(); // set up panel to contain boardPanel
btnNew = new JButton("New Game");
panel2.add(btnNew, BorderLayout.NORTH);
panel2.add( boardPanel, BorderLayout.CENTER ); // add board panel
add( panel2, BorderLayout.CENTER ); // add container panel
btnNew.setEnabled(false);
btnNew.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
newGame();
setSize( 300, 225 ); // set size of window
setVisible( true ); // show window
startClient();
} // end TicTacToeClient constructor
// start the client thread
public void startClient()
try // connect to server, get streams and start outputThread
// make connection to server
connection = new Socket(
InetAddress.getByName( ticTacToeHost ), 12345 );
// get streams for input and output
input = new Scanner( connection.getInputStream() );
output = new Formatter( connection.getOutputStream() );
} // end try
catch ( IOException ioException )
ioException.printStackTrace();
} // end catch
// create and start worker thread for this client
ExecutorService worker = Executors.newFixedThreadPool( 1 );
worker.execute( this ); // execute client
} // end method startClient
// control thread that allows continuous update of displayArea
public void run()
myMark = input.nextLine(); // get player's mark (X or O)
SwingUtilities.invokeLater(
new Runnable()
public void run()
// display player's mark
idField.setText( "You are player \"" + myMark + "\"" );
} // end method run
} // end anonymous inner class
); // end call to SwingUtilities.invokeLater
myTurn = ( myMark.equals( X_MARK ) ); // determine if client's turn
// receive messages sent to client and output them
while ( true )
if ( input.hasNextLine() )
processMessage( input.nextLine() );
} // end while
} // end method run
// process messages received by client
private void processMessage( String message )
// valid move occurred
if ( message.equals( "Valid move." ) )
displayMessage( "Valid move, please wait.\n" );
setMark( currentSquare, myMark ); // set mark in square
} // end if
else if ( message.equals( "Invalid move, try again" ) )
displayMessage( message + "\n" ); // display invalid move
myTurn = true; // still this client's turn
} // end else if
else if ( message.equals( "Opponent moved" ) )
int location = input.nextInt(); // get move location
input.nextLine(); // skip newline after int location
int row = location / 3; // calculate row
int column = location % 3; // calculate column
setMark( board[ row ][ column ],
( myMark.equals( X_MARK ) ? O_MARK : X_MARK ) ); // mark move
displayMessage( "Opponent moved. Your turn.\n" );
myTurn = true; // now this client's turn
} // end else if
//Game Over #*********Here**********#
else if ( message.equals( "no winner, you loose" ) )
btnNew.setEnabled(true);
myTurn = false;
} // end else if
else if ( message.equals( "Player X wins" ) ||
message.equals( "Player X wins, you loose" ) )
btnNew.setEnabled(true);
myTurn = false;
} // end else if
else if ( message.equals( "Player O wins" ) ||
message.equals( "Player O wins, you loose" ) )
btnNew.setEnabled(true);
myTurn = false;
} // end else if
else
displayMessage( message + "\n" ); // display the message
} // end method processMessage
//start a new game here
private void newGame()
// manipulate outputArea in event-dispatch thread
private void displayMessage( final String messageToDisplay )
SwingUtilities.invokeLater(
new Runnable()
public void run()
displayArea.append( messageToDisplay ); // updates output
} // end method run
} // end inner class
); // end call to SwingUtilities.invokeLater
} // end method displayMessage
// utility method to set mark on board in event-dispatch thread
private void setMark( final Square squareToMark, final String mark )
SwingUtilities.invokeLater(
new Runnable()
public void run()
squareToMark.setMark( mark ); // set mark in square
} // end method run
} // end anonymous inner class
); // end call to SwingUtilities.invokeLater
} // end method setMark
// send message to server indicating clicked square
public void sendClickedSquare( int location )
// if it is my turn
if ( myTurn )
output.format( "%d\n", location ); // send location to server
output.flush();
myTurn = false; // not my turn anymore
} // end if
} // end method sendClickedSquare
// set current Square
public void setCurrentSquare( Square square )
currentSquare = square; // set current square to argument
} // end method setCurrentSquare
// private inner class for the squares on the board
private class Square extends JPanel
private String mark; // mark to be drawn in this square
private int location; // location of square
public Square( String squareMark, int squareLocation )
mark = squareMark; // set mark for this square
location = squareLocation; // set location of this square
addMouseListener(
new MouseAdapter() {
public void mouseReleased( MouseEvent e )
setCurrentSquare( Square.this ); // set current square
// send location of this square
sendClickedSquare( getSquareLocation() );
} // end method mouseReleased
} // end anonymous inner class
); // end call to addMouseListener
} // end Square constructor
// return preferred size of Square
public Dimension getPreferredSize()
return new Dimension( 30, 30 ); // return preferred size
} // end method getPreferredSize
// return minimum size of Square
public Dimension getMinimumSize()
return getPreferredSize(); // return preferred size
} // end method getMinimumSize
// set mark for Square
public void setMark( String newMark )
mark = newMark; // set mark of square
repaint(); // repaint square
} // end method setMark
// return Square location
public int getSquareLocation()
return location; // return location of square
} // end method getSquareLocation
// draw Square
public void paintComponent( Graphics g )
super.paintComponent( g );
g.drawRect( 0, 0, 29, 29 ); // draw square
g.drawString( mark, 11, 20 ); // draw mark
} // end method paintComponent
} // end inner-class Square
} // end class TicTacToeClient
Please any kind of help will be appreciated.
HELP!!!This isn't a code writing service.
Start your own thread, rather than reviving one that is very old. And ask a question: that is, actually describe in what respect your program is not working. Often the most effective way of doing this is to post some code whose runtime behaviour is not what you expect or intend. If you do post code make sure it's brief and to the point (ie just illustrates the problem you are having). To make sure your code is readable when you post it here use the code tags: put {code} at the start of your code and the same thing again at the end. -
Hi,
I'm taking an introductory Java class, and I'm just trying to complete an assignment in my textbook. Here is a copy of the code that I'm having a problem with:
import java.util.Scanner;
public class TicTacToeClient
public static void main( String [] args )
Scanner scan = new Scanner( System.in );
TicTacToe ttt1 = new TicTacToe( );
String garbage;
int player = 1;
boolean gameOver = false;
int position;
while ( ! gameOver )
System.out.print( "Please enter a position, player " + player + " > " );
while( ! scan.hasNextInt( ) )
garbage = scan.nextLine( );
System.out.print( "Please enter a valid position, player " + player + " > " );
position = scan.nextInt( );
if ( ! ttt1.isLegal( position ) )
System.out.println( "This position is already used!" );
else
ttt1.makeMove( player, position );
if ( ttt1.gameWon( player ) || ttt1.isTie( ) )
gameOver = true;
else
if ( player == 1 )
player = 2;
else
player = 1;
ttt1.printWinner( player );
I'm very sorry if the format of this code is hard to read, as the message textbox is pretty small.
Anyhow, when I enter 0 for player 1, and then an invalid character for player 2 ( such as 'j' ), I get the "Please enter a valid value ..." message twice in a row. I thought that the scan.hasNextInt( ) condition in the while loop would wait for the user to press Enter before repeating the loop. Why does this happen and how can I correct it?
Thanks in advance for your help.
Message was edited by:
invinciBillThanks for the link.
This should be easier to read:
import java.util.Scanner;
public class TicTacToeClient
public static void main( String [] args )
Scanner scan = new Scanner( System.in );
TicTacToe ttt1 = new TicTacToe( );
String garbage;
int player = 1;
boolean gameOver = false;
int position;
while ( ! gameOver )
System.out.print( "Please enter a position, player " + player + " > " );
while( ! scan.hasNextInt( ) )
garbage = scan.nextLine( );
System.out.print( "Please enter a valid position, player " + player + " > " );
position = scan.nextInt( );
if ( ! ttt1.isLegal( position ) )
System.out.println( "This position is already used!" );
else
ttt1.makeMove( player, position );
if ( ttt1.gameWon( player ) || ttt1.isTie( ) )
gameOver = true;
else
if ( player == 1 )
player = 2;
else
player = 1;
ttt1.printWinner( player );
} -
I am very new to java and our teacher has given us a program
that i am having quite a bit of trouble with. I was wondering if anyone could help me out.
This is the program which i have bolded.
{You will write a Java class to play the TicTacToe game. This program will have at least two data members, one for the status of the board and one to keep track of whose turn it is. All data members must be private. You will create a user interface that allows client code to play the game.
The user interface must include:
� Boolean xPlay(int num) which allows x to play in the square labeled by num. This function will return true if that play caused the game to end and false otherwise.
� Boolean oPlay(int num) which allows o to play in the square labeled by num. This function will return true if that play caused the game to end and false otherwise.
� Boolean isEmpty(int num) will check to see if the square labeled by num is empty.
� Void display() which displays the current game status to the screen.
� Char whoWon() which will return X, O, or C depending on the outcome of the game.
� You must not allow the same player to play twice in a row. Should the client code attempt to, xPlay or oPlay should print an error and do nothing else.
� Also calling whoWon when the game is not over should produce an error message and return a character other than X, O, or C.
� Client code for the moment is up to you. Assume you have two human players that can enter the number of the square in which they want to play.
Verifying user input WILL be done by the client code.}This is the program which i have bolded.Hmmm, that doesn't look like any programming language I've ever seen. I guess you have the wrong forum here, because it isn't Java.
That looks like a natural-language programming language that directly understands a homework assignment. Either that, or you really did just post the assignment. You wouldn't have done that though, right? -
Hello Sir/Mam,
Im Sanjeev Das from Bhilai(C.G.). Doing my B.E.(C.S.) and in final year from RCET, Bhilai.And has been selected by RISPL, Bhilai and Lambent, Nagpur mobiles companies.
My J2ME training was completed from RISPL on June of calendar year. RISPL is the Bhilai`s only InfoTech company that works on J2ME and Brew Tech.
Now with my hand I have three Game :-
1. Chakravue....(The Maze).
2. Tic-Tac-Toe.
3. Brick Game.
Now Im interested in application program that�s why my next project is �MobileBluetoothApplication� in which Im providing user to exchange data like image, text, sound�etc files through Bluetooth.
But one problem is there. Im not able to send the text and sound files through the Bluetooth. Please help me so that my project can grow up and perform the best result.Hi !
Place this code net benas file or any editor
it will work on stand alone phone
Premal
* TicTacToe.java
* Created on April 4, 2006, 10:14 PM
* @author premal lathiya
* @version
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class TicTacToe extends MIDlet
private Display display;
private MyCanvas canvas;
public TicTacToe ()
display = Display.getDisplay(this);
protected void startApp()
canvas = new MyCanvas (this);
display.setCurrent( canvas );
protected void pauseApp()
protected void destroyApp( boolean unconditional )
public void exitMIDlet()
destroyApp(true);
notifyDestroyed();
class MyCanvas extends Canvas implements CommandListener
private Command exit, restart;
private TicTacToe ticTacToe;
int[] gameArr= new int[10];
int position[][]=new int[10][2];
int startX=2;
int startY=2;
boolean b=true, gameOverFlag=false;
Image img1,img2;
public MyCanvas (TicTacToe ticTacToe)
this.ticTacToe = ticTacToe;
exit = new Command("Exit", Command.EXIT, 1);
restart = new Command("Restart", Command.SCREEN, 1);
addCommand(exit);
setCommandListener(this);
position[1][0]=startX;
position[1][1]=startY;
position[2][0]=(getWidth())/3;
position[2][1]=startY;
position[3][0]=2*((getWidth())/3);
position[3][1]=startY;
position[4][0]=startX;
position[4][1]=(getHeight()-50)/3;
position[5][0]=(getWidth())/3;
position[5][1]=(getHeight()-50)/3;
position[6][0]=2*((getWidth())/3);
position[6][1]=(getHeight()-50)/3;
position[7][0]=startX;
position[7][1]=2*((getHeight()-50)/3);
position[8][0]=(getWidth())/3;
position[8][1]=2*((getHeight()-50)/3);
position[9][0]=2*((getWidth())/3);
position[9][1]=2*((getHeight()-50)/3);
for(int i=0;i<10;i++)
{ gameArr[i] =0;
protected void paint(Graphics graphics)
int width=getWidth();
int height=getHeight();
boolean flag=false;
graphics.setColor(255,255,255);
graphics.fillRect(0, 0, width, height);
graphics.setColor(255,0,0);
graphics.drawRect(startX, startY, width-10, height-50);
graphics.drawLine(width/3,2,width/3,height-50+2);
graphics.drawLine(2*(width/3),2,2*(width/3),height-50+2);
graphics.drawLine(2,(height-50)/3,width-8,(height-50)/3);
graphics.drawLine(2,2*(height-50)/3,width-8,2*(height-50)/3);
for(int i=1;i<10;i++)
if (gameArr[i] != 0)
if(gameArr==1)
graphics.drawString("0", position[i][0]+5,position[i][1]+5,0); //zero
else
graphics.drawString("X", position[i][0]+5,position[i][1]+5,0); //zero
if(gameArr[i] == 0)
flag = true;
if(flag == false)
graphics.drawString("No Result", getWidth() / 3, getHeight() - 30, 0);
addCommand(restart);
else if(gameOverFlag && !b)
graphics.drawString("Player-1 wins", getWidth() / 3, getHeight() - 30, 0);
else if(gameOverFlag && b)
graphics.drawString("Player-2 wins", getWidth() / 3, getHeight() - 30, 0);
public void commandAction(Command command, Displayable displayable)
if (command == exit)
ticTacToe.exitMIDlet();
else if(command == restart)
ticTacToe.startApp();
protected void keyPressed(int key)
if(gameOverFlag)
return;
switch ( key )
case KEY_NUM1:
setValue(1);
break;
case KEY_NUM2:
setValue(2);
break;
case KEY_NUM3:
setValue(3);
break;
case KEY_NUM4:
setValue(4);
break;
case KEY_NUM5:
setValue(5);
break;
case KEY_NUM6:
setValue(6);
break;
case KEY_NUM7:
setValue(7);
break;
case KEY_NUM8:
setValue(8);
break;
case KEY_NUM9:
setValue(9);
break;
repaint();
checkWin();
public void setValue(int subScript){
if(gameArr[subScript] == 0){
if(b)
gameArr[subScript] = 1; //zero
else
gameArr[subScript] = 2; //cross
b=!b;
public void checkWin()
if((gameArr[1] == 1 && gameArr[2] == 1 && gameArr[3] == 1) ||
(gameArr[4] == 1 && gameArr[5] == 1 && gameArr[6] == 1) ||
(gameArr[7] == 1 && gameArr[8] == 1 && gameArr[9] == 1) ||
(gameArr[1] == 1 && gameArr[4] == 1 && gameArr[7] == 1) ||
(gameArr[2] == 1 && gameArr[5] == 1 && gameArr[8] == 1) ||
(gameArr[3] == 1 && gameArr[6] == 1 && gameArr[9] == 1) ||
(gameArr[1] == 1 && gameArr[5] == 1 && gameArr[9] == 1) ||
(gameArr[3] == 1 && gameArr[5] == 1 && gameArr[7] == 1))
gameOverFlag = true;
addCommand(restart);
if((gameArr[1] == 2 && gameArr[2] == 2 && gameArr[3] == 2) ||
(gameArr[4] == 2 && gameArr[5] == 2 && gameArr[6] == 2) ||
(gameArr[7] == 2 && gameArr[8] == 2 && gameArr[9] == 2) ||
(gameArr[1] == 2 && gameArr[4] == 2 && gameArr[7] == 2) ||
(gameArr[2] == 2 && gameArr[5] == 2 && gameArr[8] == 2) ||
(gameArr[3] == 2 && gameArr[6] == 2 && gameArr[9] == 2) ||
(gameArr[1] == 2 && gameArr[5] == 2 && gameArr[9] == 2) ||
(gameArr[3] == 2 && gameArr[5] == 2 && gameArr[7] == 2))
gameOverFlag = true;
addCommand(restart); -
I have this code so far and it won't compile, and I don't know how to fix it, can anyone help me?
import java.awt.*;
import javax.swing.*;
public class TicTacToe extends JFrame{
public void main (String [] args){
TicTacToe t3 = new TicTacToe();
t3.setSize(400, 400);
t3.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
t3.setLayout(new GridLayout(3,3));
JButton NW = new JButton("");
JButton N = new JButton("");
JButton NE = new JButton("");
JButton W = new JButton("");
JButton C = new JButton("");
JButton E = new JButton("");
JButton SW = new JButton("");
JButton S = new JButton("");
JButton SE = new JButton("");
t3.add(NW);
NW.addActionListener(new PressedButton());
t3.add(N);
N.addActionListener(new PressedButton());
t3.add(NE);
NE.addActionListener(new PressedButton());
t3.add(W);
W.addActionListener(new PressedButton());
t3.add(C);
C.addActionListener(new PressedButton());
t3.add(E);
E.addActionListener(new PressedButton());
t3.add(SW);
SW.addActionListener(new PressedButton());
t3.add(S);
SW.addActionListener(new PressedButton());
t3.add(SE);
SE.addActionListener(new PressedButton());
t3.setVisible(true);
public class PressedButton implements ActionListener{
public void actionPerformed(ActionEvent e){
JButton button = (JButton)e.getSource();
if (O turn){
button.setText("O");
}else{
button.setText("X");
private class checkEndgame{
private void checkEndgame(){
for (final int[] winChance : TicTacToe.winChances) {
if (this.checkVictory(winChance)) {
final String winner = this.turn.equals("X") ? "O" : "X";
JOptionPane.showMessageDialog(this.frame, winner + " won the game!",
"Game Over", JOptionPane.INFORMATION_MESSAGE);
this.reset();
return;
Does anyone notice any errors that i might have over looked?
thanksOk scratch out that entire code, i started over and it still won't compile.
import java.awt.*;
import javax.swing.*;
import java.awt.event;
public class TicTacToe implements ActionListener{
private int[][] winCombinations = new int[][]{
{1, 2, 3}, {4, 5, 6}, {7, 8, 9},
{1, 4, 7}, {2, 5, 8}, {3, 6, 9},
{1, 5, 9}, {3, 5, 7}
private JFrame window = new JFrame("Tic-Tac-Toe");
private JButton buttons[] = new JButton[10];
private int count = 0;
private String letter = "";
private boolean win = false;
public class PressedButton{
public void actionPerformed(ActionEvent a) {
count++;
if(count % 2 == 0){
letter = "O";
} else {
letter = "X";
for(int t=1; t<=9; t++){
if(a.getSource() == buttons[t]){
buttons[t].setText(letter);
buttons[t].setEnabled(false);
for(int i=0; i<=7; i++){
if( buttons[winCombinations[t][0]].getText() == buttons[winCombinations[t][1]].getText() &&
buttons[winCombinations[t][1]].getText() == buttons[winCombinations[t][2]].getText() &&
buttons[winCombinations[t][0]].getText() != ""){
win = true;
if(win == true){
JOptionPane.showMessageDialog(null, letter + " wins the game!");
System.exit(0);
} else if(count == 9 && win == false){
JOptionPane.showMessageDialog(null, "The game was a tie!");
System.exit(0);
the error message says that I still need a "}" on line 49 which is the line after the last bracket that I have, I put one there and it still shows up an error message, what do I do? -
Start to Buffering- need help !
Hello !
I'm starting with game programing. FIrst did a tictactoe game and after that tried to make some animated things, but I notice flikering, so I read something about buffered image in 2D api tutorial of java tutorials. Where I can find more things about 2D java api and buffered image.
Thanks on advanced, and sorry about my poor english.
Tiago de Souza
ticdd
[email protected]Thanks for the trick.
I read some of 2d java api and tried do a test but I take a "out of memory" error, what the problem ? Someone can help me ?
The CODE:
class CanvasPainel extends Canvas{
private
double widthContainer,heightContainer;
private
BufferedImage img;
private
boolean firstTime=true;
private
Graphics2D gBuf;
private
Rectangle rect = new Rectangle(this.getWidth()/2, is.getHeight()/3);
public CanvasPainel(){
//img=Toolkit.getDefaultToolkit().getImage(getClass().getResource("clouds.jpg"));
setSize(400,400);
setBackground(Color.black);
widthContainer = (double)getWidth()/12;
heightContainer= (double)getHeight()/20;
}//end constructor method
public void paint(Graphics g){
super.paint(g);
Graphics2D g2 =(Graphics2D)g;
if(firstTime){
img=(BufferedImage)createImage(this.getWidth(), his.getHeight());
gBuf=img.createGraphics();
gBuf.setColor(getForeground());
gBuf.fillRect (20, 50, this.getSize().width/2, this.getSize().height/3);
paint(gBuf);
g2.drawImage(img,0,0,this);
}//CanvasPainel class end -
Executable Jar file, please help!!!
I know this has been posted many times before, but Im going insane, and nothing is working, I will now have spent more time trying to make an executable jar file, than the time I spent actually writing the program, here's my problem
I got two classes, tictactoe.class, and whichBox.class, I want to make a jar file, I have tried many types of manifest files, none worked, my Main() is in tictactoe.class, if ANYONE can help me get this working I will give them dukes!!!!!I know this has been posted many times before, but Im
going insane, and nothing is working, I will now have
spent more time trying to make an executable jar file,
than the time I spent actually writing the program,
here's my problem
I got two classes, tictactoe.class, and
whichBox.class, I want to make a jar file, I have
tried many types of manifest files, none worked, my
Main() is in tictactoe.class, if ANYONE can help me
get this working I will give them dukes!!!!!
your manifest file should look like this...
Manifest-Version: 1.0
Main-Class: tictactoeplease note there must be a line return at the end of tictactoe. so the file should have three lines.
if you have this correct the only other thing i can suggest is are you sure it is your manifest file that is being added to the jar.
your jar command should look like the following assuming the jar files is called Game, your manifest is called game.mf and both files reside in the default package.
jar -cvfm Game.jar game.mf *.class hope this helps.
Maybe you are looking for
-
How to retrieve PARTNER_NUMBER from IBRELATION/Partner view (Install bases)
Hi Experts, I've added an enhancement field in IBDETAIL/Header. Within the I-GETTER of this new field I need to retrieve PARTNER_NUMBER of a specific PARTNER_FCT (Partner Function), say '00000002'. IBDETAIL is one of the views in the component IBMAIN
-
Yep so i have a couple of really good hi fi speakers donated by relati'ves. I've tried these through using my home theatre kit amp, connected via a coaxial lead and a 3.5mm socket adapter to the back of the sound card. Worked swell. Now I need the th
-
Dummy Product & Dummy Logical component???
Hello SolMan Gurus, Can anybody throw some light on how to create Dummy Product & Dummy Logical component? Your replies will be greately appreciated. best regds, Alagammai.
-
Error creating Master/Detail Form
Hi, I tried to create a master detail form. I went through all the steps fine, only when i click the button to create the form, i received the following errors: ORA-20001: Unable to create master detail page. ORA-06502: PL/SQL: numeric or value error
-
PDF Distribution Limitations with new EULA?
We have created Interactive PDFs for our customers to use and distribute among their teams. No data from these PDFs are coming back to us. Is someone on this forum able to verify that we are not violating the new EULA 500 limit? After being on hold f