implements shell

This commit is contained in:
Luca Puderbach 2024-10-19 22:50:17 +02:00
parent a798edf07f
commit 04d16a2882
18 changed files with 388316 additions and 33 deletions

2
.gitignore vendored
View File

@ -24,3 +24,5 @@ out
.DS_Store .DS_Store
!Projekte/gradle/wrapper/gradle-wrapper.jar !Projekte/gradle/wrapper/gradle-wrapper.jar
45.j3o
KingGeorge.j3o

View File

@ -34,6 +34,7 @@ public class GameSound extends AbstractAppState implements GameEventListener {
private AudioNode splashSound; private AudioNode splashSound;
private AudioNode shipDestroyedSound; private AudioNode shipDestroyedSound;
private AudioNode explosionSound; private AudioNode explosionSound;
private AudioNode shellFlyingSound;
/** /**
* Checks if sound is enabled in the preferences. * Checks if sound is enabled in the preferences.
@ -78,6 +79,7 @@ public class GameSound extends AbstractAppState implements GameEventListener {
shipDestroyedSound = loadSound(app, "Sound/Effects/sunken.wav"); //NON-NLS shipDestroyedSound = loadSound(app, "Sound/Effects/sunken.wav"); //NON-NLS
splashSound = loadSound(app, "Sound/Effects/splash.wav"); //NON-NLS splashSound = loadSound(app, "Sound/Effects/splash.wav"); //NON-NLS
explosionSound = loadSound(app, "Sound/Effects/explosion.wav"); //NON-NLS explosionSound = loadSound(app, "Sound/Effects/explosion.wav"); //NON-NLS
shellFlyingSound = loadSound(app, "Sound/Effects/shell_flying.wav");
} }
/** /**
@ -123,6 +125,20 @@ public class GameSound extends AbstractAppState implements GameEventListener {
if (isEnabled() && shipDestroyedSound != null) if (isEnabled() && shipDestroyedSound != null)
shipDestroyedSound.playInstance(); shipDestroyedSound.playInstance();
} }
/**
* Plays the shell flying sound effect.
*/
public void shellFly() {
if (isEnabled() && shellFlyingSound != null) {S
shellFlyingSound.playInstance();
}
}
/**
* Handles a recieved {@code SoundEvent} and plays the according sound.
*
* @param event the Sound event to be processed
*/
@Override @Override
public void receivedEvent(SoundEvent event) { public void receivedEvent(SoundEvent event) {

View File

@ -16,6 +16,7 @@ import com.jme3.scene.Geometry;
import com.jme3.scene.Node; import com.jme3.scene.Node;
import com.jme3.scene.Spatial.CullHint; import com.jme3.scene.Spatial.CullHint;
import com.jme3.scene.shape.Quad; import com.jme3.scene.shape.Quad;
import pp.battleship.client.BattleshipApp; import pp.battleship.client.BattleshipApp;
import pp.battleship.model.IntPoint; import pp.battleship.model.IntPoint;
import pp.battleship.model.ShipMap; import pp.battleship.model.ShipMap;
@ -28,7 +29,7 @@ import pp.util.Position;
* and interaction between the model and the view. * and interaction between the model and the view.
*/ */
class MapView { class MapView {
private static final float FIELD_SIZE = 40f; public static final float FIELD_SIZE = 40f;
private static final float GRID_LINE_WIDTH = 2f; private static final float GRID_LINE_WIDTH = 2f;
private static final float BACKGROUND_DEPTH = -4f; private static final float BACKGROUND_DEPTH = -4f;
private static final float GRID_DEPTH = -1f; private static final float GRID_DEPTH = -1f;

View File

@ -10,10 +10,16 @@ package pp.battleship.client.gui;
import com.jme3.math.ColorRGBA; import com.jme3.math.ColorRGBA;
import com.jme3.scene.Geometry; import com.jme3.scene.Geometry;
import com.jme3.scene.Node; import com.jme3.scene.Node;
import com.jme3.material.Material;
import com.jme3.material.RenderState;
import com.jme3.material.RenderState.BlendMode;
import com.jme3.scene.shape.Sphere;
import com.jme3.scene.Spatial; import com.jme3.scene.Spatial;
import pp.battleship.model.Battleship; import pp.battleship.model.Battleship;
import pp.battleship.model.Shot; import pp.battleship.model.Shot;
import pp.util.Position; import pp.util.Position;
import static com.jme3.material.Materials.UNSHADED;
/** /**
* Synchronizes the visual representation of the ship map with the game model. * Synchronizes the visual representation of the ship map with the game model.
@ -109,6 +115,8 @@ class MapViewSynchronizer extends ShipMapSynchronizer {
return shipNode; return shipNode;
} }
/** /**
* Creates a line geometry representing part of the ship's border. * Creates a line geometry representing part of the ship's border.
* *
@ -122,4 +130,24 @@ class MapViewSynchronizer extends ShipMapSynchronizer {
private Geometry shipLine(float x1, float y1, float x2, float y2, ColorRGBA color) { private Geometry shipLine(float x1, float y1, float x2, float y2, ColorRGBA color) {
return view.getApp().getDraw().makeFatLine(x1, y1, x2, y2, SHIP_DEPTH, color, SHIP_LINE_WIDTH); return view.getApp().getDraw().makeFatLine(x1, y1, x2, y2, SHIP_DEPTH, color, SHIP_LINE_WIDTH);
} }
/**
* Creates and returns a Spatial representation of the given {@code Shell} object
* for 2D visualization in the game. The shell is represented as a circle.
*
* @param shell The {@code Shell} object to be visualized.
* @return A {@code Spatial} object representing the shell on the map.
*/
@Override
public Spatial visit(Shell shell) {
final ColorRGBA color = ColorRGBA.Black;
Geometry ellipse = new Geometry("ellipse", new Sphere(50, 50, MapView.FIELD_SIZE / 2 * 0.8f));
Material mat = new Material(view.getApp().getAssetManager(), UNSHADED); //NON-NLS
mat.getAdditionalRenderState().setBlendMode(BlendMode.Alpha);
mat.getAdditionalRenderState().setFaceCullMode(RenderState.FaceCullMode.Off);
mat.setColor("Color", color);
ellipse.setMaterial(mat);
ellipse.addControl(new Shell2DControl(view, shell));
return ellipse;
}
} }

View File

@ -28,6 +28,7 @@ import pp.battleship.model.Battleship;
import pp.battleship.model.Rotation; import pp.battleship.model.Rotation;
import pp.battleship.model.ShipMap; import pp.battleship.model.ShipMap;
import pp.battleship.model.Shot; import pp.battleship.model.Shot;
import pp.battleship.model.Shell;
import static pp.util.FloatMath.HALF_PI; import static pp.util.FloatMath.HALF_PI;
import static pp.util.FloatMath.PI; import static pp.util.FloatMath.PI;
@ -384,4 +385,25 @@ class SeaSynchronizer extends ShipMapSynchronizer {
case UP -> PI; case UP -> PI;
}; };
} }
/**
* Creates and returns a 3D model representation of the given {@code Shell} object
* for visualization in the game.
*
* @param shell The {@code Shell} object to be visualized.
* @return A {@code Spatial} object representing the 3D model of the shell.
*/
@Override
public Spatial visit(Shell shell) {
final Spatial model = app.getAssetManager().loadModel("Models/Shell/shell.j3o");
model.setLocalScale(.05f);
model.setShadowMode(ShadowMode.CastAndReceive);
Material mat = new Material(app.getAssetManager(), LIGHTING);
mat.setTexture("DiffuseMap", app.getAssetManager().loadTexture("Models/Shell/shell_color.png"));
mat.setReceivesShadows(true);
model.setMaterial(mat);
model.addControl(new ShellControl(shell));
return model;
}
} }

