@JC, I just wrote this code really quick and it does compile without errors for the server side ... but I am not sure about 1 thing .. here is the code first
import java.net.*;
import java.io.*;
public class GameServer extends Thread{
private ServerSocket serverSocket;
private enum Action { Scissors, Rock, Paper;
public int checkActions(Action action){
int win = 1;
int lose = -1;
int draw = 0;
if (this == action) return draw;
switch (this){
case Scissors:
if(action == Paper) return win;
else return lose;
case Rock:
if(action == Scissors) return win;
else return lose;
case Paper:
if(action == Rock) return win;
else return lose;
}
return 69; // Default return, will never reach it
}
}
private String inputFromUser1,inputFromUser2;
public GameServer(int port)throws IOException{
serverSocket = new ServerSocket(port);
}
public static void main(String[] args){
int port = 9001;
try{
Thread t = new GameServer(port);
t.start();
}catch(IOException e){
e.printStackTrace();
}
}
public void run(){
while(true){
try{
Socket server = serverSocket.accept();
PrintWriter out = new PrintWriter(server.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(server .getInputStream()));
inputFromUser1 = in.readLine();
inputFromUser2 = in.readLine();
out.println(play(getUser1Move(),getUser2Move()));
} catch(IOException e){
e.printStackTrace();
}
}
}
public String play(Action move1, Action move2) {
int result;
String output;
result = move1.checkActions(move2);
if(result==0)
return output = "User's move " + move1.toString() + "Computer move "
+ move2.toString() + ", the game is: DRAW";
else if(result==1)
return output = "User's move " + move1.toString() + "Computer move "
+ move2.toString() + ", You WIN!";
else
return output = "User's move " + move1.toString() + "Computer move "
+ move2.toString() + ", You LOSE!";
}
public Action getUser1Move(){
if(inputFromUser1.equals("Scissors")|| inputFromUser1.equals("Rock")|| inputFromUser1.equals("Paper")){
switch (inputFromUser1) {
case "Scissors":
return Action.Scissors;
case "Rock":
return Action.Rock;
case "Paper":
return Action.Paper;
}
}
return getUser1Move(); //Wrong spelled or w/e, get new input
}
public Action getUser2Move(){
if(inputFromUser2.equals("Scissors")|| inputFromUser2.equals("Rock")|| inputFromUser2.equals("Paper")){
switch (inputFromUser2) {
case "Scissors":
return Action.Scissors;
case "Rock":
return Action.Rock;
case "Paper":
return Action.Paper;
}
}
return getUser2Move(); //Wrong spelled or w/e, get new input
}
}
My doubts are about the input from users in run(), I did it this way because I think I can make it from client side so each client can send only 1 message per game, so the second input should be from second client? Does it make sense to be like this?