solution for number 13

added an AnimationState in Client and Server
added 2D and 3D representation of a missile
added missile launch sound
updated Singlemode to continue functionality
This commit is contained in:
Timo Brennförder
2024-10-12 18:24:33 +02:00
parent 264b854cbe
commit febdd63422
34 changed files with 2970 additions and 112 deletions

View File

@@ -0,0 +1,94 @@
package pp.battleship.game.client;
import pp.battleship.message.client.EndAnimationMessage;
import pp.battleship.message.server.EffectMessage;
import pp.battleship.message.server.SwitchToBattleState;
import pp.battleship.model.IntPoint;
import pp.battleship.model.Shell;
import pp.battleship.model.ShipMap;
import pp.battleship.notification.Music;
import pp.battleship.notification.Sound;
import java.lang.System.Logger.Level;
public class AnimationState extends ClientState{
private boolean myTurn;
public AnimationState(ClientGameLogic logic, boolean turn, IntPoint position) {
super(logic);
logic.playMusic(Music.GAME_THEME);
myTurn = turn;
if (myTurn){
logic.getOpponentMap().add(new Shell(position));
}
else {
logic.getOwnMap().add(new Shell(position));
}
}
@Override
boolean showBattle(){
return true;
}
/**
* Reports the effect of a shot based on the server message.
*
* @param msg the message containing the effect of the shot
*/
@Override
public void receivedEffect(EffectMessage msg) {
ClientGameLogic.LOGGER.log(Level.INFO, "report effect: {0}", msg); //NON-NLS
playSound(msg);
myTurn = msg.isMyTurn();
logic.setInfoText(msg.getInfoTextKey());
affectedMap(msg).add(msg.getShot());
if (destroyedOpponentShip(msg))
logic.getOpponentMap().add(msg.getDestroyedShip());
if (msg.isGameOver()) {
msg.getRemainingOpponentShips().forEach(logic.getOpponentMap()::add);
logic.setState(new GameOverState(logic, msg.isGameLost()));
}
}
@Override
public void receivedSwitchToBattleState(SwitchToBattleState msg){
logic.setState(new BattleState(logic, msg.getTurn()));
}
/**
* Determines which map (own or opponent's) should be affected by the shot based on the message.
*
* @param msg the effect message received from the server
* @return the map (either the opponent's or player's own map) that is affected by the shot
*/
private ShipMap affectedMap(EffectMessage msg) {
return msg.isOwnShot() ? logic.getOpponentMap() : logic.getOwnMap();
}
/**
* Checks if the opponent's ship was destroyed by the player's shot.
*
* @param msg the effect message received from the server
* @return true if the shot destroyed an opponent's ship, false otherwise
*/
private boolean destroyedOpponentShip(EffectMessage msg) {
return msg.getDestroyedShip() != null && msg.isOwnShot();
}
/**
* Plays a sound based on the outcome of the shot. Different sounds are played for a miss, hit,
* or destruction of a ship.
*
* @param msg the effect message containing the result of the shot
*/
private void playSound(EffectMessage msg) {
if (!msg.getShot().isHit())
logic.playSound(Sound.SPLASH);
else if (msg.getDestroyedShip() == null)
logic.playSound(Sound.EXPLOSION);
else
logic.playSound(Sound.DESTROYED_SHIP);
}
}

View File