View File

@ -0,0 +1,49 @@
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.model.Shell;
import pp.util.Position;
/**
* Controls the 2D representation of a {@code Shell} in the game, updating its position
* based on the shell's current state in the game model. The {@code Shell2DControl} class
* is responsible for translating the shell's 3D position to a 2D view position within
* the game's map view.
*/
public class Shell2DControl extends AbstractControl {
private final Shell shell;
private final MapView view;
/**
* Constructs a new {@code Shell2DControl} to manage the 2D visualization of the given {@code Shell}.
*
* @param view The {@code MapView} used to get information about the map to display.
* @param shell The {@code Shell} being visualized.
*/
public Shell2DControl(MapView view, Shell shell){
this.shell = shell;
this.view = view;
}
/**
* Updates the position of the shell's 2D representation based on the shell's current
* 3D position in the game model. The position is mapped from model space to view space
* coordinates and translated to the appropriate location within the {@code MapView}.
*
* @param tpf Time per frame, representing the time elapsed since the last frame.
*/
@Override
protected void controlUpdate(float tpf) {
Vector3f shellPos = shell.getPosition();
Position viewPos = view.modelToView(shellPos.x, shellPos.z);
spatial.setLocalTranslation(viewPos.getX() + MapView.FIELD_SIZE / 2, viewPos.getY() + MapView.FIELD_SIZE / 2, 0);
}
@Override
protected void controlRender(RenderManager rm, ViewPort vp) {
// No rendering-specific behavior required for this control
}
}

