Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

JAVA: I would like to integrate my working Grid Class (GUI) into a client/server

ID: 3747921 • Letter: J

Question

JAVA: I would like to integrate my working Grid Class (GUI) into a client/server two player program, similiar to the attached tic tac toe program. Just so that both players can click the column buttons and populate the game. I am having issues impementing some of the code. Thanks!
***********Grid/GUI***********

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.layout.GridPane;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Shape;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.event.EventHandler;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
public class Grid extends Application {
private static final int TILE_SIZE = 80;
private static final int COLUMNS = 7;
private static int ROWS = 7;
private static Circle circles[][];
// instance for each 7 columns in array. starts at bottom
private static int row1 = 6;
private static int row2 = 6;
private static int row3 = 6;
private static int row4 = 6;
private static int row5 = 6;
private static int row6 = 6;
private static int row7 = 6;
// determines total number of possible moves
protected static int count = 42;
// instance to determine who's move it is
protected static int determinePlayer = 0;
//create array
private static char[][] objArray;
public static void main(String[] args) {
launch(args);
}
public Grid() {
objArray = new char[7][7];
} // end of constructor
/**
* Accessor for elements of object Connect 4
*
* @param row row value
* @param col column value
* @return element from objects row/column
*/
public char getElement(int row, int col) {
return objArray[row][col];
} // end of accessor getElement
/**
* Mutator that adds game pieces to Connect4 2D array
*
* @param row row value
* @param col column value
* @param value element to be added to object
*/
public void setElement(int row, int col, char value) {
objArray[row][col] = value;
} // end of mutator setElement
public void fillColumn(int col) {
for (int i = ROWS - 2; i >= 0; i--) {
Circle c = circles[i][col];
if ((Color) c.getFill() == Color.WHITE) {
if (determinePlayer % 2 == 0) {
c.setFill(Color.BLUE);
} else {
c.setFill(Color.RED);
}
return;
}
}
}
@Override
public void start(Stage primaryStage) {
Grid matrix = new Grid();
Button bt[] = new Button[COLUMNS];
for (int i = 0; i < bt.length; i++) {
bt[i] = new Button("Col " + (i + 1));
bt[i].setMaxSize(TILE_SIZE, TILE_SIZE);
bt[i].setShape(new Circle(1.5));
// set button position
bt[i].setTranslateX(TILE_SIZE / 4 + i * (TILE_SIZE + 5));
bt[i].setTranslateY(-260);
}
// Action Events
bt[0].setOnAction(new EventHandler<ActionEvent>() {
@Override // Override the handle method
public void handle(ActionEvent e) {
String label = ((Button) e.getSource()).getText();
System.out.println(label);
// column are from 1 to COLUMN, while index is from 0
// hence subtracting 1
fillColumn(Integer.parseInt(label.split(" ")[1]) - 1);
if (!columnSpace(1)) {
System.out.println("No more column Space");
} else {
matrix.add(1);
}
}
});
bt[1].setOnAction(new EventHandler<ActionEvent>() {
@Override // Override the handle method
public void handle(ActionEvent e) {
String label = ((Button) e.getSource()).getText();
System.out.println(label);
// column are from 1 to COLUMN, while index is from 0
// hence subtracting 1
fillColumn(Integer.parseInt(label.split(" ")[1]) - 1);
if (!columnSpace(2)) {
System.out.println("No more column Space");
} else {
matrix.add(2);
}
}
});
bt[2].setOnAction(new EventHandler<ActionEvent>() {
@Override // Override the handle method
public void handle(ActionEvent e) {
String label = ((Button) e.getSource()).getText();
System.out.println(label);
// column are from 1 to COLUMN, while index is from 0
// hence subtracting 1
fillColumn(Integer.parseInt(label.split(" ")[1]) - 1);
if (!columnSpace(3)) {
System.out.println("No more column Space");
} else {
matrix.add(3);
}
}
});
bt[3].setOnAction(new EventHandler<ActionEvent>() {
@Override // Override the handle method
public void handle(ActionEvent e) {
String label = ((Button) e.getSource()).getText();
System.out.println(label);
// column are from 1 to COLUMN, while index is from 0
// hence subtracting 1
fillColumn(Integer.parseInt(label.split(" ")[1]) - 1);
if (!columnSpace(4)) {
System.out.println("No more column Space");
} else {
matrix.add(4);
}
}
});
bt[4].setOnAction(new EventHandler<ActionEvent>() {
@Override // Override the handle method
public void handle(ActionEvent e) {
String label = ((Button) e.getSource()).getText();
System.out.println(label);
// column are from 1 to COLUMN, while index is from 0
// hence subtracting 1
fillColumn(Integer.parseInt(label.split(" ")[1]) - 1);
if (!columnSpace(5)) {
System.out.println("No more column Space");
} else {
matrix.add(5);
}
}
});
bt[5].setOnAction(new EventHandler<ActionEvent>() {
@Override // Override the handle method
public void handle(ActionEvent e) {
String label = ((Button) e.getSource()).getText();
System.out.println(label);
// column are from 1 to COLUMN, while index is from 0
// hence subtracting 1
fillColumn(Integer.parseInt(label.split(" ")[1]) - 1);
if (!columnSpace(6)) {
System.out.println("No more column Space");
} else {
matrix.add(6);
}
}
});
bt[6].setOnAction(new EventHandler<ActionEvent>() {
@Override // Override the handle method
public void handle(ActionEvent e) {
String label = ((Button) e.getSource()).getText();
System.out.println(label);
// column are from 1 to COLUMN, while index is from 0
// hence subtracting 1
fillColumn(Integer.parseInt(label.split(" ")[1]) - 1);
if (!columnSpace(7)) {
System.out.println("No more column Space");
} else {
matrix.add(7);
}
}
});
// Create rectangle grid
Shape shape = new Rectangle((COLUMNS + 1) * TILE_SIZE, (ROWS + 1) * TILE_SIZE);
// create GridPane
GridPane pane = new GridPane();
pane.setAlignment(Pos.CENTER);
pane.setPadding(new Insets(11.5, 12.5, 13.5, 14.5)); // pixel buffer layout
pane.setHgap(5.5); // pixel per blocks
pane.setVgap(5.5);
// add everything to gridpane
pane.getChildren().addAll(shape);
pane.getChildren().addAll(bt);
circles = new Circle[ROWS - 1][COLUMNS];
for (int i = 0; i < ROWS - 1; i++) {
for (int i2 = 0; i2 < COLUMNS; i2++) {
Circle circle = new Circle(TILE_SIZE / 2);
circle.setCenterX(TILE_SIZE / 2);
circle.setCenterY(TILE_SIZE / 2);
circle.setTranslateX(i2 * (TILE_SIZE + 5) + TILE_SIZE / 4);
circle.setTranslateY(-20 + (i - 2) * (TILE_SIZE + 5) + TILE_SIZE / 4);
circle.setFill(Color.WHITE);
pane.getChildren().add(circle);
circles[i][i2] = circle;
}
}
Scene scene = new Scene(pane);
primaryStage.setTitle("GridPane"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
}
public void add(int x) {
switch (x) {
case 1:
if (determinePlayer % 2 == 0) {
setElement(row1, 0, 'X');
} else {
setElement(row1, 0, 'O');
}
row1--;
count--;
determinePlayer++;
break;
case 2:
if (determinePlayer % 2 == 0) {
setElement(row2, 1, 'X');
} else {
setElement(row2, 1, 'O');
}
row2--;
count--;
determinePlayer++;
break;
case 3:
if (determinePlayer % 2 == 0) {
setElement(row3, 2, 'X');
} else {
setElement(row3, 2, 'O');
}
row3--;
count--;
determinePlayer++;
break;
case 4:
if (determinePlayer % 2 == 0) {
setElement(row4, 3, 'X');
} else {
setElement(row4, 3, 'O');
}
row4--;
count--;
determinePlayer++;
break;
case 5:
if (determinePlayer % 2 == 0) {
setElement(row5, 4, 'X');
} else {
setElement(row5, 4, 'O');
}
row5--;
count--;
determinePlayer++;
break;
case 6:
if (determinePlayer % 2 == 0) {
setElement(row6, 5, 'X');
} else {
setElement(row6, 5, 'O');
}
row6--;
count--;
determinePlayer++;
break;
case 7:
if (determinePlayer % 2 == 0) {
setElement(row7, 6, 'X');
} else {
setElement(row7, 6, 'O');
}
row7--;
count--;
determinePlayer++;
break;
} // end of switch
} // end of
public static boolean columnSpace(int choice) {
if (choice == 1 && row1 < 1) {
return false;
} else if (choice == 2 && row2 < 1) {
return false;
} else if (choice == 3 && row3 < 1) {
return false;
} else if (choice == 4 && row4 < 1) {
return false;
} else if (choice == 5 && row5 < 1) {
return false;
} else if (choice == 6 && row6 < 1) {
return false;
} else if (choice == 7 && row7 < 1) {
return false;
} else {
return true;
} // if not false then true there is spcae
}
}
*****************interface tictactow*************
public interface TicTacToeConstants {
public static int PLAYER1 = 1; // Indicate player 1
public static int PLAYER2 = 2; // Indicate player 2
public static int PLAYER1_WON = 1; // Indicate player 1 won
public static int PLAYER2_WON = 2; // Indicate player 2 won
public static int DRAW = 3; // Indicate a draw
public static int CONTINUE = 4; // Indicate to continue
}
*************** server****************

import java.io.*;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.util.Date;
public class TicTacToeServer extends JFrame
implements TicTacToeConstants {
public static void main(String[] args) {
TicTacToeServer frame = new TicTacToeServer();
}
public TicTacToeServer() {
JTextArea jtaLog = new JTextArea();
// Create a scroll pane to hold text area
JScrollPane scrollPane = new JScrollPane(jtaLog);
// Add the scroll pane to the frame
add(scrollPane, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 300);
setTitle("TicTacToeServer");
setVisible(true);
try {
// Create a server socket
ServerSocket serverSocket = new ServerSocket(8000);
jtaLog.append(new Date()
+ ": Server started at socket 8000 ");
// Number a session
int sessionNo = 1;
// Ready to create a session for every two players
while (true) {
jtaLog.append(new Date()
+ ": Wait for players to join session " + sessionNo + ' ');
// Connect to player 1
Socket player1 = serverSocket.accept();
jtaLog.append(new Date() + ": Player 1 joined session "
+ sessionNo + ' ');
jtaLog.append("Player 1's IP address"
+ player1.getInetAddress().getHostAddress() + ' ');
// Notify that the player is Player 1
new DataOutputStream(
player1.getOutputStream()).writeInt(PLAYER1);
// Connect to player 2
Socket player2 = serverSocket.accept();
jtaLog.append(new Date()
+ ": Player 2 joined session " + sessionNo + ' ');
jtaLog.append("Player 2's IP address"
+ player2.getInetAddress().getHostAddress() + ' ');
// Notify that the player is Player 2
new DataOutputStream(
player2.getOutputStream()).writeInt(PLAYER2);
// Display this session and increment session number
jtaLog.append(new Date() + ": Start a thread for session "
+ sessionNo++ + ' ');
// Create a new thread for this session of two players
HandleASession task = new HandleASession(player1, player2);
// Start the new thread
new Thread(task).start();
}
} catch (IOException ex) {
System.err.println(ex);
}
}
}
// Define the thread class for handling a new session for two players
class HandleASession implements Runnable, TicTacToeConstants {
private Socket player1;
private Socket player2;
// Create and initialize cells
private char[][] cell = new char[3][3];
private DataInputStream fromPlayer1;
private DataOutputStream toPlayer1;
private DataInputStream fromPlayer2;
private DataOutputStream toPlayer2;
// Continue to play
private boolean continueToPlay = true;
/**
* Construct a thread
*/
public HandleASession(Socket player1, Socket player2) {
this.player1 = player1;
this.player2 = player2;
// Initialize cells
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cell[i][j] = ' ';
}
}
}
/**
* Implement the run() method for the thread
*/
@Override
public void run() {
try {
// Create data input and output streams
DataInputStream fromPlayer1 = new DataInputStream(
player1.getInputStream());
DataOutputStream toPlayer1 = new DataOutputStream(
player1.getOutputStream());
DataInputStream fromPlayer2 = new DataInputStream(
player2.getInputStream());
DataOutputStream toPlayer2 = new DataOutputStream(
player2.getOutputStream());
// Write anything to notify player 1 to start
// This is just to let player 1 know to start
toPlayer1.writeInt(1);
// Continuously serve the players and determine and report
// the game status to the players
while (true) {
// Receive a move from player 1
int row = fromPlayer1.readInt();
int column = fromPlayer1.readInt();
cell[row][column] = 'X';
// Check if Player 1 wins
if (isWon('X')) {
toPlayer1.writeInt(PLAYER1_WON);
toPlayer2.writeInt(PLAYER1_WON);
sendMove(toPlayer2, row, column);
break; // Break the loop
} else if (isFull()) { // Check if all cells are filled
toPlayer1.writeInt(DRAW);
toPlayer2.writeInt(DRAW);
sendMove(toPlayer2, row, column);
break;
} else {
// Notify player 2 to take the turn
toPlayer2.writeInt(CONTINUE);
// Send player 1's selected row and column to player 2
sendMove(toPlayer2, row, column);
}
// Receive a move from Player 2
row = fromPlayer2.readInt();
column = fromPlayer2.readInt();
cell[row][column] = 'O';
// Check if Player 2 wins
if (isWon('O')) {
toPlayer1.writeInt(PLAYER2_WON);
toPlayer2.writeInt(PLAYER2_WON);
sendMove(toPlayer1, row, column);
break;
} else {
// Notify player 1 to take the turn
toPlayer1.writeInt(CONTINUE);
// Send player 2's selected row and column to player 1
sendMove(toPlayer1, row, column);
}
}
} catch (IOException ex) {
System.err.println(ex);
}
}
/**
* Send the move to other player
*/
private void sendMove(DataOutputStream out, int row, int column)
throws IOException {
out.writeInt(row); // Send row index
out.writeInt(column); // Send column index
}
/**
* Determine if the cells are all occupied
*/
private boolean isFull() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (cell[i][j] == ' ') {
return false; // At least one cell is not filled
}
}
}
// All cells are filled
return true;
}
/**
* Determine if the player with the specified token wins
*/
private boolean isWon(char token) {
// Check all rows
for (int i = 0; i < 3; i++) {
if ((cell[i][0] == token)
&& (cell[i][1] == token)
&& (cell[i][2] == token)) {
return true;
}
}
/**
* Check all columns
*/
for (int j = 0; j < 3; j++) {
if ((cell[0][j] == token)
&& (cell[1][j] == token)
&& (cell[2][j] == token)) {
return true;
}
}
/**
* Check major diagonal
*/
if ((cell[0][0] == token)
&& (cell[1][1] == token)
&& (cell[2][2] == token)) {
return true;
}
/**
* Check subdiagonal
*/
if ((cell[0][2] == token)
&& (cell[1][1] == token)
&& (cell[2][0] == token)) {
return true;
}
/**
* All checked, but no winner
*/
return false;
}
}
***************client***************
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.LineBorder;
import java.io.*;
import java.net.*;
public class TicTacToeClient extends JApplet
implements Runnable, TicTacToeConstants {
// Indicate whether the player has the turn
private boolean myTurn = false;
// Indicate the token for the player
private char myToken = ' ';
// Indicate the token for the other player
private char otherToken = ' ';
// Create and initialize cells
private Cell[][] cell = new Cell[3][3];
// Create and initialize a title label
private JLabel jlblTitle = new JLabel();
// Create and initialize a status label
private JLabel jlblStatus = new JLabel();
// Indicate selected row and column by the current move
private int rowSelected;
private int columnSelected;
// Input and output streams from/to server
private DataInputStream fromServer;
private DataOutputStream toServer;
// Continue to play?
private boolean continueToPlay = true;
// Wait for the player to mark a cell
private boolean waiting = true;
// Indicate if it runs as application
private boolean isStandAlone = false;
// Host name or ip
private String host = "localhost";
/**
* Initialize UI
*/
@Override
public void init() {
// Panel p to hold cells
JPanel p = new JPanel();
p.setLayout(new GridLayout(3, 3, 0, 0));
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
p.add(cell[i][j] = new Cell(i, j));
}
}
// Set properties for labels and borders for labels and panel
p.setBorder(new LineBorder(Color.black, 1));
jlblTitle.setHorizontalAlignment(JLabel.CENTER);
jlblTitle.setFont(new Font("SansSerif", Font.BOLD, 16));
jlblTitle.setBorder(new LineBorder(Color.black, 1));
jlblStatus.setBorder(new LineBorder(Color.black, 1));
// Place the panel and the labels to the applet
add(jlblTitle, BorderLayout.NORTH);
add(p, BorderLayout.CENTER);
add(jlblStatus, BorderLayout.SOUTH);
// Connect to the server
connectToServer();
}
private void connectToServer() {
try {
// Create a socket to connect to the server
Socket socket;
if (isStandAlone) {
socket = new Socket(host, 8000);
} else {
socket = new Socket(getCodeBase().getHost(), 8000);
}
// Create an input stream to receive data from the server
fromServer = new DataInputStream(socket.getInputStream());
// Create an output stream to send data to the server
toServer = new DataOutputStream(socket.getOutputStream());
} catch (Exception ex) {
System.err.println(ex);
}
// Control the game on a separate thread
Thread thread = new Thread(this);
thread.start();
}
@Override
public void run() {
try {
// Get notification from the server
int player = fromServer.readInt();
// Am I player 1 or 2?
if (player == PLAYER1) {
myToken = 'X';
otherToken = 'O';
jlblTitle.setText("Player 1 with token 'X'");
jlblStatus.setText("Waiting for player 2 to join");
// Receive startup notification from the server
fromServer.readInt(); // Whatever read is ignored
// The other player has joined
jlblStatus.setText("Player 2 has joined. I start first");
// It is my turn
myTurn = true;
} else if (player == PLAYER2) {
myToken = 'O';
otherToken = 'X';
jlblTitle.setText("Player 2 with token 'O'");
jlblStatus.setText("Waiting for player 1 to move");
}
// Continue to play
while (continueToPlay) {
if (player == PLAYER1) {
waitForPlayerAction(); // Wait for player 1 to move
sendMove(); // Send the move to the server
receiveInfoFromServer(); // Receive info from the server
} else if (player == PLAYER2) {
receiveInfoFromServer(); // Receive info from the server
waitForPlayerAction(); // Wait for player 2 to move
sendMove(); // Send player 2's move to the server
}
}
} catch (Exception ex) {
}
}
/**
* Wait for the player to mark a cell
*/
private void waitForPlayerAction() throws InterruptedException {
while (waiting) {
Thread.sleep(100);
}
waiting = true;
}
/**
* Send this player's move to the server
*/
private void sendMove() throws IOException {
toServer.writeInt(rowSelected); // Send the selected row
toServer.writeInt(columnSelected); // Send the selected column
}
/**
* Receive info from the server
*/
private void receiveInfoFromServer() throws IOException {
// Receive game status
int status = fromServer.readInt();
if (status == PLAYER1_WON) {
// Player 1 won, stop playing
continueToPlay = false;
if (myToken == 'X') {
jlblStatus.setText("I won! (X)");
} else if (myToken == 'O') {
jlblStatus.setText("Player 1 (X) has won!");
receiveMove();
}
} else if (status == PLAYER2_WON) {
// Player 2 won, stop playing
continueToPlay = false;
if (myToken == 'O') {
jlblStatus.setText("I won! (O)");
} else if (myToken == 'X') {
jlblStatus.setText("Player 2 (O) has won!");
receiveMove();
}
} else if (status == DRAW) {
// No winner, game is over
continueToPlay = false;
jlblStatus.setText("Game is over, no winner!");
if (myToken == 'O') {
receiveMove();
}
} else {
receiveMove();
jlblStatus.setText("My turn");
myTurn = true; // It is my turn
}
}
private void receiveMove() throws IOException {
// Get the other player's move
int row = fromServer.readInt();
int column = fromServer.readInt();
cell[row][column].setToken(otherToken);
}
// An inner class for a cell
public class Cell extends JPanel {
// Indicate the row and column of this cell in the board
private int row;
private int column;
// Token used for this cell
private char token = ' ';
public Cell(int row, int column) {
this.row = row;
this.column = column;
setBorder(new LineBorder(Color.black, 1)); // Set cell's border
addMouseListener(new ClickListener()); // Register listener
}
/**
* Return token
*/
public char getToken() {
return token;
}
/**
* Set a new token
*/
public void setToken(char c) {
token = c;
repaint();
}
@Override
/**
* Paint the cell
*/
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (token == 'X') {
g.drawLine(10, 10, getWidth() - 10, getHeight() - 10);
g.drawLine(getWidth() - 10, 10, 10, getHeight() - 10);
} else if (token == 'O') {
g.drawOval(10, 10, getWidth() - 20, getHeight() - 20);
}
}
/**
* Handle mouse click on a cell
*/
private class ClickListener extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent e) {
// If cell is not occupied and the player has the turn
if ((token == ' ') && myTurn) {
setToken(myToken); // Set the player's token in the cell
myTurn = false;
rowSelected = row;
columnSelected = column;
jlblStatus.setText("Waiting for the other player to move");
waiting = false; // Just completed a successful move
}
}
}
}
/**
* This main method enables the applet to run as an application
*/
public static void main(String[] args) {
// Create a frame
JFrame frame = new JFrame("Tic Tac Toe Client");
// Create an instance of the applet
TicTacToeClient applet = new TicTacToeClient();
applet.isStandAlone = true;
// Get host
if (args.length == 1) {
applet.host = args[0];
}
// Add the applet instance to the frame
frame.getContentPane().add(applet, BorderLayout.CENTER);
// Invoke init() and start()
applet.init();
applet.start();
// Display the frame
frame.setSize(320, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

Explanation / Answer

Cliente.java (Client)

public class Cliente extends JFrame implements ActionListener,Runnable

{

...   

private JPanel boardPanel, panel2;

private JButton[] gameBtn = new JButton[16];

private JPanel gamePnl = new JPanel();

...

public void start2()

{

try

{

connection = new Socket(InetAddress.getByName("localhost"), 5000 );

output = new ObjectOutputStream(connection.getOutputStream());

input = new ObjectInputStream(connection.getInputStream());

inputThread = new Thread( this );

inputThread.start();

MsgIdt msg = new MsgIdt();

msg.envia(output);

System.out.println(msg);

}

catch (Exception e)

{

e.printStackTrace();

}

}

...

public void createGUI()

{

for (int i = 0; i < gameBtn.length; i++)

{

gameBtn[i] = new JButton(ButtonIcon);

gameBtn[i].addActionListener(this);

}

...

public void createJPanels()

{

gamePnl.setLayout(new GridLayout(4, 4));

TrataRato tr = new TrataRato();

for (int i = 0; i < gameBtn.length; i++)

{

gamePnl.add(gameBtn[i]);   

gameBtn[i].addMouseListener(tr);   

}  

...  

}

// You will need to fit this properly in your client class

public List<Integer> listReciever() throws IOException

{  

List<Integer> lista = new ArrayList<>();

int size = input.readInt();

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

{

lista.add(input.readInt());

}

return lista;

}

Servidor.java (Server)

public class Servidor extends JFrame

{

private ArrayList<Integer> gameList = new ArrayList<Integer>();

public Servidor ()

{

super( "Tic-Tac-Toe Server" );

Container cont = getContentPane();

board = new byte[9];

players = new Player[2];

currentPlayer = 0;

try

{

server = new ServerSocket(5000, 2 );

}

catch (IOException e)

{

e.printStackTrace();

System.exit( 1 );

}

output = new TextArea(10, 30);

output.setEditable(false);

JScrollPane sp = new JScrollPane(output);

cont.add( "Center", sp);

display("Tic-Tac-Toe Server running.");

addWindowListener(new ProcessaJanela());

setVisible(true);

pack();

}

public void execute()

{

for ( int i = 0 ; i < players.length; i++ )

{

try

{

players[i] = new Player( server.accept(), this, i );

players[i].start();

++numberOfPlayers;

}

catch ( IOException e)

{

e.printStackTrace();

System.exit( 1 );

}

}

setTurn();

}

public int getNumberOfPlayers()

{

return numberOfPlayers;

}

public int getCurrentPlayer()

{

return currentPlayer;

}

public int getWinner()

{

return winner;

}

public boolean getGameOver()

{

return gameOver;

}

public void setArrayListText() // generates random numbers

{

java.util.List<Integer> lista = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8);

Collections.shuffle(lista);

gameList.addAll(lista);

}   

public void gridclients() throws IOException

{

players[0].sendList(gameList);

players[1].sendList(gameList);

}

public void setTurn()

{

try

{   

players[currentPlayer].setTurn("OK");

players[(currentPlayer == 0 ? 1 : 0 )].setTurn("NOK");

}

catch (Exception e)

{

e.printStackTrace();

}

}

...

}

...

Player.java

public class Player extends Thread

{

private JButton[] gameBtn = new JButton[16];

Servidor control;

Socket connection;

ObjectInputStream input; //por no protocolo as msgs serem da classe Object

ObjectOutputStream output;

int number;

char mark;

public Player(Socket s, Servidor t, int num )

{

connection = s;

control = t;

number = num;

mark = ( num == 0 ? 'X' : 'O' );

try

{

input = new ObjectInputStream( connection.getInputStream() );

output = new ObjectOutputStream( connection.getOutputStream() );

}

catch (IOException e)

{

e.printStackTrace();

System.exit(1);

}

}  

public void run()

{

try

{

while( !control.getGameOver() )

{

processaMsg(Protocolo.recebe(input));

}

connection.close();

}

catch( Exception e )

{

e.printStackTrace();

System.exit(1);

}

}  

public void sendList(List<Integer> gameList) throws IOException

{

output.writeInt(gameList.size());

for(int i = 0; i < gameList.size(); i++)

{

output.writeInt(gameList.get(i));

}

}