@@ -9,6 +9,7 @@
import pp.battleship.message.client.ShootMessage;
import pp.battleship.message.server.EffectMessage;
import pp.battleship.message.server.StartAnimationMessage;
import pp.battleship.model.IntPoint;
import pp.battleship.model.ShipMap;
import pp.battleship.notification.Music;
@@ -47,58 +48,9 @@ else if (logic.getOpponentMap().isValid(pos))
logic.send(new ShootMessage(pos));
}
/**
* Reports the effect of a shot based on the server message.
*
* @param msg the message containing the effect of the shot
*/
@Override
public void receivedEffect(EffectMessage msg) {
ClientGameLogic.LOGGER.log(Level.INFO, "report effect: {0}", msg); //NON-NLS
playSound(msg);
myTurn = msg.isMyTurn();
logic.setInfoText(msg.getInfoTextKey());
affectedMap(msg).add(msg.getShot());
if (destroyedOpponentShip(msg))
logic.getOpponentMap().add(msg.getDestroyedShip());
if (msg.isGameOver()) {
msg.getRemainingOpponentShips().forEach(logic.getOpponentMap()::add);
logic.setState(new GameOverState(logic, msg.isGameLost()));
}
}
/**
* Determines which map (own or opponent's) should be affected by the shot based on the message.
*
* @param msg the effect message received from the server
* @return the map (either the opponent's or player's own map) that is affected by the shot
*/
private ShipMap affectedMap(EffectMessage msg) {
return msg.isOwnShot() ? logic.getOpponentMap() : logic.getOwnMap();
}
/**
* Checks if the opponent's ship was destroyed by the player's shot.
*
* @param msg the effect message received from the server
* @return true if the shot destroyed an opponent's ship, false otherwise
*/
private boolean destroyedOpponentShip(EffectMessage msg) {
return msg.getDestroyedShip() != null && msg.isOwnShot();
}
/**
* Plays a sound based on the outcome of the shot. Different sounds are played for a miss, hit,
* or destruction of a ship.
*
* @param msg the effect message containing the result of the shot
*/
private void playSound(EffectMessage msg) {
if (!msg.getShot().isHit())
logic.playSound(Sound.SPLASH);
else if (msg.getDestroyedShip() == null)
logic.playSound(Sound.EXPLOSION);
else
logic.playSound(Sound.DESTROYED_SHIP);
public void receivedStartAnimation(StartAnimationMessage msg){
logic.setState(new AnimationState(logic, msg.isMyTurn(), msg.getPosition() ));
logic.playSound(Sound.MISSILE_LAUNCH);
}
}

View File

