Starting rework of client request protocol to allow multiplayer

This commit is contained in:
2021-03-20 23:31:33 +01:00
parent 1b4bcd1ec2
commit 9195dbad22
4 changed files with 138 additions and 117 deletions

View File

@@ -9,27 +9,28 @@ public class TicTacToe_Client {
private Engine renderEngine;
private Client client;
private boolean isSingleServer;
private static String clientName;
private boolean isPlayerOne;
public TicTacToe_Client() {
renderEngine = Engine.waitForEngine();
client = new Client("server", 2589, clientName);
client.handshake();
isPlayerOne = client.isPlayerOne();
this.setWindowTitle(isPlayerOne);
client.sendToServer("ready");
}
private void ticTacToe_gameloop() {
//Setup
client = new Client("server", 2589, clientName);
client.handshake();
isSingleServer = client.getServerType();
if (isSingleServer){
this.setWindowTitle(client.isPlayerOne());
client.sendToServer("ready");
this.drawBoard(client.getGameState());
if (isPlayerOne){
this.userInput();
}
while (client.isConnected() && !renderEngine.isWindowClosed()) {
String message = client.getResponse();
//Check if message is gamestate
if (message.charAt(0) == 'x' || message.charAt(0) == '-' || message.charAt(0) == 'o') {
this.drawBoard(message);
this.gameFlow("userInput");
}
//Handle everything else
else {
@@ -41,9 +42,6 @@ public class TicTacToe_Client {
} catch (Exception e) {
e.printStackTrace();
}
} else {
this.setWindowTitle(client.isPlayerOne());
}
}
private void gameFlow(String input) {
@@ -59,26 +57,20 @@ public class TicTacToe_Client {
renderEngine.setMouseClicked(false);
this.userInput();
break;
case "invalidInput":
this.onInvalidInput();
break;
case ""
}
}
private void requestOpponentMove(){
client.sendToServer("opponentMove");
}
private void userInput(){
//Send command
client.sendToServer("clientMove");
//Send position
client.sendToServer(String.format("%f|%f", renderEngine.getCoordinates().getX(), renderEngine.getCoordinates().getY()));
//Get gameState
String gameState = client.getResponse();
if (gameState.length() == 9) {
this.drawBoard(gameState);
//Send command
if (!client.getGameEnded()) {
client.sendToServer("computerMove");
this.drawBoard(client.getResponse());
} else {
private void onGameEnd(){
LinkedList<Integer> winCoordinates = new LinkedList<>();
//Get winning fields
String response = client.getResponse();
@@ -94,6 +86,27 @@ public class TicTacToe_Client {
}
client.resetBoard();
}
private void onInvalidInput(){
int column = (int) renderEngine.getCoordinates().getX() / 300;
int row = (int) renderEngine.getCoordinates().getY() / 300;
System.err.printf("You are not allowed to place at %d|%d%n", column, row);
this.userInput();
}
private void userInput() {
client.sendToServer("clientMove");
client.sendToServer(String.format("%f|%f", renderEngine.getCoordinates().getX(), renderEngine.getCoordinates().getY()));
//Get gameState
String gameState = client.getResponse();
if (gameState.length() == 9) {
this.drawBoard(gameState);
//Send command
if (!client.getGameEnded()) {
this.requestOpponentMove();
} else {
this.onGameEnd();
}
} else {
int column = (int) renderEngine.getCoordinates().getX() / 300;
int row = (int) renderEngine.getCoordinates().getY() / 300;

View File

@@ -92,6 +92,16 @@ public class Client {
return isClientOne;
}
public String getGameState(){
try {
out.writeUTF("gameState");
return this.getResponse();
} catch (IOException e) {
e.printStackTrace();
}
return "---------";
}
public boolean getServerType(){
this.sendToServer("serverType");
boolean serverType = this.getBooleanResponse("isSingleServer");

View File

@@ -11,13 +11,12 @@ import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class TicTacToe_Server {
private ServerSocket serverSocket;
private HashMap<Integer, Socket> clients;
private HashMap<Socket, Integer> clientIds;
private HashMap<Socket, String> clientNames;
private HashMap<Socket, Boolean> clientMoveAuthorizations;
private HashMap<Socket, DataOutputStream> outstreams;
@@ -25,6 +24,7 @@ public class TicTacToe_Server {
private TicTacToe_GameRules ticTacToe_gameRules;
private ServerLogger serverLogger;
private int requiredConnections;
private boolean[] clientsReady;
public TicTacToe_Server(int port, int requiredConnections) {
@@ -32,12 +32,14 @@ public class TicTacToe_Server {
serverSocket = new ServerSocket(port);
clients = new HashMap<>();
clientNames = new HashMap<>();
clientIds = new HashMap<>();
clientMoveAuthorizations = new HashMap<>();
outstreams = new HashMap<>();
instreams = new HashMap<>();
ticTacToe_gameRules = new TicTacToe_GameRules();
serverLogger = new ServerLogger();
this.requiredConnections = requiredConnections;
clientsReady = new boolean[requiredConnections];
serverLogger.printLog("Server started successfully", LogType.Log);
} catch (IOException e) {
@@ -46,6 +48,7 @@ public class TicTacToe_Server {
}
private boolean isSingleServer() {
serverLogger.printLog(""+ requiredConnections + (requiredConnections == 1), LogType.Error);
return requiredConnections == 1;
}
@@ -56,6 +59,7 @@ public class TicTacToe_Server {
while (clients.size() < requiredConnections) {
Socket momentaryClient = serverSocket.accept();
clients.put(id, momentaryClient);
clientIds.put(clients.get(id), id);
outstreams.put(momentaryClient, new DataOutputStream(momentaryClient.getOutputStream()));
instreams.put(momentaryClient, new DataInputStream(momentaryClient.getInputStream()));
id++;
@@ -117,21 +121,11 @@ public class TicTacToe_Server {
}
public void ticTacToe_gameloop() {
if (isSingleServer()) {
Socket client = clients.get(0);
//SingleServer GameLoop
while (!client.isClosed()) {
//Get instruction
this.gameFlow(handleInput(client), client);
}
} else {
//MultiServer GameLoop
gameFlow("gameState");
while (clients.size() == requiredConnections) {
for (Socket client : clients.values()) {
gameFlow(handleInput(client), client);
}
}
public void gameFlow(String input){
this.gameFlow(input, null);
}
public void gameFlow(String input, Socket client) {
@@ -142,6 +136,7 @@ public class TicTacToe_Server {
} else {
sendGameState(client);
}
clientsReady[clientIds.get(client)] = true;
break;
case "gameState":
@@ -152,14 +147,12 @@ public class TicTacToe_Server {
try {
//Get position (X|Y)
String position = handleInput(client);
boolean moveAllowed = ticTacToe_gameRules.makeClientMove(position);
boolean moveAllowed = ticTacToe_gameRules.makeClientMove(position, clientIds.get(client));
if (moveAllowed) {
sendGameState();
} else {
//send " "
outstreams.get(client).writeUTF("userInput");
outstreams.get(client).writeUTF("invalidInput");
outstreams.get(client).flush();
serverLogger.printLog("Requested userInput", LogType.Log);
serverLogger.printLog(String.format("Move is not allowed!"), clientNames.get(client), LogType.Error);
}
} catch (IOException e) {
@@ -167,9 +160,22 @@ public class TicTacToe_Server {
}
break;
case "computerMove":
case "opponentMove":
if (isSingleServer()) {
ticTacToe_gameRules.makeComputerMove();
serverLogger.printLog("Made computer move", LogType.Log);
} else {
//request move from other player
try {
outstreams.get(1-clientIds.get(client)).writeUTF("userInput");
outstreams.get(client).flush();
serverLogger.printLog("Requested opponent userInput", clientNames.get(1-clientIds.get(client)), LogType.Log);
} catch (IOException e) {
e.printStackTrace();
}
}
sendGameState();
if (isSingleServer()) {
try {
outstreams.get(client).writeUTF("userInput");
outstreams.get(client).flush();
@@ -177,11 +183,12 @@ public class TicTacToe_Server {
} catch (IOException e) {
e.printStackTrace();
}
}
break;
case "serverType":
try {
outstreams.get(client).writeBoolean(true);
outstreams.get(client).writeBoolean(isSingleServer());
outstreams.get(client).flush();
serverLogger.printLog("Sent serverType", Boolean.toString(true), clientNames.get(client), LogType.Log);
} catch (IOException e) {
@@ -190,20 +197,12 @@ public class TicTacToe_Server {
break;
case "isClientOne":
for (Map.Entry<Integer, Socket> entry : clients.entrySet()) {
if (Objects.equals(client, entry.getValue())) {
boolean isClientOne = clientIds.get(client) == 0;
try {
boolean isClientOne = entry.getKey() == 0;
outstreams.get(client).writeBoolean(isClientOne);
outstreams.get(client).flush();
serverLogger.printLog("Sent isPlayerOne", Boolean.toString(isClientOne), clientNames.get(client), LogType.Log);
} catch (IOException e) {
e.printStackTrace();
}
} else {
serverLogger.printLog("Current client not in clients!", LogType.Error);
}
}
break;
case "gameEnded":

View File

@@ -12,7 +12,7 @@ public class TicTacToe_GameRules {
Point startWin, endWin;
public TicTacToe_GameRules(){
gameState = "---------";
gameState = "o--x-o--x";
}
public void resetGameState() {
@@ -34,13 +34,13 @@ public class TicTacToe_GameRules {
board = this.convertToNumbers(gameState);
}
public boolean makeClientMove(String input) {
public boolean makeClientMove(String input, int id) {
int column = Double.valueOf(input.split("\\|")[0]).intValue() / 300;
int row = Double.valueOf(input.split("\\|")[1]).intValue() / 300;
int index = column * 3 + row;
if (isLegalMove(column, row)) {
makeMoveOnBoard(index, 0);
makeMoveOnBoard(index, id);
return true;
} else {
return false;
@@ -144,7 +144,6 @@ public class TicTacToe_GameRules {
return horizontalWin() || verticalWin() || diagonalWin();
}
public Point[] getWinCoordinates(){
return new Point[]{startWin, endWin};
}