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

@@ -35,6 +35,7 @@ public class GameSound extends AbstractAppState implements GameEventListener {
private AudioNode splashSound;
private AudioNode shipDestroyedSound;
private AudioNode explosionSound;
private AudioNode missileLaunch;
/**
* Checks if sound is enabled in the preferences.
@@ -79,6 +80,7 @@ public void initialize(AppStateManager stateManager, Application app) {
shipDestroyedSound = loadSound(app, "Sound/Effects/sunken.wav"); //NON-NLS
splashSound = loadSound(app, "Sound/Effects/splash.wav"); //NON-NLS
explosionSound = loadSound(app, "Sound/Effects/explosion.wav"); //NON-NLS
missileLaunch = loadSound(app, "Sound/Effects/missilefiring.wav"); //NON-NLS
}
/**
@@ -101,6 +103,14 @@ private AudioNode loadSound(Application app, String name) {
return null;
}
/**
* Plays the splash sound effect.
*/
public void missileLaunch() {
if (isEnabled() && missileLaunch != null)
missileLaunch.playInstance();
}
/**
* Plays the splash sound effect.
*/
@@ -131,6 +141,7 @@ public void receivedEvent(SoundEvent event) {
case EXPLOSION -> explosion();
case SPLASH -> splash();
case DESTROYED_SHIP -> shipDestroyed();
case MISSILE_LAUNCH -> missileLaunch();
}
}
}

View File

@@ -70,7 +70,7 @@ public void hitEffect(Node battleshipNode, Shot shot){
debris.setLocalTranslation(shot.getY() + 0.5f, 0 , shot.getX() + 0.5f);
debris.emitAllParticles();
//Fire //TODO Fix creation of fire on the edge of the map
//Fire
ParticleEmitter fire = new ParticleEmitter("Fire", Type.Triangle, 30);
Material fireMaterial = new Material(assetManager, "Common/MatDefs/Misc/Particle.j3md");
fireMaterial.setTexture("Texture", assetManager.loadTexture("Textures/Fire/fire.png"));

View File

@@ -12,9 +12,14 @@
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import pp.battleship.model.Battleship;
import pp.battleship.model.IntPoint;
import pp.battleship.model.Shell;
import pp.battleship.model.Shot;
import pp.util.Position;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
/**
* Synchronizes the visual representation of the ship map with the game model.
* It handles the rendering of ships and shots on the map view, updating the view
@@ -26,6 +31,9 @@ class MapViewSynchronizer extends ShipMapSynchronizer {
private static final float SHOT_DEPTH = -2f;
private static final float SHIP_DEPTH = 0f;
private static final float INDENT = 4f;
private static final float MISSILE_DEPTH = 6f;
private static final float MISSILE_SIZE = 0.8f;
private static final float MISSILE_CENTERED_IN_MAP_GRID = 0.0625f;
// Colors used for different visual elements
private static final ColorRGBA HIT_COLOR = ColorRGBA.Red;
@@ -37,6 +45,8 @@ class MapViewSynchronizer extends ShipMapSynchronizer {
// The MapView associated with this synchronizer
private final MapView view;
static final Logger LOGGER = System.getLogger(MapViewSynchronizer.class.getName());
/**
* Constructs a new MapViewSynchronizer for the given MapView.
* Initializes the synchronizer and adds existing elements from the model to the view.
@@ -58,16 +68,14 @@ public MapViewSynchronizer(MapView view) {
*/
@Override
public Spatial visit(Shot shot) {
LOGGER.log(Level.DEBUG, "visiting" + shot);
// Convert the shot's model coordinates to view coordinates
final Position p1 = view.modelToView(shot.getX(), shot.getY());
final Position p2 = view.modelToView(shot.getX() + 1, shot.getY() + 1);
final ColorRGBA color = shot.isHit() ? HIT_COLOR : MISS_COLOR;
// Create and return a rectangle representing the shot
return view.getApp().getDraw().makeRectangle(p1.getX(), p1.getY(),
SHOT_DEPTH,
p2.getX() - p1.getX(), p2.getY() - p1.getY(),
color);
return view.getApp().getDraw().makeRectangle(p1.getX(), p1.getY(), SHOT_DEPTH, p2.getX() - p1.getX(), p2.getY() - p1.getY(), color);
}
/**
@@ -109,6 +117,26 @@ public Spatial visit(Battleship ship) {
return shipNode;
}
@Override
public Spatial visit(Shell shell) {
LOGGER.log(Logger.Level.DEBUG, "Visiting {0}", shell);
final Node missileNode = new Node("missile");
final Position p1 = view.modelToView(shell.getX(), shell.getY());
final Position p2 = view.modelToView(shell.getX() + MISSILE_SIZE, shell.getY() + MISSILE_SIZE);
final float x1 = p1.getX() + INDENT;
final float y1 = p1.getY() + INDENT;
final float x2 = p2.getX() - INDENT;
final float y2 = p2.getY() - INDENT;
final Position startPosition = view.modelToView(MISSILE_CENTERED_IN_MAP_GRID, MISSILE_CENTERED_IN_MAP_GRID);
missileNode.attachChild(view.getApp().getDraw().makeRectangle(startPosition.getX(), startPosition.getY(), MISSILE_DEPTH, p2.getX() - p1.getX(), p2.getY() - p1.getY(), ColorRGBA.DarkGray));
missileNode.setLocalTranslation(startPosition.getX(), startPosition.getY(), MISSILE_DEPTH);
missileNode.addControl(new ShellMapControl(p1, view.getApp(), new IntPoint(shell.getX(), shell.getY())));
return missileNode;
}
/**
* Creates a line geometry representing part of the ship's border.
*
@@ -120,6 +148,7 @@ public Spatial visit(Battleship ship) {
* @return a Geometry representing the line
*/
private Geometry shipLine(float x1, float y1, float x2, float y2, ColorRGBA color) {
LOGGER.log(Logger.Level.DEBUG, "created Ship line");
return view.getApp().getDraw().makeFatLine(x1, y1, x2, y2, SHIP_DEPTH, color, SHIP_LINE_WIDTH);
}
}