View File

@ -0,0 +1,50 @@
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.model.Shell;
import static pp.util.FloatMath.PI;
/**
* Controls the 3D representation of a {@code Shell} in the game, updating its position
* and rotation based on the shell's current state in the game model. The {@code ShellControl}
* class ensures that the spatial associated with the shell is positioned and oriented correctly
* within the world.
*/
public class ShellControl extends AbstractControl {
private final Shell shell;
/**
* Constructs a new {@code ShellControl} to manage the 3D visualization of the given {@code Shell}.
*
* @param shell The {@code Shell} being visualized and controlled.
*/
public ShellControl(Shell shell){
super();
this.shell = shell;
}
/**
* Updates the 3D position and rotation of the shell based on its current state.
* Converts map coordinates to world coordinates and applies the shell's orientation.
*
* @param tpf Time per frame, representing the elapsed time since the last update.
*/
@Override
protected void controlUpdate(float tpf) {
Vector3f pos = shell.getPosition();
Vector3f fixed = new Vector3f(pos.z + 0.5f, pos.y, pos.x + 0.5f);
fixed.setY(pos.y);
spatial.setLocalTranslation(fixed);
spatial.setLocalRotation(shell.getRotation());
spatial.rotate(PI/2,0,0);
}
@Override
protected void controlRender(RenderManager rm, ViewPort vp) {
// No rendering-specific behavior required for this control
}
}

View File