@@ -11,7 +11,9 @@
import pp.battleship.message.server.EffectMessage;
import pp.battleship.message.server.GameDetails;
import pp.battleship.message.server.ServerInterpreter;
import pp.battleship.message.server.StartAnimationMessage;
import pp.battleship.message.server.StartBattleMessage;
import pp.battleship.message.server.SwitchToBattleState;
import pp.battleship.model.IntPoint;
import pp.battleship.model.ShipMap;
import pp.battleship.model.dto.ShipMapDTO;
@@ -228,6 +230,22 @@ public void received(EffectMessage msg) {
state.receivedEffect(msg);
}
/**
* @param msg
*/
@Override
public void received(StartAnimationMessage msg) {
state.receivedStartAnimation(msg);
}
/**
* @param msg
*/
@Override
public void received(SwitchToBattleState msg) {
state.receivedSwitchToBattleState(msg);
}
/**
* Initializes the player's own map, opponent's map, and harbor based on the game details.
*
@@ -306,7 +324,7 @@ public void saveMap(File file) throws IOException {
*
* @param msg the message to be sent
*/
void send(ClientMessage msg) {
public void send(ClientMessage msg) {
if (clientSender == null)
LOGGER.log(Level.ERROR, "trying to send {0} with sender==null", msg); //NON-NLS
else

View File

@@ -9,7 +9,9 @@
import pp.battleship.message.server.EffectMessage;
import pp.battleship.message.server.GameDetails;
import pp.battleship.message.server.StartAnimationMessage;
import pp.battleship.message.server.StartBattleMessage;
import pp.battleship.message.server.SwitchToBattleState;
import pp.battleship.model.IntPoint;
import java.io.File;
@@ -165,6 +167,14 @@ void receivedEffect(EffectMessage msg) {
ClientGameLogic.LOGGER.log(Level.ERROR, "receivedEffect not allowed in {0}", getName()); //NON-NLS
}
void receivedSwitchToBattleState(SwitchToBattleState msg) {
ClientGameLogic.LOGGER.log(Level.ERROR, "receivedSwitchToBattleState not allowed in {0}", getName());
}
void receivedStartAnimation(StartAnimationMessage msg) {
ClientGameLogic.LOGGER.log(Level.ERROR, "receivedStartAnimation not allowed in {0}", getName());
}
/**
* Loads a map from the specified file.
*

View File

@@ -9,12 +9,15 @@
import pp.battleship.BattleshipConfig;
import pp.battleship.message.client.ClientInterpreter;
import pp.battleship.message.client.EndAnimationMessage;
import pp.battleship.message.client.MapMessage;
import pp.battleship.message.client.ShootMessage;
import pp.battleship.message.server.EffectMessage;
import pp.battleship.message.server.GameDetails;
import pp.battleship.message.server.ServerMessage;
import pp.battleship.message.server.StartAnimationMessage;
import pp.battleship.message.server.StartBattleMessage;
import pp.battleship.message.server.SwitchToBattleState;
import pp.battleship.model.Battleship;
import pp.battleship.model.IntPoint;
@@ -39,6 +42,9 @@ public class ServerGameLogic implements ClientInterpreter {
private Player activePlayer;
private ServerState state = ServerState.WAIT;
private boolean p1AnimationFinished = false;
private boolean p2AnimationFinished = false;
/**
* Constructs a ServerGameLogic with the specified sender and configuration.
*
@@ -142,17 +148,46 @@ public Player addPlayer(int id) {
public void received(MapMessage msg, int from) {
if (state != ServerState.SET_UP)
LOGGER.log(Level.ERROR, "playerReady not allowed in {0}", state); //NON-NLS
else if(!checkMap(msg, from)) {
else if (!checkMap(msg, from)) {
LOGGER.log(Level.ERROR, "The submitted map is not allowed");
send(players.get(from), new GameDetails(config));
}
else
playerReady(getPlayerById(from), msg.getShips());
}
/**
* @param msg
*/
@Override
public void received(EndAnimationMessage msg, int from){
if(state != ServerState.WAIT_ANIMATION)
LOGGER.log(Level.ERROR, "animation not allowed in {0}", state);
else
if(getPlayerById(from) == players.get(0)){
LOGGER.log(Level.DEBUG, "{0} set to true", getPlayerById(from));
p1AnimationFinished = true;
shoot(getPlayerById(from), msg.getPosition());
}
else if (getPlayerById(from) == players.get(1)){
LOGGER.log(Level.DEBUG, "{0} set to true {1}", getPlayerById(from), getPlayerById(from).toString());
p2AnimationFinished = true;
shoot(getPlayerById(from), msg.getPosition());
}
if(p1AnimationFinished && p2AnimationFinished) {
setState(ServerState.BATTLE);
for (Player player : players)
send(player, new SwitchToBattleState(player == activePlayer));
p1AnimationFinished = false;
p2AnimationFinished = false;
}
}
/**
* Returns true if the map contains correct ship placement and is of the correct size
*
* @param msg the received MapMessage of the player
* @param msg the received MapMessage of the player
* @param from the ID of the Player
* @return a boolean based on if the transmitted map ist correct
*/
@@ -165,7 +200,7 @@ private boolean checkMap(MapMessage msg, int from) {
return false;
// check if ship is out of bounds
for (Battleship ship : msg.getShips()){
for (Battleship ship : msg.getShips()) {
if (ship.getMaxX() >= mapWidth || ship.getMinX() < 0 || ship.getMaxY() >= mapHeight || ship.getMinY() < 0) {
LOGGER.log(Level.ERROR, "Ship is out of bounds ({0})", ship.toString());
return false;
@@ -174,10 +209,10 @@ private boolean checkMap(MapMessage msg, int from) {
// check if ships overlap
List<Battleship> ships = msg.getShips();
for(Battleship ship:ships){
for(Battleship compareShip:ships){
if(!(ship==compareShip)){
if(ship.collidesWith(compareShip)){
for (Battleship ship : ships) {
for (Battleship compareShip : ships) {
if (!(ship == compareShip)) {
if (ship.collidesWith(compareShip)) {
return false;
}
}
@@ -197,10 +232,13 @@ public void received(ShootMessage msg, int from) {
if (state != ServerState.BATTLE)
LOGGER.log(Level.ERROR, "shoot not allowed in {0}", state); //NON-NLS
else
shoot(getPlayerById(from), msg.getPosition());
for (Player player : players) {
send(player, new StartAnimationMessage(msg.getPosition(), player == activePlayer));
setState(ServerState.WAIT_ANIMATION);
}
}
/**
/**
* Marks the player as ready and sets their ships.
* Transitions the state to PLAY if both players are ready.
*
@@ -220,41 +258,66 @@ void playerReady(Player player, List<Battleship> ships) {
}
}
/**
* Handles the shooting action by the player.
*
* @param p the player who shot
* @param pos the position of the shot
*/
void shoot(Player p, IntPoint pos) {
if (p != activePlayer) return;
final Player otherPlayer = getOpponent(activePlayer);
final Battleship selectedShip = otherPlayer.getMap().findShipAt(pos);
void shoot(Player player, IntPoint position) {
final Battleship selectedShip;
selectedShip = getSelectedShip(player, position);
if (selectedShip == null) {
// shot missed
send(activePlayer, EffectMessage.miss(true, pos));
send(otherPlayer, EffectMessage.miss(false, pos));
activePlayer = otherPlayer;
shotMissed(player, position);
}
else {
// shot hit a ship
selectedShip.hit(pos);
if (otherPlayer.getMap().getRemainingShips().isEmpty()) {
// game is over
send(activePlayer, EffectMessage.won(pos, selectedShip));
send(otherPlayer, EffectMessage.lost(pos, selectedShip, activePlayer.getMap().getRemainingShips()));
shotHit(player, position, selectedShip);
}
}
Battleship getSelectedShip(Player player, IntPoint position) {
if (player != activePlayer) {
return player.getMap().findShipAt(position);
}
else {
return getOpponent(player).getMap().findShipAt(position);
}
}
void shotMissed(Player player, IntPoint position) {
if (player != activePlayer) {
send(player, EffectMessage.miss(false, position));
}
else
send(activePlayer, EffectMessage.miss(true, position));
if (p1AnimationFinished && p2AnimationFinished)
if (player == activePlayer)
activePlayer = getOpponent(player);
else
activePlayer = player;
}
void shotHit(Player player, IntPoint position, Battleship ship) {
ship.hit(position);
if (getOpponent(activePlayer).getMap().getRemainingShips().isEmpty()) {
if (player != activePlayer)
send(player, EffectMessage.lost(position, ship, activePlayer.getMap().getRemainingShips()));
else
send(activePlayer, EffectMessage.won(position, ship));
if (p1AnimationFinished && p2AnimationFinished) {
setState(ServerState.GAME_OVER);
}
else if (selectedShip.isDestroyed()) {
// ship has been destroyed, but game is not yet over
send(activePlayer, EffectMessage.shipDestroyed(true, pos, selectedShip));
send(otherPlayer, EffectMessage.shipDestroyed(false, pos, selectedShip));
}
else if (ship.isDestroyed()) {
if (player != activePlayer)
send(player, EffectMessage.shipDestroyed(false, position, ship));
else
send(activePlayer, EffectMessage.shipDestroyed(true, position, ship));
}
else {
if (player != activePlayer) {
send(player, EffectMessage.hit(false, position));
}
else {
// ship has been hit, but it hasn't been destroyed
send(activePlayer, EffectMessage.hit(true, pos));
send(otherPlayer, EffectMessage.hit(false, pos));
send(activePlayer, EffectMessage.hit(true, position));
}
}
}
}
}

View File

@@ -26,6 +26,11 @@ enum ServerState {
*/
BATTLE,
/**
* Waits for the Animation to finish
*/
WAIT_ANIMATION,
/**
* The game has ended because all the ships of one player have been destroyed.
*/

View File

@@ -9,6 +9,7 @@
import pp.battleship.message.client.ClientInterpreter;
import pp.battleship.message.client.ClientMessage;
import pp.battleship.message.client.EndAnimationMessage;
import pp.battleship.message.client.MapMessage;
import pp.battleship.message.client.ShootMessage;
import pp.battleship.model.Battleship;
@@ -63,6 +64,15 @@ public void received(MapMessage msg, int from) {
copiedMessage = new MapMessage(msg.getShips().stream().map(Copycat::copy).toList());
}
/**
* @param msg
* @param from
*/
@Override
public void received(EndAnimationMessage msg, int from) {
copiedMessage = new EndAnimationMessage(msg.getPosition());
}
/**
* Creates a copy of the provided {@link Battleship}.
*

View File

@@ -9,11 +9,7 @@
import pp.battleship.game.client.BattleshipClient;
import pp.battleship.game.client.ClientGameLogic;
import pp.battleship.message.server.EffectMessage;
import pp.battleship.message.server.GameDetails;
import pp.battleship.message.server.ServerInterpreter;
import pp.battleship.message.server.ServerMessage;
import pp.battleship.message.server.StartBattleMessage;
import pp.battleship.message.server.*;
import java.io.IOException;
@@ -24,11 +20,13 @@
class InterpreterProxy implements ServerInterpreter {
private final BattleshipClient playerClient;
static final System.Logger LOGGER = System.getLogger(InterpreterProxy.class.getName());
/**
* Constructs an InterpreterProxy with the specified BattleshipClient.
*
* @param playerClient the client to which the server messages are forwarded
*/
InterpreterProxy(BattleshipClient playerClient) {
this.playerClient = playerClient;
}
@@ -82,6 +80,27 @@ public void received(EffectMessage msg) {
forward(msg);
}
/**
* Forwards the received AnimationStartMessage to the client's game logic.
*
* @param msg the AnimationStartMessage received from the server
*/
@Override
public void received(StartAnimationMessage msg) {
forward(msg);
}
/**
* Forwards the received SwitchBattleState to the client's game logic.
*
* @param msg the SwitchBattleState received from the server
*/
@Override
public void received(SwitchToBattleState msg){
LOGGER.log(System.Logger.Level.INFO, "Received SwitchBattleState");
forward(msg);
}
/**
* Forwards the specified ServerMessage to the client's game logic by enqueuing the message acceptance.
*

View File

@@ -1,12 +1,10 @@
package pp.battleship.game.singlemode;
import pp.battleship.game.client.BattleshipClient;
import pp.battleship.message.client.EndAnimationMessage;
import pp.battleship.message.client.MapMessage;
import pp.battleship.message.client.ShootMessage;
import pp.battleship.message.server.EffectMessage;
import pp.battleship.message.server.GameDetails;
import pp.battleship.message.server.ServerInterpreter;
import pp.battleship.message.server.StartBattleMessage;
import pp.battleship.message.server.*;
import pp.battleship.model.IntPoint;
import pp.battleship.model.dto.ShipMapDTO;
import pp.util.RandomPositionIterator;
@@ -113,15 +111,35 @@ public void received(StartBattleMessage msg) {
}
/**
* Receives an effect message, logs it, and updates the turn status.
* If it is RobotClient's turn to shoot, schedules a shot using shoot();
* Receives an effect message, logs it.
*
* @param msg The effect message
*/
@Override
public void received(EffectMessage msg) {
LOGGER.log(Level.INFO, "Received EffectMessage: {0}", msg); //NON-NLS
if (msg.isMyTurn())
}
/**
* Receives an AnimationStartMessage, and responds instantly with an AnimationEndMessage
*
* @param msg the AnimationStartMessage received
*/
@Override
public void received(StartAnimationMessage msg) {
LOGGER.log(Level.INFO, "Received AnimationStartMessage: {0}", msg);
connection.sendRobotMessage(new EndAnimationMessage(msg.getPosition()));
}
/**
* Receives a SwitchBattleState, and shots if it is the robots turn
*
* @param msg the SwitchBattleState received
*/
@Override
public void received(SwitchToBattleState msg){
LOGGER.log(Level.INFO, "Received SwitchBattleStateMessage: {0}", msg);
if (msg.getTurn())
shoot();
}
}
}

View File

@@ -26,4 +26,6 @@ public interface ClientInterpreter {
* @param from the connection ID from which the message was received
*/
void received(MapMessage msg, int from);
void received(EndAnimationMessage msg, int from);
}

View File

@@ -0,0 +1,33 @@
package pp.battleship.message.client;
import com.jme3.network.serializing.Serializable;
import pp.battleship.model.IntPoint;
@Serializable
public class EndAnimationMessage extends ClientMessage{
private IntPoint position;
private EndAnimationMessage(){/*do nothing */}
public EndAnimationMessage(final IntPoint position){
this.position = position;
}
/**
* Accepts a visitor for processing this message.
*
* @param interpreter the visitor to be used for processing
* @param from the connection ID of the sender
*/
@Override
public void accept(ClientInterpreter interpreter, int from) {
interpreter.received(this, from);
}
public IntPoint getPosition() {
return position;
}
}

View File

@@ -7,6 +7,8 @@
package pp.battleship.message.server;
import pp.battleship.message.client.EndAnimationMessage;
/**
* An interface for processing server messages.
* Implementations of this interface can be used to handle different types of server messages.
@@ -33,4 +35,8 @@ public interface ServerInterpreter {
* @param msg the EffectMessage received
*/
void received(EffectMessage msg);
void received(StartAnimationMessage msg);
void received(SwitchToBattleState msg);
}

View File

@@ -0,0 +1,45 @@
package pp.battleship.message.server;
import com.jme3.network.serializing.Serializable;
import pp.battleship.model.IntPoint;
@Serializable
public class StartAnimationMessage extends ServerMessage {
private IntPoint position;
private boolean myTurn;
private StartAnimationMessage(){/*do nothing */}
public StartAnimationMessage(IntPoint position, boolean myTurn) {
this.position = position;
this.myTurn = myTurn;
}
/**
* Accepts a visitor for processing this message.
*
* @param interpreter the visitor to be used for processing
*/
@Override
public void accept(ServerInterpreter interpreter) {
interpreter.received(this);
}
/**
* Gets the bundle key of the informational text to be shown at the client.
* This key is used to retrieve the appropriate localized text for display.
*
* @return the bundle key of the informational text
*/
@Override
public String getInfoTextKey() {
return "started animation at " + position;
}
public IntPoint getPosition() {return position;}
public boolean isMyTurn() {return myTurn;}
}

View File

@@ -0,0 +1,40 @@
package pp.battleship.message.server;
import com.jme3.network.serializing.Serializable;
@Serializable
public class SwitchToBattleState extends ServerMessage{
private boolean myTurn;
private SwitchToBattleState(){/*do nothing */}
public SwitchToBattleState(boolean turn){
myTurn = turn;
}
/**
* Accepts a visitor for processing this message.
*
* @param interpreter the visitor to be used for processing
*/
@Override
public void accept(ServerInterpreter interpreter) {
interpreter.received(this);
}
/**
* Gets the bundle key of the informational text to be shown at the client.
* This key is used to retrieve the appropriate localized text for display.
*
* @return the bundle key of the informational text
*/
@Override
public String getInfoTextKey() {
return "switched to battle state";
}
public boolean getTurn(){return myTurn;}
}

View File

@@ -0,0 +1,77 @@
package pp.battleship.model;
/**
* This class represents a shell
*/
public class Shell implements Item {
private int x;
private int y;
/**
* constructs a new shell object
*
* @param position the end position of the shell
*/
public Shell(IntPoint position) {
x = position.getX();
y = position.getY();
}
/**
* getter for the x coordinate
*
* @return int x coordinate
*/
public int getX() {
return x;
}
/**
* getter for the y coordinate
*
* @return int y coordinate
*/
public int getY() {
return y;
}
/**
* setter for x coordinate
*
* @param x the new value of x coordinate
*/
public void setX(int x) {
this.x = x;
}
/**
* setter for y coordinate
*
* @param y the new value of y coordinate
*/
public void setY(int y) {
this.y = y;
}
/**
* Accepts a visitor with a return value.
*
* @param visitor the visitor to accept
* @param <T> the type of the return value
* @return the result of the visitor's visit method
*/
@Override
public <T> T accept(Visitor<T> visitor) {
return visitor.visit(this);
}
/**
* Accepts a visitor without a return value.
*
* @param visitor the visitor to accept
*/
@Override
public void accept(VoidVisitor visitor) {
visitor.visit(this);
}
}

View File

@@ -91,6 +91,14 @@ public void add(Shot shot) {
addItem(shot);
}
/**
* Registers a shell on the map
* @param shell the shell to be registered
*/
public void add(Shell shell) {
addItem(shell);
}
/**
* Removes an item from the map and triggers an item removal event.
*

View File

@@ -28,4 +28,6 @@ public interface Visitor<T> {
* @return the result of visiting the Battleship element
*/
T visit(Battleship ship);
T visit(Shell shell);
}

View File

@@ -25,4 +25,6 @@ public interface VoidVisitor {
* @param ship the Battleship element to visit
*/
void visit(Battleship ship);
void visit(Shell shell);
}

View File

@@ -22,5 +22,9 @@ public enum Sound {
/**
* Sound of a ship being destroyed.
*/
DESTROYED_SHIP
DESTROYED_SHIP,
/**
* Sound of a missile being fired
*/
MISSILE_LAUNCH
}