View File

@@ -8,8 +8,10 @@
package pp.battleship.client.gui;
import com.jme3.material.Material;
import com.jme3.material.RenderState;
import com.jme3.material.RenderState.BlendMode;
import com.jme3.math.ColorRGBA;
import com.jme3.renderer.queue.RenderQueue;
import com.jme3.renderer.queue.RenderQueue.ShadowMode;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
@@ -18,6 +20,7 @@
import com.jme3.scene.shape.Cylinder;
import pp.battleship.client.BattleshipApp;
import pp.battleship.model.Battleship;
import pp.battleship.model.Shell;
import pp.battleship.model.Rotation;
import pp.battleship.model.ShipMap;
import pp.battleship.model.Shot;
@@ -37,10 +40,14 @@ class SeaSynchronizer extends ShipMapSynchronizer {
private static final String KING_GEORGE_V_MODEL = "Models/KingGeorgeV/KingGeorgeV.j3o";
private static final String UBOAT_MODEL = "Models/UBOAT/14084_WWII_Ship_German_Type_II_U-boat_v2_L1.obj";
private static final String PATROL_BOAT_MODEL = "Models/PATROL_BOAT/12219_boat_v2_L2.obj";
private static final String MODERNBATTLESHIP_MODEL = "Models/BATTLESHIP/10619_Battleship.obj";
private static final String MODERN_BATTLESHIP_MODEL = "Models/BATTLESHIP/10619_Battleship.obj";
private static final String MODERN_BATTLESHIP_TEXTURES = "Models/BATTLESHIP/BattleshipC.jpg";
private static final String MISSILE_MODEL = "Models/Missile/AIM120D.obj";
private static final String MISSILE_TEXTURE = "Models/Missile/texture.png";
private static final String COLOR = "Color"; //NON-NLS
private static final String SHIP = "ship"; //NON-NLS
private static final String SHOT = "shot"; //NON-NLS
private static final String MISSILE = "missile"; //NON-NLS
private static final ColorRGBA BOX_COLOR = ColorRGBA.Gray;
private static final ColorRGBA SPLASH_COLOR = new ColorRGBA(0f, 0f, 1f, 0.4f);
private static final ColorRGBA HIT_COLOR = new ColorRGBA(1f, 0f, 0f, 0.4f);
@@ -136,6 +143,25 @@ public Spatial visit(Battleship ship) {
return node;
}
/**
* Visits a Shell and creates a graphical representation of it.
*
* @param shell the battleship to be represented
* @return the node containing the graphical representation of the battleship
*/
@Override
public Spatial visit(Shell shell) {
final Node node = new Node(MISSILE);
node.attachChild(createMissile());
final float x = shell.getY();
final float z = shell.getX();
node.setLocalTranslation(x+0.5f, 10f, z+0.5f);
node.addControl(new ShellControl(shell, app));
return node;
}
/**
* Creates the appropriate graphical representation of the specified battleship.
* The representation is either a detailed model or a simple box based on the length of the ship.
@@ -213,7 +239,13 @@ private Spatial createBattleship(Battleship ship) {
*/
private Spatial createModernBattleship(Battleship ship) {
final Spatial model = app.getAssetManager().loadModel(MODERNBATTLESHIP_MODEL);
final Spatial model = app.getAssetManager().loadModel(MODERN_BATTLESHIP_MODEL);
Material mat = new Material(app.getAssetManager(), UNSHADED);
mat.setTexture("ColorMap", app.getAssetManager().loadTexture(MODERN_BATTLESHIP_TEXTURES));
mat.getAdditionalRenderState().setBlendMode(RenderState.BlendMode.Off);
model.setMaterial(mat);
model.setQueueBucket(RenderQueue.Bucket.Opaque);
model.rotate(-HALF_PI, calculateRotationAngle(ship.getRot()) + HALF_PI, 0f);
model.scale(0.000075f);
@@ -222,6 +254,30 @@ private Spatial createModernBattleship(Battleship ship) {
return model;
}
/**
* Creates a detailed 3D model to represent a missile.
*
* @return the spatial representing the missile
*/
private Spatial createMissile() {
final Spatial model = app.getAssetManager().loadModel(MISSILE_MODEL);
Material mat = new Material(app.getAssetManager(), UNSHADED);
mat.setTexture("ColorMap", app.getAssetManager().loadTexture(MISSILE_TEXTURE));
mat.getAdditionalRenderState().setBlendMode(RenderState.BlendMode.Off);
model.setMaterial(mat);
model.setQueueBucket(RenderQueue.Bucket.Opaque);
model.rotate(-HALF_PI,0,0);
model.scale(0.009f);
model.setShadowMode(ShadowMode.CastAndReceive);
model.move(0,0f,0);
return model;
}
/**
* Creates a detailed 3D model to represent a Uboat.
*

View File

@@ -0,0 +1,41 @@
package pp.battleship.client.gui;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.control.AbstractControl;
import pp.battleship.client.BattleshipApp;
import pp.battleship.message.client.EndAnimationMessage;
import pp.battleship.model.IntPoint;
import pp.battleship.model.Shell;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
public class ShellControl extends AbstractControl {
private final Shell shell;
private final BattleshipApp app;
private static final float TRAVEL_SPEED = 8.5f;
static final Logger LOGGER = System.getLogger(BattleshipApp.class.getName());
public ShellControl(Shell shell, BattleshipApp app) {
this.shell = shell;
this.app = app;
}
@Override
public void controlUpdate(float tpf) {
//LOGGER.log(Level.DEBUG, "missile at x=" + shell.getX() + ", y=" + shell.getY());
spatial.move(0, -TRAVEL_SPEED*tpf, 0);
if(spatial.getLocalTranslation().getY() <= 0.2){
spatial.getParent().detachChild(spatial);
app.getGameLogic().send(new EndAnimationMessage(new IntPoint(shell.getX(), shell.getY())));
}
}
@Override
protected void controlRender(RenderManager rm, ViewPort vp) {
}
}

View File

@@ -0,0 +1,39 @@
package pp.battleship.client.gui;
import com.jme3.math.Vector3f;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.control.AbstractControl;
import pp.battleship.client.BattleshipApp;
import pp.battleship.message.client.EndAnimationMessage;
import pp.battleship.model.IntPoint;
import pp.util.Position;
public class ShellMapControl extends AbstractControl {
private final Position position;
private final IntPoint pos;
private static final Vector3f vector = new Vector3f();
private final BattleshipApp app;
public ShellMapControl(Position position, BattleshipApp app, IntPoint pos) {
super();
this.position = position;
this.pos = pos;
this.app = app;
vector.set(new Vector3f(position.getX(), position.getY(), 0));
}
@Override
protected void controlUpdate(float tpf) {
spatial.move(vector.mult(tpf));
if (spatial.getLocalTranslation().getX() >= position.getX() && spatial.getLocalTranslation().getY() >= position.getY()) {
spatial.getParent().detachChild(spatial);
app.getGameLogic().send(new EndAnimationMessage(pos));
}
}
@Override
protected void controlRender(RenderManager rm, ViewPort vp) {
}
}

View File

@@ -19,12 +19,15 @@
import pp.battleship.game.server.ServerGameLogic;
import pp.battleship.game.server.ServerSender;
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.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;
import pp.battleship.model.Shot;
@@ -114,11 +117,15 @@ private void initializeSerializables() {
Serializer.registerClass(Battleship.class);
Serializer.registerClass(IntPoint.class);
Serializer.registerClass(Shot.class);
Serializer.registerClass(StartAnimationMessage.class);
Serializer.registerClass(EndAnimationMessage.class);
Serializer.registerClass(SwitchToBattleState.class);
}
private void registerListeners() {
myServer.addMessageListener(this, MapMessage.class);
myServer.addMessageListener(this, ShootMessage.class);
myServer.addMessageListener(this, EndAnimationMessage.class);
myServer.addConnectionListener(this);
}

View File

@@ -0,0 +1,12 @@
# Blender MTL File: 'AIM120D.blend'
# Material Count: 1
newmtl Material.006
Ns 96.078431
Ka 0.000000 0.000000 0.000000
Kd 0.640000 0.640000 0.640000
Ks 0.500000 0.500000 0.500000
Ni 1.000000
d 1.000000
illum 2
map_Kd texture.png

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,2 @@
AIM-120D Missile (Air-to-Air) by https://free3d.com/3d-model/aim-120d-shell-air-to-air-20348.html
License: License for personal use

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 MiB

View File

@@ -0,0 +1,2 @@
Missile firing fl by NHMWretched (https://pixabay.com/sound-effects/missile-firing-fl-106655/)
CCO License

View File

@@ -41,7 +41,7 @@ public static void main(String[] args) {
*/
@Override
public void simpleInitApp() {
export("Models/KingGeorgeV/King_George_V.obj", "KingGeorgeV.j3o"); //NON-NLS
export("Models/KingGeorgeV/King_George_V.obj", "Models/KingGeorgeV/KingGeorgeV.j3o"); //NON-NLS
stop();
}

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
}

View File

@@ -19,12 +19,15 @@
import pp.battleship.game.server.ServerGameLogic;
import pp.battleship.game.server.ServerSender;
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.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;
import pp.battleship.model.Shot;
@@ -118,11 +121,15 @@ private void initializeSerializables() {
Serializer.registerClass(Battleship.class);
Serializer.registerClass(IntPoint.class);
Serializer.registerClass(Shot.class);
Serializer.registerClass(StartAnimationMessage.class);
Serializer.registerClass(EndAnimationMessage.class);
Serializer.registerClass(SwitchToBattleState.class);
}
private void registerListeners() {
myServer.addMessageListener(this, MapMessage.class);
myServer.addMessageListener(this, ShootMessage.class);
myServer.addMessageListener(this, EndAnimationMessage.class);
myServer.addConnectionListener(this);
}