@ -15,7 +15,7 @@ import com.jme3.scene.control.AbstractControl;
*/ */
public class SinkingShip extends AbstractControl { public class SinkingShip extends AbstractControl {
private float elapsedTime = 0f; private float elapsedTime = 0.2f;
private final float burnTiltDuration; private final float burnTiltDuration;
private final float sinkDuration; private final float sinkDuration;
private final float sinkDepth; private final float sinkDepth;
@ -79,7 +79,7 @@ public class SinkingShip extends AbstractControl {
// Apply the tilt angle (remains constant during sinking) // Apply the tilt angle (remains constant during sinking)
float sinkingTiltAngle = FastMath.DEG_TO_RAD * tiltAngle * progress; float sinkingTiltAngle = FastMath.DEG_TO_RAD * tiltAngle * progress;
float sinkingRotationAngle = FastMath.DEG_TO_RAD * 45f * progress; // Additional rotation during sinking float sinkingRotationAngle = FastMath.DEG_TO_RAD * 45f * progress; // Additional rotation during sinking (test)
Quaternion tiltRotation = new Quaternion().fromAngles(-sinkingTiltAngle, sinkingRotationAngle, sinkingRotationAngle); Quaternion tiltRotation = new Quaternion().fromAngles(-sinkingTiltAngle, sinkingRotationAngle, sinkingRotationAngle);
spatial.setLocalRotation(tiltRotation); spatial.setLocalRotation(tiltRotation);
@ -94,6 +94,28 @@ public class SinkingShip extends AbstractControl {
} }
spatial.removeControl(this); spatial.removeControl(this);
} }
// public void checkAndTriggerExplosion() {
// // Prüfen, ob das sinkende Schiff den Boden erreicht hat
// if (spatial != null && spatial.getLocalTranslation().y <= sinkDepth) {
// // Explosion ausführen, wenn der Boden erreicht ist
// triggerExplosionAnimation();
//
// // Entfernen des Schiffs aus dem Elternknoten
// Node parentNode = (Node) spatial.getParent();
// if (parentNode != null) {
// parentNode.detachChild(spatial);
// }
//
// // Entfernen der Kontrolle vom Spatial
// spatial.removeControl(this);
// }
// }
//
// private void triggerExplosionAnimation() {
// // Code für die Explosion-Animation (alibi Methode)
// System.out.println("Explosion wird ausgeführt: Das Schiff hat den Boden erreicht!");
// // Hier könnte eine echte Animation eingefügt werden, z.B. Partikeleffekte
// }
} }
/** /**

View File

@ -1,4 +1,11 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.client.server; package pp.battleship.client.server;
import pp.battleship.message.client.ClientInterpreter; import pp.battleship.message.client.ClientInterpreter;
@ -9,4 +16,3 @@ record ReceivedMessageSelfhost(ClientMessage message, int from) {
message.accept(interpreter, from); message.accept(interpreter, from);
} }
} }

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 17 KiB

View File

@ -34,8 +34,8 @@ public class ModelExporter extends SimpleApplication {
*/ */
@Override @Override
public void simpleInitApp() { public void simpleInitApp() {
export("Models/KingGeorge.obj", "KingGeorge.j3o");//NON-NLS passt export("Models/45.obj", "45.j3o");//NON-NLS passt
//export("Models/Wing.obj", "Wing.j3o"); //export("Models/.j3o");
// export("Models/Transporter/Transporter.obj", "Transporter.j3o"); //NON-NLS passt // export("Models/Transporter/Transporter.obj", "Transporter.j3o"); //NON-NLS passt
// export("Models/TieFighter.obj", "TieFighter.j3o"); //NON-NLS // export("Models/TieFighter.obj", "TieFighter.j3o"); //NON-NLS
// export("Models/Venator/Venator.obj", "Venator.j3o"); //NON-NLS kickt // export("Models/Venator/Venator.obj", "Venator.j3o"); //NON-NLS kickt

File diff suppressed because it is too large Load Diff

View File

@ -14,6 +14,7 @@ import pp.battleship.message.server.EffectMessage;
import pp.battleship.model.IntPoint; import pp.battleship.model.IntPoint;
import pp.battleship.model.ShipMap; import pp.battleship.model.ShipMap;
import pp.battleship.notification.Sound; import pp.battleship.notification.Sound;
import pp.battleship.model.Shell;
/** /**
* Represents the state of the client where players take turns to attack each other's ships. * Represents the state of the client where players take turns to attack each other's ships.
@ -53,16 +54,13 @@ class BattleState extends ClientState {
@Override @Override
public void receivedEffect(EffectMessage msg) { public void receivedEffect(EffectMessage msg) {
ClientGameLogic.LOGGER.log(Level.INFO, "report effect: {0}", msg); //NON-NLS ClientGameLogic.LOGGER.log(Level.INFO, "report effect: {0}", msg); //NON-NLS
playSound(msg);
myTurn = msg.isMyTurn(); myTurn = msg.isMyTurn();
logic.setInfoText(msg.getInfoTextKey()); logic.setInfoText(msg.getInfoTextKey());
affectedMap(msg).add(msg.getShot()); Shell shell = new Shell(msg.getShot());
if (destroyedOpponentShip(msg)) affectedMap(msg).add(shell);
logic.getOpponentMap().add(msg.getDestroyedShip()); logic.playSound(Sound.SHELL_FLYING);
if (msg.isGameOver()) { logic.setState(new ShootingState(logic, shell, myTurn, msg));
msg.getRemainingOpponentShips().forEach(logic.getOpponentMap()::add);
logic.setState(new GameOverState(logic));
}
} }
/** /**
@ -81,22 +79,4 @@ class BattleState extends ClientState {
* @param msg the effect message received from the server * @param msg the effect message received from the server
* @return true if the shot destroyed an opponent's ship, false otherwise * @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

@ -0,0 +1,114 @@
package pp.battleship.game.client;
import pp.battleship.message.client.AnimationFinishedMessage;
import pp.battleship.message.server.EffectMessage;
import pp.battleship.model.Battleship;
import pp.battleship.model.Shell;
import pp.battleship.model.ShipMap;
import pp.battleship.notification.Sound;
/**
* Represents the shooting state of the game where a shell is fired at the opponent.
*/
public class ShootingState extends ClientState {
private float shootValue;
private final static float SHELL_SPEED = 0.3f;
private final Shell shell;
private final boolean myTurn;
private final EffectMessage msg;
/**
* Constructs a shooting state with the specified game logic.
*
* @param logic the game logic
* @param shell the shell being shot
* @param myTurn indicates if it is the player's turn
* @param msg the effect message associated with the shooting action
*/
public ShootingState(ClientGameLogic logic, Shell shell, boolean myTurn, EffectMessage msg) {
super(logic);
this.msg = msg;
this.myTurn = myTurn;
this.shell = shell;
this.shootValue = 0;
shell.move(shootValue);
}
@Override
public boolean showBattle() {
return true;
}
/**
* Updates the shooting state by moving the shell based on the elapsed time.
*
* @param delta the time in seconds since the last update
*/
@Override
void update(float delta) {
super.update(delta);
if (shootValue > 1) {
endState();
}
else {
shootValue += delta * SHELL_SPEED;
shell.move(shootValue);
}
}
/**
* Ends the shooting state and processes the effects of the shot.
*/
private void endState() {
playSound(msg);
affectedMap(msg).add(msg.getShot());
affectedMap(msg).remove(shell);
if (destroyedOpponentShip(msg))
logic.getOpponentMap().add(msg.getDestroyedShip());
if (msg.isGameOver()) {
for (Battleship ship : msg.getRemainingOpponentShips()) {
logic.getOpponentMap().add(ship);
}
logic.setState(new GameOverState(logic));
return;
}
logic.send(new AnimationFinishedMessage());
logic.setState(new BattleState(logic, myTurn));
}
/**
* Checks if an opponent's ship was destroyed by the shot.
*
* @param msg the effect message containing the shot details
* @return true if an opponent's ship was destroyed, false otherwise
*/
private boolean destroyedOpponentShip(EffectMessage msg) {
return msg.getDestroyedShip() != null && msg.isOwnShot();
}
/**
* Retrieves the affected map based on whether the shot was owned by the player or the opponent.
*
* @param msg the effect message containing shot details
* @return the ShipMap that was affected by the shot
*/
private ShipMap affectedMap(EffectMessage msg) {
return msg.isOwnShot() ? logic.getOpponentMap() : logic.getOwnMap();
}
/**
* 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

@ -24,6 +24,7 @@ import pp.battleship.message.server.ServerMessage;
import pp.battleship.message.server.StartBattleMessage; import pp.battleship.message.server.StartBattleMessage;
import pp.battleship.model.Battleship; import pp.battleship.model.Battleship;
import pp.battleship.model.IntPoint; import pp.battleship.model.IntPoint;
import pp.battleship.message.client.AnimationFinishedMessage;
/** /**
* Controls the server-side game logic for Battleship. * Controls the server-side game logic for Battleship.
@ -38,6 +39,7 @@ public class ServerGameLogic implements ClientInterpreter {
private final ServerSender serverSender; private final ServerSender serverSender;
private Player activePlayer; private Player activePlayer;
private ServerState state = ServerState.WAIT; private ServerState state = ServerState.WAIT;
private Set<Player> waitPlayers = new HashSet<>();
/** /**
* Constructs a ServerGameLogic with the specified sender and configuration. * Constructs a ServerGameLogic with the specified sender and configuration.