Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 3 of 3

Thread: tictactoe client-server game

  1. #1
    Junior Member
    Join Date
    Dec 2011
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default tictactoe client-server game

    Hello. I have some problems with my java tictactoe client-server game. I can't figure it out and solve it not rewriting all program. So, my problem is that my tictactoe game doesn't end when one of the players wins game( get 3 X or O horizontal, vertical) and another problem is that i cant start new game. I would be very thankful if someone could help me out with this.
    Client Code:
    package tictactoeclient;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;
    import javax.swing.*;
     
    public class TicTacToeClient extends JApplet implements Runnable {
    private JTextField id;
    private JTextArea display;
    private JPanel boardPanel, panel2;
    private Square board[][], currentSquare;
    private Socket connection;
    private DataInputStream input;
    private DataOutputStream output;
    private Thread outputThread;
    private char myMark;
    private boolean myTurn;
     
    public void init()
    {
    display = new JTextArea( 4, 30 );
    display.setEditable( false );
    getContentPane().add( new JScrollPane( display ), BorderLayout.SOUTH );
    boardPanel = new JPanel();
    GridLayout layout = new GridLayout( 3, 3, 0, 0 );
    boardPanel.setLayout( layout );
    board = new Square[ 3 ][ 3 ];
     
    for ( int row = 0; row < board.length; row++ )
    {
    for ( int col = 0;col < board[ row ].length; col++ ) {
    board[ row ][ col ] =new Square( ' ', row * 3 + col );
    board[ row ][ col ].addMouseListener(new SquareListener(this, board[ row ][ col ] ) );
    boardPanel.add( board[ row ][ col ] );
    }
    }
    id = new JTextField();
    id.setEditable( false );
    getContentPane().add( id, BorderLayout.NORTH );
    panel2 = new JPanel();
    panel2.add( boardPanel, BorderLayout.CENTER );
    getContentPane().add( panel2, BorderLayout.CENTER );
    }
     
    public void start()
    {
    try {
    connection = new Socket(InetAddress.getByName( "127.0.0.1" ), 5000 );
    input = new DataInputStream(connection.getInputStream() );
    output = new DataOutputStream(connection.getOutputStream() );
    }
    catch ( IOException e ) {
    e.printStackTrace();
    }
    outputThread = new Thread( this );
    outputThread.start();
    }
    public void run()
    {
    try {
    myMark = input.readChar();
    id.setText( "You are player \"" + myMark + "\"" );
    myTurn = ( myMark == 'X' ? true : false );
    }
    catch ( IOException e ) {
    e.printStackTrace();
    }
     
    while ( true ) {
    try {
    String s = input.readUTF();
    processMessage( s );
    }
    catch ( IOException e ) {
    e.printStackTrace();
    }
    }
    }
     
    public void processMessage( String s )
    {
    if ( s.equals( "Valid move." ) ) {
    display.append( "Valid move, please wait.\n" );
    currentSquare.setMark( myMark );
    currentSquare.repaint();
    }
    else if ( s.equals( "Invalid move, try again" ) ) {
    display.append( s + "\n" );
    myTurn = true;
    }
    else if ( s.equals( "Opponent moved" ) ) {
    try {
    int loc = input.readInt();
    board[ loc / 3 ][ loc % 3 ].setMark(( myMark == 'X' ? 'O' : 'X' ) );
    board[ loc / 3 ][ loc % 3 ].repaint();
    display.append("Opponent moved. Your turn.\n" );
    myTurn = true;
    }
    catch ( IOException e ) {
    e.printStackTrace();
    }
    }
    else
    display.append( s + "\n" );
    display.setCaretPosition(display.getText().length() );
    }
    public void sendClickedSquare( int loc )
    {
    if ( myTurn )
    try {
    output.writeInt( loc );
    myTurn = false;
    }
    catch ( IOException ie ) {
    ie.printStackTrace();
    }
    }
    public void setCurrentSquare( Square s )
    {
    currentSquare = s;
    }
    }
    // Maintains one square on the board
    class Square extends JPanel {
    private char mark;
    private int location;
    public Square( char m, int loc)
    {
    mark = m;
    location = loc;
    setSize ( 30, 30 );
    setVisible(true);
    }
    public Dimension getPreferredSize() {
    return ( new Dimension( 30, 30 ) );
    }
    public Dimension getMinimumSize() {
    return ( getPreferredSize() );
    }
    public void setMark( char c ) { mark = c; }
    public int getSquareLocation() { return location; }
    public void paintComponent( Graphics g )
    {
    super.paintComponent( g );
    g.drawRect( 0, 0, 29, 29 );
    g.drawString( String.valueOf( mark ), 11, 20 );
    }
    }
    class SquareListener extends MouseAdapter {
    private TicTacToeClient applet;
    private Square square;
    public SquareListener( TicTacToeClient t, Square s )
    {
    applet = t;
    square = s;
    }
    public void mouseReleased( MouseEvent e )
    {
    applet.setCurrentSquare( square );
    applet.sendClickedSquare( square.getSquareLocation() );
    }
    }
    Server Code:
    package tictactoeserver;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;
    import javax.swing.*;
    public class TicTacToeServer extends JFrame {
    private byte board[];
    private boolean xMove;
    private JTextArea output;
    private Player players[];
    private ServerSocket server;
    private int currentPlayer;
    // private boolean available = false;
    // private static String theWinner = "";
    public TicTacToeServer()
    {
    super( "tic - tac - toe " );
    board = new byte[ 9 ];
    xMove = true;
    players = new Player[ 2 ];
    currentPlayer = 0;
    // set up ServerSocket
    try {
    server = new ServerSocket( 5000, 2 );
    }
    catch( IOException e ) {
    e.printStackTrace();
    System.exit( 1 );
    }
    output = new JTextArea();
    getContentPane().add( output, BorderLayout.CENTER );
    output.setText( "Server awaiting connections\n" );
    setSize( 300, 300 );
    show();
    }
    // wait for two connections so game can be played
    public void execute()
    {
    for ( int i = 0; i < players.length; i++ ) {
    try {
    players[ i ] =
    new Player( server.accept(), this, i );
    players[ i ].start();
    }
    catch( IOException e ) {
    e.printStackTrace();
    System.exit( 1 );
    }
    }
    // Player X is suspended until Player O connects.
    // Resume player X now.
    synchronized ( players[ 0 ] ) {
    players[ 0 ].threadSuspended = false;
    players[ 0 ].notify();
    }
    }
    public void display( String s )
    {
    output.append( s + "\n" );
    }
    // Determine if a move is valid.
    // This method is synchronized because only one move can be
    // made at a time.
    public synchronized boolean validMove( int loc,int player )
    {
    boolean moveDone = false;
    while ( player != currentPlayer ) {
    try {
    wait();
    }
    catch( InterruptedException e ) {
    e.printStackTrace();
    }
    }
    if ( !isOccupied( loc ) ) {
    board[ loc ] = (byte) ( currentPlayer == 0 ? 'X' : 'O' );
    currentPlayer = ( currentPlayer + 1 ) % 2;
    players[ currentPlayer ].otherPlayerMoved( loc );
    notify(); // tell waiting player to continue
    return true;
    }
    else
    return false;
    }
    public boolean isOccupied( int loc )
    {
    if ( board[ loc ] == 'X' || board [ loc ] == 'O' )
    return true;
    else
    return false;
    }
    public boolean gameOver()
    {
     
    // Place code here to test for a winner of the game
    return false;
    }
    public static void main( String args[] )
    {
    TicTacToeServer game = new TicTacToeServer();
    game.addWindowListener( new WindowAdapter() {
    public void windowClosing( WindowEvent e )
    {
    System.exit( 0 );
    }
    }
    );
    game.execute();
    }
    }
    // Player class to manage each Player as a thread
    class Player extends Thread {
    private Socket connection;
    private DataInputStream input;
    private DataOutputStream output;
    private TicTacToeServer control;
    private int number;
    private char mark;
    protected boolean threadSuspended = true;
    public Player( Socket s, TicTacToeServer t, int num )
    {
    mark = ( num == 0 ? 'X' : 'O' );
    connection = s;
    try {
    input = new DataInputStream(connection.getInputStream() );
    output = new DataOutputStream(connection.getOutputStream() );
    }
    catch( IOException e ) {
    e.printStackTrace();
    System.exit( 1 );
    }
    control = t;
    number = num;
    }
    public void otherPlayerMoved( int loc )
    {
    try {
    output.writeUTF( "Opponent moved" );
    output.writeInt( loc );
    }
    catch ( IOException e ) { e.printStackTrace(); }
    }
    public void run()
    {
    boolean done = false;
    try {
    control.display( "Player " + ( number == 0 ? 'X' : 'O' ) + " connected" );
    output.writeChar( mark );
    output.writeUTF( "Player " + ( number == 0 ? "X connected\n" : "O connected, please wait\n" ) );
    // wait for another player to arrive
    if ( mark == 'X' ) {
    output.writeUTF( "Waiting for another player" );
    try {
    synchronized( this ) {
    while ( threadSuspended )
    wait();
    }
    }
    catch ( InterruptedException e ) {
    e.printStackTrace();
    }
    output.writeUTF( "Other player connected. Your move." );
    }
    // Play game
    while ( !done ) {
    int location = input.readInt();
    if ( control.validMove( location, number ) ) {
    control.display( "loc: " + location );
    output.writeUTF( "Valid move." );
    }
    else
    output.writeUTF( "Invalid move, try again" );
    if ( control.gameOver() )
    done = true;
    }
    connection.close();
    }
    catch( IOException e ) {
    e.printStackTrace();
    System.exit( 1 );
    }
    }
    }


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: tictactoe client-server game

    Please edit your code and add proper indentation.
    The posted code is all to the left which makes it very hard to read the logic.

  3. #3
    Forum VIP
    Join Date
    Jun 2011
    Posts
    317
    My Mood
    Bored
    Thanks
    47
    Thanked 89 Times in 74 Posts
    Blog Entries
    4

    Default Re: tictactoe client-server game

    Put a break point in at this line in your server code.
    if ( control.gameOver() )
    done = true;
    }
    Does control.gameOver() behave as you expect? What happens when the loop ends? Looking at it I would expect it to exit the loop and quit the program so you will need another loop around that one to restart the game.

Similar Threads

  1. Bluetooth Client & Server
    By SarahVeni in forum What's Wrong With My Code?
    Replies: 3
    Last Post: September 5th, 2013, 03:47 AM
  2. simple ftp server and ftp client
    By simontkk2005 in forum Java Networking
    Replies: 4
    Last Post: January 26th, 2011, 10:29 AM
  3. [Java] Client - server, example
    By Grabar in forum Java Networking
    Replies: 6
    Last Post: January 22nd, 2011, 01:56 PM
  4. client/server socket
    By Java_dude_101 in forum File I/O & Other I/O Streams
    Replies: 2
    Last Post: January 18th, 2011, 01:16 AM
  5. Client/Server
    By Dillz in forum Paid Java Projects
    Replies: 2
    Last Post: June 2nd, 2010, 05:19 AM