Skip to content
Snippets Groups Projects
Commit be860a5f authored by Leonard Haddad's avatar Leonard Haddad :rocket:
Browse files

Merge branch 'network' into 'master'

Network

See merge request reswp-2020/galaxytrucker!71
parents 2dab176c d1e4fb2a
No related branches found
No related tags found
No related merge requests found
......@@ -10,15 +10,21 @@ import lombok.*;
@Setter
@Getter
@RequiredArgsConstructor(access = AccessLevel.PUBLIC)
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class ClientControllerCommunicator {
/** Singleton */
private static ClientControllerCommunicator singleton = null;
/**
* Client ship
*/
private Ship clientShip;
/**
* OverWorld
*/
private Overworld map;
private Planet currentPlanet;
/**
* Client class
......@@ -50,4 +56,14 @@ public class ClientControllerCommunicator {
}
return permittedLogin;
}
/** Constructor
* @param client - the client object, used to connect to server */
public static ClientControllerCommunicator getInstance(Client client){
if (singleton == null){
singleton = new ClientControllerCommunicator(client);
}
// TODO CREATE ALL CONTROLLERS HERE
return singleton;
}
}
package com.galaxytrucker.galaxytruckerreloaded.Controller;
import com.galaxytrucker.galaxytruckerreloaded.Communication.ClientControllerCommunicator;
import com.galaxytrucker.galaxytruckerreloaded.Model.Map.Planet;
import com.galaxytrucker.galaxytruckerreloaded.Model.Ship;
import com.galaxytrucker.galaxytruckerreloaded.Server.RequestObject;
import com.galaxytrucker.galaxytruckerreloaded.Server.RequestType;
import com.galaxytrucker.galaxytruckerreloaded.Server.ResponseObject;
import lombok.*;
import java.util.List;
@Getter
@Setter
@RequiredArgsConstructor(access = AccessLevel.PUBLIC)
public class TravelController extends Controller{
/**
* My own ship
*/
/** ClientControllerCommunicator */
@NonNull
private Ship myself;
private ClientControllerCommunicator clientControllerCommunicator;
/**
* travels from one location to another
* @param destination - the destination
*/
public void travel(Planet destination){
public boolean travel(Planet destination){
try {
RequestObject requestObject = new RequestObject();
requestObject.setRequestType(RequestType.HYPERJUMP);
requestObject.setShip(clientControllerCommunicator.getClientShip());
requestObject.setPlanet(destination);
ResponseObject object = clientControllerCommunicator.sendRequest(requestObject);
if (object.isValidRequest()){
Ship s = clientControllerCommunicator.getClientShip();
// Remove ship from planet
List<Ship> currentShips = s.getPlanet().getShips();
currentShips.remove(s);
s.getPlanet().setShips(currentShips);
// Set ship to target planet
s.setPlanet(destination);
// Set planet ship list
currentShips = destination.getShips();
currentShips.add(s);
destination.setShips(currentShips);
clientControllerCommunicator.setClientShip(s);
return true;
}
return false;
}
catch (Exception e){
e.printStackTrace();
return false;
}
}
}
......@@ -8,8 +8,9 @@ import lombok.Setter;
import java.io.*;
import java.net.Socket;
import java.util.UUID;
import java.util.*;
/** Handle each client in a separate thread */
public class ClientHandler implements Runnable {
/**
......@@ -59,7 +60,9 @@ public class ClientHandler implements Runnable {
@Setter
private boolean gameActive = true;
/** Map seed */
/**
* Map seed
*/
private int seed;
/**
......@@ -67,6 +70,23 @@ public class ClientHandler implements Runnable {
*/
private User user;
/**
* Planet name array
*/
private String[] names = {"MERCURY", "VENUS", "EARTH", "MARS", "JUPITER", "SATURN", "URANUS", "NEPTUN", "PLUTO", "AUGUSTUS",
"SIRIUS", "HOMESTREAD", "ALPHA CENTAURI", "GLIESE", "404 NOT FOUND", "KEPLER", "TOI", "USCO1621b","OGLE","WASP","WENDELSTEIN"
,"EPIC","ARION","DIMIDIUM","GALILEO","DAGON","SMETRIOS","THESTIAS","SAMH","SAFFAR","ARBER","MADRIU","AWASIS","DITSO"};
/**
* Planet name list
*/
private List<String> planetNames;
/**
* Used planet names list
*/
private List<String> usedPlanetNames = new ArrayList<>();
/**
* Constructor
*
......@@ -94,6 +114,7 @@ public class ClientHandler implements Runnable {
@Override
public void run() {
System.out.println("\n========== HANDLER RUNNING ==========\n");
planetNames.addAll(Arrays.asList(names));
// ==================== LOGIN ====================
try {
this.username = receive.readLine().replace("[LOGIN]:", "");
......@@ -106,6 +127,7 @@ public class ClientHandler implements Runnable {
this.user = serverServiceCommunicator.getUserService().getUser(username);
if (user.isFirstGame()) {
send.println("[NEW-GAME]");
// ==================== Overworld Creation ====================
Overworld overworld = new Overworld(UUID.randomUUID().hashCode(), UUID.randomUUID().hashCode(), username);
this.seed = overworld.getSeed();
//TODO PLANET CREATION, ADD TO OVERWORLD
......@@ -145,7 +167,6 @@ public class ClientHandler implements Runnable {
e.printStackTrace();
send.println("[EXCEPTION]:[NEW-GAME]:[USERNAME]:" + username);
}
// ==================== RUNNING ====================
while (gameActive) {
sendObject.writeObject(this.serverServiceCommunicator.getResponse((RequestObject) receiveObject.readObject()));
......@@ -153,7 +174,31 @@ public class ClientHandler implements Runnable {
}
} catch (Exception e) {
e.printStackTrace();
send.println("[EXCEPTION]:[LOGIN]:[USERNAME]:" + username);
// Socket will be closed thanks to exception, therefor cannot send more data
// Thread will terminate with socket exception
try {
send.println("[EXCEPTION]:[LOGIN]:[USERNAME]:" + username);
}
catch (Exception f){
f.printStackTrace();
}
}
}
/**
* Get a new planet name
*
* @param names - planet names
* @param usedNames - the already used planet names
* @param seed - the world seed
* @return an unused planet name
*/
private String getPlanetName(List<String> names, List<String> usedNames, int seed) {
Random random = new Random(seed);
String newName = names.get(random.nextInt(names.size()));
if (usedNames.contains(newName)) {
getPlanetName(names, usedNames, seed);
}
return newName;
}
}
......@@ -5,6 +5,7 @@ import com.galaxytrucker.galaxytruckerreloaded.Model.Map.Planet;
import com.galaxytrucker.galaxytruckerreloaded.Model.Map.Trader;
import com.galaxytrucker.galaxytruckerreloaded.Model.Ship;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import java.util.List;
......
......@@ -2,5 +2,5 @@ package com.galaxytrucker.galaxytruckerreloaded.Server;
/** Type of request sent to the server */
public enum RequestType {
LOGOUT
LOGOUT, HYPERJUMP
}
package com.galaxytrucker.galaxytruckerreloaded.Server;
import com.galaxytrucker.galaxytruckerreloaded.Model.Map.Overworld;
import com.galaxytrucker.galaxytruckerreloaded.Model.Map.Planet;
import com.galaxytrucker.galaxytruckerreloaded.Model.Ship;
import com.galaxytrucker.galaxytruckerreloaded.Model.User;
import com.galaxytrucker.galaxytruckerreloaded.Server.Exception.UserNotFoundException;
import com.galaxytrucker.galaxytruckerreloaded.Server.Services.TravelService;
import com.galaxytrucker.galaxytruckerreloaded.Server.Services.UserService;
import lombok.AccessLevel;
import lombok.Getter;
......@@ -20,13 +22,25 @@ public class ServerServiceCommunicator {
/** User service */
private UserService userService = new UserService();
/** TravelService */
private TravelService travelService = new TravelService();
/** Take a request from the client side, pass it through the services
* and return a response
* @return the server's response to the client's request */
public String getResponse(RequestObject request){
public ResponseObject getResponse(RequestObject request){
switch (request.getRequestType()){
case LOGOUT:
return logout(request.getShip().getAssociatedUser());
case HYPERJUMP:
return jump(request.getShip(),request.getPlanet());
//TODO OTHERS
}
return null;
}
// ==================================== USER SERVICE ====================================
/** Send the client his ship
* @param username - the client's username
* @return the client's ship */
......@@ -52,6 +66,9 @@ public class ServerServiceCommunicator {
catch (Exception e){
System.out.println("[NEW-USER]:[USERNAME]:"+username);
try {
if (username.isEmpty() || username.equals("[ENEMY]")){
return true;
}
userService.addUser(username);
return false;
}
......@@ -62,6 +79,52 @@ public class ServerServiceCommunicator {
}
}
/** Logout
* @param username - the client's username
* @return ResponseObject with either an accepted or aborted logout */
private ResponseObject logout(String username){
ResponseObject responseObject = new ResponseObject();
try {
User u = userService.getUser(username);
if (u.isLoggedIn()) {
if (!u.getUserShip().isInCombat()) {
u.setLoggedIn(false);
userService.updateUser(u);
responseObject.setValidRequest(true);
}
}
}
catch (Exception e){
e.printStackTrace();
responseObject.setValidRequest(false);
}
return responseObject;
}
// ==================================== TRAVEL SERVICE ====================================
/** Make a jump to a target planet
* @param s - the client ship
* @param p - the target planet
* @return a ResponseObject */
private ResponseObject jump(Ship s, Planet p){
ResponseObject responseObject = new ResponseObject();
try {
if (travelService.validateJump(s, p,userService.getUser(s.getAssociatedUser()))) {
boolean successfulJump = travelService.jump(s, p);
if (successfulJump) {
responseObject.setValidRequest(true);
}
}
}
catch (Exception e){
e.printStackTrace();
}
return responseObject;
}
// ========================================================================================
/** Get instance */
public static ServerServiceCommunicator getInstance(){
if (serverServiceCommunicator == null){
......
......@@ -2,33 +2,100 @@ package com.galaxytrucker.galaxytruckerreloaded.Server.Services;
import com.galaxytrucker.galaxytruckerreloaded.Model.Map.Planet;
import com.galaxytrucker.galaxytruckerreloaded.Model.Ship;
import com.galaxytrucker.galaxytruckerreloaded.Model.User;
import com.galaxytrucker.galaxytruckerreloaded.Server.Persistence.PlanetDAO;
import com.galaxytrucker.galaxytruckerreloaded.Server.Persistence.ShipDAO;
import lombok.*;
/** Used to move user from one star to another */
@RequiredArgsConstructor(access = AccessLevel.PUBLIC)
import java.util.List;
/**
* Used to move user from one star to another
*/
@NoArgsConstructor(access = AccessLevel.PUBLIC)
@Getter
@Setter
public class TravelService {
/** ShipDAO */
@NonNull
private ShipDAO shipDAO;
/**
* ShipDAO
*/
private ShipDAO shipDAO = new ShipDAO();
/** PlanetDAO */
@NonNull
private PlanetDAO planetDAO;
/**
* PlanetDAO
*/
private PlanetDAO planetDAO = new PlanetDAO();
/** Validate the travel request
* @param s - the ship that wisches to travel
* @return true if the travel request is valid */
public boolean validateJump(Ship s){
return false;
/**
* Validate the travel request
*
* @param s - the ship that wishes to travel
* @param p - the destination planet
* @return true if the travel request is valid
*/
public boolean validateJump(Ship s, Planet p, User u) {
try {
if (u.getOverworld().getPlanetMap().containsValue(p)) {
return !s.getPlanet().equals(p) && s.getFTLCharge() == 100;
}
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/** Jump ship from one star to another
* @param s - the ship to jump
* @param dest - the destination star */
public void jump(Ship s, Planet dest){}
/**
* Jump ship from one star to another
*
* @param s - the ship to jump
* @param dest - the destination star
*/
public boolean jump(Ship s, Planet dest) {
try {
Planet current = s.getPlanet();
try {
// Remove ship from current planet
List<Ship> ships = current.getShips();
ships.remove(s);
current.setShips(ships);
planetDAO.update(current);
// Set ship to target planet
s.setPlanet(dest);
shipDAO.update(s);
// Update target planet
ships = dest.getShips();
ships.add(s);
dest.setShips(ships);
planetDAO.update(dest);
return true;
} catch (Exception e) {
e.printStackTrace();
// Revert charnges
try {
// Revert current planet
List<Ship> ships = current.getShips();
ships.add(s);
current.setShips(ships);
planetDAO.update(current);
// Revert ship
s.setPlanet(current);
shipDAO.update(s);
// Revert target planet
ships = dest.getShips();
ships.remove(s);
dest.setShips(ships);
planetDAO.update(dest);
} catch (Exception f) {
f.printStackTrace();
}
return false;
}
}
catch (Exception g){
g.printStackTrace();
return false;
}
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment