Tried implementing a simple command for server that starts up a game, didn't work so I had to readjust some things

This commit is contained in:
Seraina 2022-04-08 22:23:00 +02:00
parent 5b4a06dd75
commit 3b0bc40ad0
15 changed files with 127 additions and 80 deletions

View File

@ -6,6 +6,7 @@ Implemented:
* CPING Ping from client to server. * CPING Ping from client to server.
* PINGB Pingback from client to server. * PINGB Pingback from client to server.
* NAMEC$name Change name to whatever is specified * NAMEC$name Change name to whatever is specified
* STGAM start the Game
Future / planned: Future / planned:
* CRTGM Create a new game * CRTGM Create a new game

View File

@ -2,7 +2,13 @@ package ch.unibas.dmi.dbis.cs108.gamelogic;
import ch.unibas.dmi.dbis.cs108.BudaLogConfig; import ch.unibas.dmi.dbis.cs108.BudaLogConfig;
import ch.unibas.dmi.dbis.cs108.gamelogic.klassenstruktur.GhostNPC;
import ch.unibas.dmi.dbis.cs108.gamelogic.klassenstruktur.GhostPlayer;
import ch.unibas.dmi.dbis.cs108.gamelogic.klassenstruktur.HumanNPC;
import ch.unibas.dmi.dbis.cs108.gamelogic.klassenstruktur.HumanPlayer;
import ch.unibas.dmi.dbis.cs108.gamelogic.klassenstruktur.Passenger;
import ch.unibas.dmi.dbis.cs108.multiplayer.server.ClientHandler; import ch.unibas.dmi.dbis.cs108.multiplayer.server.ClientHandler;
import java.util.HashSet;
import org.apache.logging.log4j.*; import org.apache.logging.log4j.*;
public class Game { public class Game {
@ -15,7 +21,7 @@ public class Game {
protected int nrOfPlayers; //sets the length of the train protected int nrOfPlayers; //sets the length of the train
protected int nrOfGhosts; // sets how many Ghosts we start witch protected int nrOfGhosts; // sets how many Ghosts we start witch
protected int nrOfUsers; // safes how many clients are active in this Game protected int nrOfUsers; // safes how many clients are active in this Game
protected GameFunctions gameFunctions; protected GameState gameState;
protected boolean isDay; //false means it is night, it is night by default protected boolean isDay; //false means it is night, it is night by default
protected VoteHandler voteHandler; protected VoteHandler voteHandler;
//TODO: Figure out where Day/Night game state is saved maybe think about a game state class or smt. //TODO: Figure out where Day/Night game state is saved maybe think about a game state class or smt.
@ -31,11 +37,11 @@ public class Game {
this.nrOfPlayers = nrOfPlayers; this.nrOfPlayers = nrOfPlayers;
this.nrOfGhosts = nrOfGhosts; this.nrOfGhosts = nrOfGhosts;
this.nrOfUsers = nrOfUsers; this.nrOfUsers = nrOfUsers;
this.gameFunctions = new GameFunctions(nrOfPlayers, nrOfGhosts, nrOfUsers, this); this.gameState = new GameState(nrOfPlayers, nrOfGhosts, nrOfUsers);
} }
public GameFunctions getGameFunctions() { public GameState getGameState() {
return gameFunctions; return gameState;
} }
public int getNrOfGhosts() { public int getNrOfGhosts() {
@ -55,20 +61,53 @@ public class Game {
} }
public void run(ClientHandler clientHandler) { public void run(ClientHandler clientHandler) {
int i = 0; int i = 0;
String gameOverCheck = ""; HashSet<ClientHandler> clients = ClientHandler.getConnectedClients();
while (true) { //ToDo: was ist die Abbruchbedingung? VoteHandler muss das schicken. String gameOverCheck = "";
if (!isDay) { int[] order = gameState.getTrain().orderOfTrain;
voteHandler.ghostVote(gameFunctions.getPassengerTrain(), this); Passenger[] passengerTrain = gameState.getPassengerTrain();
setDay(true);
} else {
gameOverCheck = voteHandler.humanVote(gameFunctions.getPassengerTrain(), this); for (ClientHandler client : clients) {
} int index = order[i];
if (gameOverCheck.equals("Game over: ghosts win!") || gameOverCheck.equals("Game over: humans win!")){ if (passengerTrain[index].getIsGhost()) { //if there is a ghost
clientHandler.broadcastAnnouncement(gameOverCheck); GhostPlayer ghostPlayer = new GhostPlayer(passengerTrain[index].getPosition(),
return; client.getClientUserName(), client, passengerTrain[index].getIsOG());
} gameState.getPassengerTrain()[index] = ghostPlayer;
} } else {
HumanPlayer humanPlayer = new HumanPlayer(passengerTrain[index].getPosition(),
client.getClientUserName(), client, passengerTrain[index].getIsOG());
gameState.getPassengerTrain()[index] = humanPlayer;
}
i++;
}
while (i < order.length) {
int index = order[i];
if (passengerTrain[index].getIsGhost()) { //if there is a ghost
GhostNPC ghostNPC = new GhostNPC(passengerTrain[index].getPosition(), "NPC" + passengerTrain[index].getPosition(),passengerTrain[index].getIsOG() ,this);
gameState.getPassengerTrain()[index] = ghostNPC;
} else {
//ToDo: give NPC nice usernames
HumanNPC humanNPC = new HumanNPC(passengerTrain[index].getPosition(), "NPC" + passengerTrain[index].getPosition(),this);
gameState.getPassengerTrain()[index] = humanNPC;
}
i++;
}
i = 0;
while (true) { //ToDo: was ist die Abbruchbedingung? VoteHandler muss das schicken.
if (!isDay) {
voteHandler.ghostVote(gameState.getPassengerTrain(), this);
setDay(true);
} else {
gameOverCheck = voteHandler.humanVote(gameState.getPassengerTrain(), this);
}
if (gameOverCheck.equals("Game over: ghosts win!") || gameOverCheck.equals(
"Game over: humans win!")) {
clientHandler.broadcastAnnouncement(gameOverCheck);
return;
}
}
} }

View File

@ -7,22 +7,25 @@ import ch.unibas.dmi.dbis.cs108.gamelogic.klassenstruktur.Passenger;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
public class GameFunctions { public class GameState {
public static final Logger LOGGER = LogManager.getLogger(); public static final Logger LOGGER = LogManager.getLogger();
public static final BudaLogConfig l = new BudaLogConfig(LOGGER); public static final BudaLogConfig l = new BudaLogConfig(LOGGER);
/** /**
* Can be extended for optional Game-settings * Can be extended for optional Game-settings
**/ **/
protected int nrOfPlayers; //sets the length of the train public final int nrOfPlayers; //sets the length of the train
protected int nrOfGhosts; // sets how many Ghosts we start witch public final int nrOfGhosts; // sets how many Ghosts we start witch
protected int nrOfUsers; // safes how many clients are active in this Game public final int nrOfUsers; // safes how many clients are active in this Game
protected Train train; // safes who sits where public final Train train; // safes who sits where
protected Passenger[] passengerTrain; /**
protected Game game; * contains all Passengers on train, needs to be updated
*/
private Passenger[] passengerTrain;
/** /**
* Constructs a GameFunctions instance where nrOfPlayers >= nrOfUsers. Fills passengerTrain with * Constructs a GameState instance where nrOfPlayers >= nrOfUsers. Fills passengerTrain with
* only humans * only humans
* *
* @param nrOfPlayers is the length of the Train * @param nrOfPlayers is the length of the Train
@ -30,7 +33,7 @@ public class GameFunctions {
* @param nrOfUsers is the number of active users at the time (non NPCs) * @param nrOfUsers is the number of active users at the time (non NPCs)
* @throws TrainOverflow if nrOfPlayers < nrOfUsers * @throws TrainOverflow if nrOfPlayers < nrOfUsers
*/ */
GameFunctions(int nrOfPlayers, int nrOfGhosts, int nrOfUsers, Game game) GameState(int nrOfPlayers, int nrOfGhosts, int nrOfUsers)
throws TrainOverflow { //ToDo: where will Exception be handled? throws TrainOverflow { //ToDo: where will Exception be handled?
this.nrOfPlayers = nrOfPlayers; this.nrOfPlayers = nrOfPlayers;
this.nrOfGhosts = nrOfGhosts; this.nrOfGhosts = nrOfGhosts;
@ -39,12 +42,12 @@ public class GameFunctions {
Passenger[] passengerTrain = new Passenger[nrOfPlayers]; //Creates an array with Passengers with correlation positions (Train) Passenger[] passengerTrain = new Passenger[nrOfPlayers]; //Creates an array with Passengers with correlation positions (Train)
for (int i = 0; i < nrOfPlayers; i++) { for (int i = 0; i < nrOfPlayers; i++) {
if (i == 3) { if (i == 3) {
Ghost g = new Ghost(game); Ghost g = new Ghost();
g.setPosition(train.orderOfTrain[i]); g.setPosition(train.orderOfTrain[i]);
g.setIsOG(true); g.setIsOG(true);
passengerTrain[train.orderOfTrain[i]] = g; passengerTrain[train.orderOfTrain[i]] = g;
} else { } else {
Human h = new Human(game); Human h = new Human();
h.setPosition(train.orderOfTrain[i]); h.setPosition(train.orderOfTrain[i]);
passengerTrain[train.orderOfTrain[i]] = h; passengerTrain[train.orderOfTrain[i]] = h;
} }
@ -53,19 +56,22 @@ public class GameFunctions {
this.passengerTrain = passengerTrain; this.passengerTrain = passengerTrain;
} }
public int getNrOfGhosts() {
return nrOfGhosts;
}
public int getNrOfPlayers() {
return nrOfPlayers;
}
public int getNrOfUsers() {
return nrOfUsers;
}
public Passenger[] getPassengerTrain() { public Passenger[] getPassengerTrain() {
return passengerTrain; return passengerTrain;
} }
public Train getTrain() {
return train;
}
/**
* Takes a given Passenger and puts it into the passengerTrain at a certain position
* @param passenger the new passenger being put into the train
* @param position the position of the passenger
*/
public void addNewPassenger(Passenger passenger, int position) {
passengerTrain[position] = passenger;
}
} }

View File

@ -21,10 +21,10 @@ public class GhostifyHandler {
LOGGER.debug("Passenger Position " + p.getPosition()); LOGGER.debug("Passenger Position " + p.getPosition());
p.setGhost(); p.setGhost();
Ghost g; Ghost g;
g = new Ghost(game); g = new Ghost();
g.setGhost(); g.setGhost();
g.setPosition(p.getPosition()); g.setPosition(p.getPosition());
game.gameFunctions.passengerTrain[g.getPosition()] = g; game.gameState.addNewPassenger(g, g.getPosition());
LOGGER.info("Passenger at position " + p.getPosition() + "has been ghostified"); LOGGER.info("Passenger at position " + p.getPosition() + "has been ghostified");
return g; return g;
} }

View File

@ -43,10 +43,10 @@ public class VoteHandler {
for (Passenger passenger : passengers) { for (Passenger passenger : passengers) {
if (passenger.getIsGhost()) { if (passenger.getIsGhost()) {
passenger.send("Vote on who to ghostify!"); passenger.send("Vote on who to ghostify!", game);
} else { } else {
passenger.send( passenger.send(
"Please wait, ghosts are active"); // TODO(Seraina): make sure whatever clients send in "Please wait, ghosts are active", game); // TODO(Seraina): make sure whatever clients send in
// this time, except chat is ignored // this time, except chat is ignored
} }
@ -91,7 +91,7 @@ public class VoteHandler {
Ghost g = gh.ghost(passengers[ghostPosition], game); Ghost g = gh.ghost(passengers[ghostPosition], game);
passengers[ghostPosition] = g; passengers[ghostPosition] = g;
passengers[ghostPosition].send( passengers[ghostPosition].send(
"You are now a ghost!"); // TODO: ServerGameInfoHandler might deal with this one "You are now a ghost!", game); // TODO: ServerGameInfoHandler might deal with this one
// set hasVoted to false for all passengers for future votings // set hasVoted to false for all passengers for future votings
for (Passenger passenger : passengers) { for (Passenger passenger : passengers) {
@ -119,9 +119,9 @@ public class VoteHandler {
// TODO: Messages in for-loop should probably be handled by ServerGameInfoHandler // TODO: Messages in for-loop should probably be handled by ServerGameInfoHandler
for (Passenger passenger : passengers) { for (Passenger passenger : passengers) {
if (passenger.getIsGhost()) { if (passenger.getIsGhost()) {
passenger.send("Please wait, humans are active"); passenger.send("Please wait, humans are active", game);
} else { } else {
passenger.send("Vote for a ghost to kick off!"); passenger.send("Vote for a ghost to kick off!", game);
} }
} }
@ -158,7 +158,7 @@ public class VoteHandler {
.getIsGhost()) { // if player with most votes is human, notify everyone about it .getIsGhost()) { // if player with most votes is human, notify everyone about it
for (Passenger passenger : passengers) { for (Passenger passenger : passengers) {
passenger.send( passenger.send(
"You voted for a human!"); // TODO: ServerGameInfoHandler might be better to use here "You voted for a human!", game); // TODO: ServerGameInfoHandler might be better to use here
} }
} }
if (passengers[voteIndex].getIsGhost()) { // if player is a ghost if (passengers[voteIndex].getIsGhost()) { // if player is a ghost
@ -183,7 +183,7 @@ public class VoteHandler {
// kick this ghost off // kick this ghost off
passengers[voteIndex].setKickedOff(true); passengers[voteIndex].setKickedOff(true);
for (Passenger passenger : passengers) { for (Passenger passenger : passengers) {
passenger.send("Player " + voteIndex + " has been kicked off!"); passenger.send("Player " + voteIndex + " has been kicked off!", game);
} }
} }
} }
@ -225,8 +225,8 @@ public class VoteHandler {
Game game = new Game(6,1, 6); Game game = new Game(6,1, 6);
VoteHandler voteHandler = new VoteHandler(); VoteHandler voteHandler = new VoteHandler();
Passenger[] testArray = game.gameFunctions.passengerTrain; Passenger[] testArray = game.gameState.getPassengerTrain();
Passenger ghost = new Ghost(game); Passenger ghost = new Ghost();
testArray[3] = ghost; testArray[3] = ghost;
testArray[3].setGhost(); testArray[3].setGhost();
testArray[3].setIsOg(); testArray[3].setIsOg();

View File

@ -9,9 +9,7 @@ public class Ghost extends Passenger {
public static final Logger LOGGER = LogManager.getLogger(); public static final Logger LOGGER = LogManager.getLogger();
public static final BudaLogConfig l = new BudaLogConfig(LOGGER); public static final BudaLogConfig l = new BudaLogConfig(LOGGER);
public Ghost(Game game) {
super(game);
}
public boolean getIsOG() { public boolean getIsOG() {
return isOG; return isOG;

View File

@ -2,6 +2,7 @@ package ch.unibas.dmi.dbis.cs108.gamelogic.klassenstruktur;
import ch.unibas.dmi.dbis.cs108.BudaLogConfig; import ch.unibas.dmi.dbis.cs108.BudaLogConfig;
import ch.unibas.dmi.dbis.cs108.gamelogic.Game; import ch.unibas.dmi.dbis.cs108.gamelogic.Game;
import ch.unibas.dmi.dbis.cs108.gamelogic.GameState;
import ch.unibas.dmi.dbis.cs108.gamelogic.ServerGameInfoHandler; import ch.unibas.dmi.dbis.cs108.gamelogic.ServerGameInfoHandler;
import ch.unibas.dmi.dbis.cs108.gamelogic.TrainOverflow; import ch.unibas.dmi.dbis.cs108.gamelogic.TrainOverflow;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
@ -19,7 +20,6 @@ public class GhostNPC extends Ghost {
* @param isOG true if the ghost is the original ghost. * @param isOG true if the ghost is the original ghost.
*/ */
public GhostNPC(int position, String name, boolean isOG, Game game) { public GhostNPC(int position, String name, boolean isOG, Game game) {
super(game);
this.isOG = isOG; this.isOG = isOG;
this.position = position; this.position = position;
this.clientHandler = null; this.clientHandler = null;
@ -34,7 +34,7 @@ public class GhostNPC extends Ghost {
} }
@Override @Override
public void send(String msg) { public void send(String msg, Game game) {
ServerGameInfoHandler.ghostNpcParser(this, msg, game); ServerGameInfoHandler.ghostNpcParser(this, msg, game);
} }
@ -44,7 +44,7 @@ public class GhostNPC extends Ghost {
*/ */
public void vote(Game game){ public void vote(Game game){
int ghostCounter = 0; int ghostCounter = 0;
Passenger[] train = game.getGameFunctions().getPassengerTrain(); Passenger[] train = game.getGameState().getPassengerTrain();
for(Passenger passenger : train) { for(Passenger passenger : train) {
if(passenger.isGhost) { if(passenger.isGhost) {
ghostCounter++; ghostCounter++;
@ -72,7 +72,7 @@ public class GhostNPC extends Ghost {
try { try {
Game game = new Game(6,1,1); Game game = new Game(6,1,1);
Passenger p = new Passenger(game); Passenger p = new Passenger();
GhostNPC ghostNPC = new GhostNPC(2,"peter", false, game); GhostNPC ghostNPC = new GhostNPC(2,"peter", false, game);
p = ghostNPC; p = ghostNPC;
ghostNPC.vote(game); ghostNPC.vote(game);

View File

@ -14,13 +14,11 @@ public class GhostPlayer extends Ghost {
/** /**
* Creates a new GhostPlayer. Should be used at game start or if a HumanPlayer is turned into a * Creates a new GhostPlayer. Should be used at game start or if a HumanPlayer is turned into a
* ghost. * ghost.
* * @param position position on the train
* @param position position on the train
* @param name name. if null, then a default name is used. * @param name name. if null, then a default name is used.
* @param isOG true if the ghost is the original ghost. * @param isOG true if the ghost is the original ghost.
*/ */
public GhostPlayer(int position, String name, ClientHandler clientHandler, boolean isOG, Game game) { public GhostPlayer(int position, String name, ClientHandler clientHandler, boolean isOG) {
super(game);
this.position = position; this.position = position;
this.clientHandler = clientHandler; this.clientHandler = clientHandler;
this.isOG = isOG; this.isOG = isOG;
@ -36,7 +34,7 @@ public class GhostPlayer extends Ghost {
@Override @Override
public void send(String msg) { public void send(String msg, Game game) {
String formattedMsg = ServerGameInfoHandler.format(msg); String formattedMsg = ServerGameInfoHandler.format(msg);
clientHandler.sendMsgToClient(formattedMsg); clientHandler.sendMsgToClient(formattedMsg);
} }

View File

@ -9,8 +9,5 @@ public class Human extends Passenger {
public static final Logger LOGGER = LogManager.getLogger(); public static final Logger LOGGER = LogManager.getLogger();
public static final BudaLogConfig l = new BudaLogConfig(LOGGER); public static final BudaLogConfig l = new BudaLogConfig(LOGGER);
public Human(Game game) {
super(game);
}
} }

View File

@ -17,7 +17,6 @@ public class HumanNPC extends Human {
* @param name player name. if null, then a default name is used. * @param name player name. if null, then a default name is used.
*/ */
public HumanNPC(int position, String name, Game game) { public HumanNPC(int position, String name, Game game) {
super(game);
this.position = position; this.position = position;
this.clientHandler = null; this.clientHandler = null;
isGhost = false; isGhost = false;
@ -31,7 +30,7 @@ public class HumanNPC extends Human {
} }
@Override @Override
public void send(String msg) { public void send(String msg, Game game) {
ServerGameInfoHandler.humanNpcParser(this, msg, game); ServerGameInfoHandler.humanNpcParser(this, msg, game);
} }

View File

@ -14,12 +14,10 @@ public class HumanPlayer extends Human {
/** /**
* Creates a new GhostPlayer. Should be used at game start or if a HumanPlayer is turned into a * Creates a new GhostPlayer. Should be used at game start or if a HumanPlayer is turned into a
* ghost. * ghost.
* * @param position position on the train
* @param position position on the train
* @param name name. if null, then a default name is used. * @param name name. if null, then a default name is used.
*/ */
public HumanPlayer(int position, String name, ClientHandler clientHandler, boolean isOG, Game game) { public HumanPlayer(int position, String name, ClientHandler clientHandler, boolean isOG) {
super(game);
this.position = position; this.position = position;
this.clientHandler = clientHandler; this.clientHandler = clientHandler;
isGhost = false; isGhost = false;
@ -33,7 +31,7 @@ public class HumanPlayer extends Human {
} }
@Override @Override
public void send(String msg) { public void send(String msg, Game game) {
String formattedMsg = ServerGameInfoHandler.format(msg); String formattedMsg = ServerGameInfoHandler.format(msg);
clientHandler.sendMsgToClient(formattedMsg); clientHandler.sendMsgToClient(formattedMsg);
} }

View File

@ -21,17 +21,12 @@ public class Passenger {
protected ClientHandler clientHandler;//the socket for the client associated with this Passenger, for NPCs, this can be null. protected ClientHandler clientHandler;//the socket for the client associated with this Passenger, for NPCs, this can be null.
protected boolean hasVoted; //true if the player gave his vote during voting time protected boolean hasVoted; //true if the player gave his vote during voting time
protected int vote; //saves the number of the player this passenger voted for during voting (0-5) protected int vote; //saves the number of the player this passenger voted for during voting (0-5)
protected Game game;
Passenger(Game game) {
this.game = game;
}
/** /**
* Sends a protocol message to the respective player or NPC. * Sends a protocol message to the respective player or NPC.
* @param msg the message that is sent to this player. * @param msg the message that is sent to this player.
**/ **/
public void send(String msg) { public void send(String msg, Game game) {
if (isPlayer) { if (isPlayer) {
String formattedMsg = ServerGameInfoHandler.format(msg); String formattedMsg = ServerGameInfoHandler.format(msg);
clientHandler.sendMsgToClient(formattedMsg); clientHandler.sendMsgToClient(formattedMsg);

View File

@ -92,6 +92,11 @@ public class Protocol {
*/ */
public static final String listLobbies = "LISTL"; public static final String listLobbies = "LISTL";
/**
* A Client decides to start the game
*/
public static final String startANewGame = "STGAM";
//SERVER TO CLIENT COMMANDS //SERVER TO CLIENT COMMANDS

View File

@ -11,6 +11,7 @@ Implemented:
* PINGB Pingback from client to server. * PINGB Pingback from client to server.
* NAMEC$name Change name to whatever is specified * NAMEC$name Change name to whatever is specified
* CRTGM Create a new game * CRTGM Create a new game
*
Future / planned: Future / planned:

View File

@ -2,6 +2,8 @@ package ch.unibas.dmi.dbis.cs108.multiplayer.server;
import ch.unibas.dmi.dbis.cs108.BudaLogConfig; import ch.unibas.dmi.dbis.cs108.BudaLogConfig;
import ch.unibas.dmi.dbis.cs108.gamelogic.Game;
import ch.unibas.dmi.dbis.cs108.gamelogic.TrainOverflow;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import ch.unibas.dmi.dbis.cs108.multiplayer.helpers.Protocol; import ch.unibas.dmi.dbis.cs108.multiplayer.helpers.Protocol;
@ -67,6 +69,14 @@ public class JServerProtocolParser {
//TODO: add action //TODO: add action
LOGGER.debug(Protocol.listLobbies + " command recieved from: " + h.getClientUserName()); LOGGER.debug(Protocol.listLobbies + " command recieved from: " + h.getClientUserName());
break; break;
case Protocol.startANewGame:
try {
Game game = new Game(6,1, h.getConnectedClients().size());
game.run(h);
} catch (TrainOverflow e) {
LOGGER.warn(e.getMessage());
}
default: default:
System.out.println("Received unknown command"); System.out.println("Received unknown command");
} }