22 Commits

Author SHA1 Message Date
Luca Puderbach
fe41a67341 add missing pic :/ 2024-10-20 04:44:12 +02:00
Luca Puderbach
842eabd32e fixed shell pos 2024-10-20 04:33:40 +02:00
Luca Puderbach
e4a24c3070 fixing shell 2024-10-20 04:30:57 +02:00
Luca Puderbach
04d16a2882 implements shell 2024-10-19 22:50:17 +02:00
Luca Puderbach
a798edf07f add spinning drop 2024-10-14 06:30:01 +02:00
Luca Puderbach
5dff2c271f fixing effects 2024-10-14 06:02:20 +02:00
Luca Puderbach
b6642a4815 add img sinking eff 2024-10-14 05:12:56 +02:00
Luca Puderbach
33dba7f3b6 more fixing things 2024-10-14 04:38:01 +02:00
Luca Puderbach
96992c5b03 fixing server host 2024-10-14 04:25:55 +02:00
Luca Puderbach
c525a8994c "redo" task11 (black screen) 2024-10-14 04:17:43 +02:00
Luca Puderbach
86a3d90bf8 clean up 2024-10-14 04:08:26 +02:00
Luca Puderbach
a6fec62fa0 neue modelle + fixing 2024-10-14 03:01:55 +02:00
Luca Puderbach
b8cd71120f implement server start from client 2024-10-13 21:02:20 +02:00
Luca Puderbach
fc22ae1819 add and convert 3d models 2024-10-13 18:11:11 +02:00
Luca Puderbach
f27ec36d2b add bgmusic 2024-10-13 17:44:13 +02:00
Luca Puderbach
68e252e174 add slider + update menu 2024-10-13 17:42:31 +02:00
Luca Puderbach
b33ddcb2c2 insert bgmusic 2024-10-13 17:41:40 +02:00
Luca Puderbach
3386d395fe testValidMap 2024-10-10 20:31:21 +02:00
Luca Puderbach
91b24db6ca getPosition() 2024-10-10 20:30:34 +02:00
Luca Puderbach
0ff5fceae7 neue maps erstellt, 2->3. map2 out of bound, map4 overlaping 2024-10-06 17:34:57 +02:00
Luca Puderbach
f6699c2a0a own->opponent 2024-10-06 15:20:18 +02:00
Luca Puderbach
9ca08c3d0c added -> removed 2024-10-06 00:53:15 +02:00
80 changed files with 475817 additions and 31699 deletions

2
.gitignore vendored
View File

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

View File

@@ -73,8 +73,7 @@ Betriebssystem:
die Zeile:
`export JAVA_HOME="<Pfad zum entpackten Archiv>"`
Ersetzen Sie dabei `<Pfad zum entpackten Archiv>` mit dem entsprechenden Pfad.
cd Ersetzen Sie dabei `<Pfad zum entpackten Archiv>` mit dem entsprechenden Pfad.
Zum Beispiel:
`export JAVA_HOME="/home/user/jdk-20.0.2"`

View File

@@ -7,8 +7,15 @@ description = 'Battleship Client'
dependencies {
implementation project(":jme-common")
implementation project(":battleship:model")
implementation 'org.jmonkeyengine:jme3-core:3.6.0-stable'
implementation 'org.jmonkeyengine:jme3-effects:3.6.0-stable'
implementation libs.jme3.desktop
implementation project(path: ':battleship:server')
implementation project(path: ':battleship:server')
runtimeOnly libs.jme3.awt.dialogs
runtimeOnly libs.jme3.plugins

View File

@@ -23,7 +23,7 @@
{
"length": 2,
"x": 4,
"y": 8,
"y": 12,
"rot": "RIGHT"
},
{

View File

@@ -0,0 +1,66 @@
{
"width": 10,
"height": 10,
"ships": [
{
"length": 4,
"x": 0,
"y": 5,
"rot": "DOWN"
},
{
"length": 3,
"x": 0,
"y": 9,
"rot": "DOWN"
},
{
"length": 3,
"x": 2,
"y": 6,
"rot": "RIGHT"
},
{
"length": 2,
"x": 4,
"y": 8,
"rot": "RIGHT"
},
{
"length": 2,
"x": 2,
"y": 4,
"rot": "DOWN"
},
{
"length": 2,
"x": 2,
"y": 1,
"rot": "DOWN"
},
{
"length": 1,
"x": 6,
"y": 2,
"rot": "RIGHT"
},
{
"length": 1,
"x": 8,
"y": 2,
"rot": "RIGHT"
},
{
"length": 1,
"x": 6,
"y": 0,
"rot": "RIGHT"
},
{
"length": 1,
"x": 8,
"y": 0,
"rot": "RIGHT"
}
]
}

View File

@@ -0,0 +1,66 @@
{
"width": 10,
"height": 10,
"ships": [
{
"length": 4,
"x": 0,
"y": 5,
"rot": "DOWN"
},
{
"length": 3,
"x": 0,
"y": 4,
"rot": "DOWN"
},
{
"length": 3,
"x": 2,
"y": 6,
"rot": "RIGHT"
},
{
"length": 2,
"x": 4,
"y": 8,
"rot": "RIGHT"
},
{
"length": 2,
"x": 2,
"y": 4,
"rot": "DOWN"
},
{
"length": 2,
"x": 2,
"y": 1,
"rot": "DOWN"
},
{
"length": 1,
"x": 6,
"y": 2,
"rot": "RIGHT"
},
{
"length": 1,
"x": 8,
"y": 2,
"rot": "RIGHT"
},
{
"length": 1,
"x": 6,
"y": 0,
"rot": "RIGHT"
},
{
"length": 1,
"x": 8,
"y": 0,
"rot": "RIGHT"
}
]
}

View File

@@ -7,6 +7,15 @@
package pp.battleship.client;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.LogManager;
import com.jme3.app.DebugKeysAppState;
import com.jme3.app.SimpleApplication;
import com.jme3.app.StatsAppState;
@@ -20,7 +29,10 @@ import com.jme3.input.controls.MouseButtonTrigger;
import com.jme3.system.AppSettings;
import com.simsilica.lemur.GuiGlobals;
import com.simsilica.lemur.style.BaseStyles;
import static pp.battleship.Resources.lookup;
import pp.battleship.client.gui.BattleAppState;
import pp.battleship.client.gui.BgMusic;
import pp.battleship.client.gui.EditorAppState;
import pp.battleship.client.gui.SeaAppState;
import pp.battleship.game.client.BattleshipClient;
@@ -35,17 +47,6 @@ import pp.dialog.DialogBuilder;
import pp.dialog.DialogManager;
import pp.graphics.Draw;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.LogManager;
import static pp.battleship.Resources.lookup;
/**
* The main class for the Battleship client application.
* It manages the initialization, input setup, GUI setup, and game states for the client.
@@ -268,6 +269,7 @@ public class BattleshipApp extends SimpleApplication implements BattleshipClient
attachGameSound();
stateManager.attachAll(new EditorAppState(), new BattleAppState(), new SeaAppState());
attachBgMusic();
}
/**
@@ -279,6 +281,12 @@ public class BattleshipApp extends SimpleApplication implements BattleshipClient
gameSound.setEnabled(GameSound.enabledInPreferences());
stateManager.attach(gameSound);
}
private void attachBgMusic() {
final BgMusic gameSound = new BgMusic();
gameSound.setEnabled(BgMusic.enabledInPreferences());
stateManager.attach(gameSound);
}
/**
* Updates the application state every frame.

View File

@@ -7,6 +7,10 @@
package pp.battleship.client;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import java.util.prefs.Preferences;
import com.jme3.app.Application;
import com.jme3.app.state.AbstractAppState;
import com.jme3.app.state.AppStateManager;
@@ -14,13 +18,9 @@ import com.jme3.asset.AssetLoadException;
import com.jme3.asset.AssetNotFoundException;
import com.jme3.audio.AudioData;
import com.jme3.audio.AudioNode;
import pp.battleship.notification.GameEventListener;
import pp.battleship.notification.SoundEvent;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import java.util.prefs.Preferences;
import static pp.util.PreferencesUtils.getPreferences;
/**

View File

@@ -7,21 +7,25 @@
package pp.battleship.client;
import com.simsilica.lemur.Button;
import com.simsilica.lemur.Checkbox;
import com.simsilica.lemur.Label;
import com.simsilica.lemur.style.ElementId;
import pp.dialog.Dialog;
import pp.dialog.StateCheckboxModel;
import pp.dialog.TextInputDialog;
import java.io.File;
import java.io.IOException;
import java.util.prefs.Preferences;
import com.simsilica.lemur.Button;
import com.simsilica.lemur.Checkbox;
import com.simsilica.lemur.Label;
import com.simsilica.lemur.style.ElementId;
import static pp.battleship.Resources.lookup;
import pp.battleship.client.gui.BgMusic;
import pp.battleship.client.gui.VolumeSlider;
import pp.dialog.Dialog;
import pp.dialog.StateCheckboxModel;
import pp.dialog.TextInputDialog;
import static pp.util.PreferencesUtils.getPreferences;
/**
* The Menu class represents the main menu in the Battleship game application.
* It extends the Dialog class and provides functionalities for loading, saving,
@@ -33,6 +37,7 @@ class Menu extends Dialog {
private final BattleshipApp app;
private final Button loadButton = new Button(lookup("menu.map.load"));
private final Button saveButton = new Button(lookup("menu.map.save"));
private final VolumeSlider slider;
/**
* Constructs the Menu dialog for the Battleship application.
@@ -42,9 +47,16 @@ class Menu extends Dialog {
public Menu(BattleshipApp app) {
super(app.getDialogManager());
this.app = app;
slider = new VolumeSlider(app.getStateManager().getState(BgMusic.class));
addChild(new Label(lookup("battleship.name"), new ElementId("header"))); //NON-NLS
addChild(new Checkbox(lookup("menu.sound-enabled"),
new StateCheckboxModel(app, GameSound.class)));
// addChild(new Checkbox(lookup("menu.sound-enabled"),
// new StateCheckboxModel(app, GameSound.class)));
addChild(new Checkbox(lookup("menu.sound-enabled"), new StateCheckboxModel(app, GameSound.class)));
addChild(new Checkbox(lookup("menu.background-sound-enabled"), new StateCheckboxModel(app, BgMusic.class)));
addChild(slider);
addChild(loadButton)
.addClickCommands(s -> ifTopDialog(this::loadDialog));
addChild(saveButton)
@@ -64,6 +76,10 @@ class Menu extends Dialog {
loadButton.setEnabled(app.getGameLogic().mayLoadMap());
saveButton.setEnabled(app.getGameLogic().maySaveMap());
}
@Override
public void update(float delta) {
slider.update();
}
/**
* As an escape action, this method closes the menu if it is the top dialog.

View File

@@ -7,20 +7,22 @@
package pp.battleship.client;
import com.simsilica.lemur.Container;
import com.simsilica.lemur.Label;
import com.simsilica.lemur.TextField;
import com.simsilica.lemur.component.SpringGridLayout;
import pp.dialog.Dialog;
import pp.dialog.DialogBuilder;
import pp.dialog.SimpleDialog;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import com.simsilica.lemur.Checkbox;
import com.simsilica.lemur.Container;
import com.simsilica.lemur.Label;
import com.simsilica.lemur.TextField;
import com.simsilica.lemur.component.SpringGridLayout;
import static pp.battleship.Resources.lookup;
import pp.battleship.client.server.BattleshipSelfhostServer;
import pp.dialog.Dialog;
import pp.dialog.DialogBuilder;
import pp.dialog.SimpleDialog;
/**
* Represents a dialog for setting up a network connection in the Battleship game.
@@ -33,6 +35,7 @@ class NetworkDialog extends SimpleDialog {
private final NetworkSupport network;
private final TextField host = new TextField(LOCALHOST);
private final TextField port = new TextField(DEFAULT_PORT);
private static final Checkbox HOST = new Checkbox(lookup("server.host"));
private String hostname;
private int portNumber;
private Future<Object> connectionFuture;
@@ -56,6 +59,7 @@ class NetworkDialog extends SimpleDialog {
input.addChild(host, 1);
input.addChild(new Label(lookup("port.number") + ": "));
input.addChild(port, 1);
input.addChild(HOST).addClickCommands(s -> ifTopDialog(this::startClientServer));
DialogBuilder.simple(app.getDialogManager())
.setTitle(lookup("server.dialog"))
@@ -150,4 +154,21 @@ class NetworkDialog extends SimpleDialog {
network.getApp().errorDialog(lookup("server.connection.failed"));
network.getApp().setInfoText(e.getLocalizedMessage());
}
/**
* Starts the server of the client in a new thread and catches connectivity issues.
*/
private void startClientServer() {
HOST.setEnabled(false);
Thread serverThread = new Thread(() -> {
try {
BattleshipSelfhostServer.main(null);
} catch (Exception e) {
HOST.setEnabled(true);
LOGGER.log(Level.ERROR, "Server could not be started", e);
network.getApp().errorDialog("Could not start server: " + e.getMessage());
}
});
serverThread.start();
}
}

View File

@@ -0,0 +1,121 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.client.gui;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import java.util.prefs.Preferences;
import com.jme3.app.Application;
import com.jme3.app.state.AbstractAppState;
import com.jme3.app.state.AppStateManager;
import com.jme3.asset.AssetLoadException;
import com.jme3.asset.AssetNotFoundException;
import com.jme3.audio.AudioData;
import com.jme3.audio.AudioNode;
import static pp.util.PreferencesUtils.getPreferences;
/**
* An application state that plays sounds.
*/
public class BgMusic extends AbstractAppState{
private static final Logger LOGGER = System.getLogger(BgMusic.class.getName());
private static final Preferences PREFERENCES = getPreferences(BgMusic.class);
private static final String ENABLED_PREF = "enabled"; //NON-NLS
private static final String VOLUME_PREF = "volume"; //NON-NLS
private AudioNode music;
/**
* Checks if sound is enabled in the preferences.
*
* @return {@code true} if sound is enabled, {@code false} otherwise.
*/
public static boolean enabledInPreferences() {
return PREFERENCES.getBoolean(ENABLED_PREF, true);
}
/**
* Checks if sound is enabled in the preferences.
*
* @return //TODO
*/
public static float volumeInPreferences() {
return PREFERENCES.getFloat(VOLUME_PREF, 0.5f);
}
/**
* Initializes the sound effects for the game.
* Overrides {@link AbstractAppState#initialize(AppStateManager, Application)}
*
* @param stateManager The state manager
* @param app The application
*/
@Override
public void initialize(AppStateManager stateManager, Application app) {
super.initialize(stateManager, app);
music = loadSound(app, "Sound/Music/bgMusic.ogg");
setVolume(volumeInPreferences());
music.setLooping(true);
if (isEnabled() && music != null) {
music.play();
}
}
/**
* Loads a sound from the specified file.
*
* @param app The application
* @param name The name of the sound file.
* @return The loaded AudioNode.
*/
private AudioNode loadSound(Application app, String name) {
try {
final AudioNode sound = new AudioNode(app.getAssetManager(), name, AudioData.DataType.Buffer);
sound.setLooping(false);
sound.setPositional(false);
return sound;
}
catch (AssetLoadException | AssetNotFoundException ex) {
LOGGER.log(Level.ERROR, ex.getMessage(), ex);
}
return null;
}
/** TODO
* Sets the enabled state of this AppState.
* Overrides {@link com.jme3.app.state.AbstractAppState#setEnabled(boolean)}
*
* @param enabled {@code true} to enable the AppState, {@code false} to disable it.
*/
@Override
public void setEnabled(boolean enabled) {
if (isEnabled() == enabled) return;
else if(!isEnabled() && enabled) {
if (music != null) music.play();
} else if (isEnabled() && !enabled) {
if (music != null) music.stop();
}
super.setEnabled(enabled);
LOGGER.log(Level.INFO, "Sound enabled: {0}", enabled); //NON-NLS
PREFERENCES.putBoolean(ENABLED_PREF, enabled);
}
/**
* Toggles the game sound on or off.
*/
public void toggleSound() {
setEnabled(!isEnabled());
}
public void setVolume(float vol){
music.setVolume(vol);
PREFERENCES.putFloat(VOLUME_PREF, vol);
}
}

View File

@@ -7,19 +7,19 @@
package pp.battleship.client.gui;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import com.jme3.input.controls.ActionListener;
import com.jme3.math.Vector2f;
import com.jme3.scene.Node;
import com.jme3.system.AppSettings;
import com.simsilica.lemur.Button;
import com.simsilica.lemur.Container;
import pp.battleship.client.BattleshipAppState;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import static pp.battleship.Resources.lookup;
import static pp.battleship.client.BattleshipApp.CLICK;
import pp.battleship.client.BattleshipAppState;
/**
* EditorState manages the editor mode in the Battleship game,

View File

@@ -16,6 +16,7 @@ import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial.CullHint;
import com.jme3.scene.shape.Quad;
import pp.battleship.client.BattleshipApp;
import pp.battleship.model.IntPoint;
import pp.battleship.model.ShipMap;
@@ -28,7 +29,7 @@ import pp.util.Position;
* and interaction between the model and the view.
*/
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 BACKGROUND_DEPTH = -4f;
private static final float GRID_DEPTH = -1f;

View File

@@ -7,11 +7,18 @@
package pp.battleship.client.gui;
import com.jme3.material.Material;
import static com.jme3.material.Materials.UNSHADED;
import com.jme3.material.RenderState;
import com.jme3.material.RenderState.BlendMode;
import com.jme3.math.ColorRGBA;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import com.jme3.scene.shape.Sphere;
import pp.battleship.model.Battleship;
import pp.battleship.model.Shell;
import pp.battleship.model.Shot;
import pp.util.Position;
@@ -109,6 +116,8 @@ class MapViewSynchronizer extends ShipMapSynchronizer {
return shipNode;
}
/**
* Creates a line geometry representing part of the ship's border.
*
@@ -122,4 +131,24 @@ class MapViewSynchronizer extends ShipMapSynchronizer {
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);
}
/**
* 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

@@ -0,0 +1,283 @@
package pp.battleship.client.gui;
import com.jme3.effect.ParticleEmitter;
import com.jme3.effect.ParticleMesh.Type;
import com.jme3.effect.shapes.EmitterSphereShape;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.FastMath;
import com.jme3.math.Vector3f;
import pp.battleship.client.BattleshipApp;
/**
* Factory class responsible for creating particle effects used in the game.
* This centralizes the creation of various types of particle emitters.
*/
public class ParticleEffectFactory {
private static final int COUNT_FACTOR = 1;
private static final float COUNT_FACTOR_F = 1f;
private static final boolean POINT_SPRITE = true;
private static final Type EMITTER_TYPE = POINT_SPRITE ? Type.Point : Type.Triangle;
private final BattleshipApp app;
ParticleEffectFactory(BattleshipApp app) {
this.app = app;
}
/**
* Creates a flame particle emitter.
*
* @return a configured flame particle emitter
*/
ParticleEmitter createFlame() {
ParticleEmitter flame = new ParticleEmitter("Flame", EMITTER_TYPE, 32 * COUNT_FACTOR);
flame.setSelectRandomImage(true);
flame.setStartColor(new ColorRGBA(1f, 0.4f, 0.05f, (1f / COUNT_FACTOR_F)));
flame.setEndColor(new ColorRGBA(.4f, .22f, .12f, 0f));
flame.setStartSize(0.1f);
flame.setEndSize(0.5f);
flame.setShape(new EmitterSphereShape(Vector3f.ZERO, 1f));
flame.setParticlesPerSec(0);
flame.setGravity(0, -5, 0);
flame.setLowLife(.4f);
flame.setHighLife(.5f);
flame.getParticleInfluencer().setInitialVelocity(new Vector3f(0, 7, 0));
flame.getParticleInfluencer().setVelocityVariation(1f);
flame.setImagesX(2);
flame.setImagesY(2);
Material mat = new Material(app.getAssetManager(), "Common/MatDefs/Misc/Particle.j3md");
mat.setTexture("Texture", app.getAssetManager().loadTexture("Effects/Explosion/flame.png"));
mat.setBoolean("PointSprite", POINT_SPRITE);
flame.setMaterial(mat);
return flame;
}
/**
* Creates a flash particle emitter.
*
* @return a configured flash particle emitter
*/
ParticleEmitter createFlash() {
ParticleEmitter flash = new ParticleEmitter("Flash", EMITTER_TYPE, 24 * COUNT_FACTOR);
flash.setSelectRandomImage(true);
flash.setStartColor(new ColorRGBA(1f, 0.8f, 0.36f, 1f / COUNT_FACTOR_F));
flash.setEndColor(new ColorRGBA(1f, 0.8f, 0.36f, 0f));
flash.setStartSize(.1f);
flash.setEndSize(0.5f);
flash.setShape(new EmitterSphereShape(Vector3f.ZERO, .05f));
flash.setParticlesPerSec(0);
flash.setGravity(0, 0, 0);
flash.setLowLife(.2f);
flash.setHighLife(.2f);
flash.getParticleInfluencer().setInitialVelocity(new Vector3f(0, 5f, 0));
flash.getParticleInfluencer().setVelocityVariation(1);
flash.setImagesX(2);
flash.setImagesY(2);
Material mat = new Material(app.getAssetManager(), "Common/MatDefs/Misc/Particle.j3md");
mat.setTexture("Texture", app.getAssetManager().loadTexture("Effects/Explosion/flash.png"));
mat.setBoolean("PointSprite", POINT_SPRITE);
flash.setMaterial(mat);
return flash;
}
/**
* Creates a round spark particle emitter.
*
* @return a configured round spark particle emitter
*/
ParticleEmitter createRoundSpark() {
ParticleEmitter roundSpark = new ParticleEmitter("RoundSpark", EMITTER_TYPE, 20 * COUNT_FACTOR);
roundSpark.setStartColor(new ColorRGBA(1f, 0.29f, 0.34f, (float) (1.0 / COUNT_FACTOR_F)));
roundSpark.setEndColor(new ColorRGBA(0, 0, 0, 0.5f / COUNT_FACTOR_F));
roundSpark.setStartSize(0.2f);
roundSpark.setEndSize(0.8f);
roundSpark.setShape(new EmitterSphereShape(Vector3f.ZERO, 1f));
roundSpark.setParticlesPerSec(0);
roundSpark.setGravity(0, -.5f, 0);
roundSpark.setLowLife(1.8f);
roundSpark.setHighLife(2f);
roundSpark.getParticleInfluencer().setInitialVelocity(new Vector3f(0, 3, 0));
roundSpark.getParticleInfluencer().setVelocityVariation(.5f);
roundSpark.setImagesX(1);
roundSpark.setImagesY(1);
Material mat = new Material(app.getAssetManager(), "Common/MatDefs/Misc/Particle.j3md");
mat.setTexture("Texture", app.getAssetManager().loadTexture("Effects/Explosion/roundspark.png"));
mat.setBoolean("PointSprite", POINT_SPRITE);
roundSpark.setMaterial(mat);
return roundSpark;
}
/**
* Creates a spark particle emitter.
*
* @return a configured spark particle emitter
*/
ParticleEmitter createSpark() {
ParticleEmitter spark = new ParticleEmitter("Spark", Type.Triangle, 30 * COUNT_FACTOR);
spark.setStartColor(new ColorRGBA(1f, 0.8f, 0.36f, 1.0f / COUNT_FACTOR_F));
spark.setEndColor(new ColorRGBA(1f, 0.8f, 0.36f, 0f));
spark.setStartSize(.5f);
spark.setEndSize(.5f);
spark.setFacingVelocity(true);
spark.setParticlesPerSec(0);
spark.setGravity(0, 5, 0);
spark.setLowLife(1.1f);
spark.setHighLife(1.5f);
spark.getParticleInfluencer().setInitialVelocity(new Vector3f(0, 20, 0));
spark.getParticleInfluencer().setVelocityVariation(1);
spark.setImagesX(1);
spark.setImagesY(1);
Material mat = new Material(app.getAssetManager(), "Common/MatDefs/Misc/Particle.j3md");
mat.setTexture("Texture", app.getAssetManager().loadTexture("Effects/Explosion/spark.png"));
spark.setMaterial(mat);
return spark;
}
/**
* Creates a smoke trail particle emitter.
*
* @return a configured smoke trail particle emitter
*/
ParticleEmitter createSmokeTrail() {
ParticleEmitter smokeTrail = new ParticleEmitter("SmokeTrail", Type.Triangle, 22 * COUNT_FACTOR);
smokeTrail.setStartColor(new ColorRGBA(1f, 0.8f, 0.36f, 1.0f / COUNT_FACTOR_F));
smokeTrail.setEndColor(new ColorRGBA(1f, 0.8f, 0.36f, 0f));
smokeTrail.setStartSize(.2f);
smokeTrail.setEndSize(1f);
smokeTrail.setFacingVelocity(true);
smokeTrail.setParticlesPerSec(0);
smokeTrail.setGravity(0, 1, 0);
smokeTrail.setLowLife(.4f);
smokeTrail.setHighLife(.5f);
smokeTrail.getParticleInfluencer().setInitialVelocity(new Vector3f(0, 12, 0));
smokeTrail.getParticleInfluencer().setVelocityVariation(1);
smokeTrail.setImagesX(1);
smokeTrail.setImagesY(3);
Material mat = new Material(app.getAssetManager(), "Common/MatDefs/Misc/Particle.j3md");
mat.setTexture("Texture", app.getAssetManager().loadTexture("Effects/Explosion/smoketrail.png"));
smokeTrail.setMaterial(mat);
return smokeTrail;
}
/**
* Creates a debris particle emitter.
*
* @return a configured debris particle emitter
*/
ParticleEmitter createDebris() {
ParticleEmitter debris = new ParticleEmitter("Debris", Type.Triangle, 15 * COUNT_FACTOR);
debris.setSelectRandomImage(true);
debris.setRandomAngle(true);
debris.setRotateSpeed(FastMath.TWO_PI * 4);
debris.setStartColor(new ColorRGBA(1f, 0.59f, 0.28f, 1.0f / COUNT_FACTOR_F));
debris.setEndColor(new ColorRGBA(.5f, 0.5f, 0.5f, 0f));
debris.setStartSize(.10f);
debris.setEndSize(.15f);
debris.setParticlesPerSec(0);
debris.setGravity(0, 12f, 0);
debris.setLowLife(1.4f);
debris.setHighLife(1.5f);
debris.setLocalTranslation(0, 2f, 0);
debris.getParticleInfluencer().setInitialVelocity(new Vector3f(0, 15, 0));
debris.getParticleInfluencer().setVelocityVariation(.60f);
debris.setImagesX(3);
debris.setImagesY(3);
Material mat = new Material(app.getAssetManager(), "Common/MatDefs/Misc/Particle.j3md");
mat.setTexture("Texture", app.getAssetManager().loadTexture("Effects/Explosion/Debris.png"));
debris.setMaterial(mat);
return debris;
}
/**
* Creates a shockwave particle emitter.
*
* @return a configured shockwave particle emitter
*/
ParticleEmitter createShockwave() {
ParticleEmitter shockwave = new ParticleEmitter("Shockwave", Type.Triangle, 1 * COUNT_FACTOR);
shockwave.setFaceNormal(Vector3f.UNIT_Y);
shockwave.setStartColor(new ColorRGBA(.48f, 0.17f, 0.01f, .8f / COUNT_FACTOR_F));
shockwave.setEndColor(new ColorRGBA(.48f, 0.17f, 0.01f, 0f));
shockwave.setStartSize(0f);
shockwave.setEndSize(3f);
shockwave.setParticlesPerSec(0);
shockwave.setGravity(0, 0, 0);
shockwave.setLowLife(0.5f);
shockwave.setHighLife(0.5f);
shockwave.getParticleInfluencer().setInitialVelocity(new Vector3f(0, 0, 0));
shockwave.getParticleInfluencer().setVelocityVariation(0f);
shockwave.setImagesX(1);
shockwave.setImagesY(1);
Material mat = new Material(app.getAssetManager(), "Common/MatDefs/Misc/Particle.j3md");
mat.setTexture("Texture", app.getAssetManager().loadTexture("Effects/Explosion/shockwave.png"));
shockwave.setMaterial(mat);
return shockwave;
}
/**
* Creates a moving smoke emitter.
*
* @return a configured smoke emitter
*/
ParticleEmitter createMovingSmokeEmitter() {
ParticleEmitter smokeEmitter = new ParticleEmitter("SmokeEmitter", Type.Triangle, 300);
smokeEmitter.setGravity(0, 0, 0);
smokeEmitter.getParticleInfluencer().setVelocityVariation(1);
smokeEmitter.setLocalTranslation(0, 2f, 0); //___________________
smokeEmitter.setLowLife(1);
smokeEmitter.setHighLife(1);
smokeEmitter.getParticleInfluencer().setInitialVelocity(new Vector3f(0, 0, 0));
smokeEmitter.setImagesX(15);
Material mat = new Material(app.getAssetManager(), "Common/MatDefs/Misc/Particle.j3md");
mat.setTexture("Texture", app.getAssetManager().loadTexture("Effects/Smoke/Smoke.png"));
smokeEmitter.setMaterial(mat);
return smokeEmitter;
}
public ParticleEmitter createWaterSplash() { //wird durch explosions animation ersetzt
// Create a new particle emitter for the splash effect
ParticleEmitter waterSplash = new ParticleEmitter("WaterSplash", Type.Triangle, 30);
// Set the shape of the emitter, making particles emit from a point or small area
waterSplash.setShape(new EmitterSphereShape(Vector3f.ZERO, 0.2f));
// Start and end colors for water (blue, fading out)
waterSplash.setStartColor(new ColorRGBA(0.4f, 0.4f, 1f, 1f)); // Light blue at start
waterSplash.setEndColor(new ColorRGBA(0.4f, 0.4f, 1f, 0f)); // Transparent at the end
// Particle size: small at start, larger before fading out
waterSplash.setStartSize(0.1f);
waterSplash.setEndSize(0.3f);
// Particle lifespan (how long particles live)
waterSplash.setLowLife(0.5f);
waterSplash.setHighLife(1f);
// Gravity: Pull the water particles downwards
waterSplash.setGravity(0, -9.81f, 0); // Earth's gravity simulation
// Velocity: Give particles an initial burst upward (simulates splash)
waterSplash.getParticleInfluencer().setInitialVelocity(new Vector3f(0, 3, 0));
waterSplash.getParticleInfluencer().setVelocityVariation(0.6f); // Add randomness to splash
// Set how many particles are emitted per second (0 to emit all particles at once)
waterSplash.setParticlesPerSec(0);
// Load a texture for the water splash (assuming a texture exists at this path)
Material mat = new Material(app.getAssetManager(), "Common/MatDefs/Misc/Particle.j3md");
mat.setTexture("Texture", app.getAssetManager().loadTexture("Effects/Splash/splash.png"));
waterSplash.setMaterial(mat);
return waterSplash;
}
}

View File

@@ -7,22 +7,28 @@
package pp.battleship.client.gui;
import static java.util.Objects.requireNonNull;
import com.jme3.effect.ParticleEmitter;
import com.jme3.material.Material;
import com.jme3.material.RenderState.BlendMode;
import com.jme3.math.ColorRGBA;
import com.jme3.math.FastMath;
import com.jme3.math.Vector3f;
import com.jme3.renderer.queue.RenderQueue.ShadowMode;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import com.jme3.scene.shape.Box;
import com.jme3.scene.shape.Cylinder;
import pp.battleship.client.BattleshipApp;
import pp.battleship.model.Battleship;
import pp.battleship.model.Rotation;
import pp.battleship.model.Shell;
import pp.battleship.model.ShipMap;
import pp.battleship.model.Shot;
import static java.util.Objects.requireNonNull;
import static pp.util.FloatMath.HALF_PI;
import static pp.util.FloatMath.PI;
@@ -34,16 +40,24 @@ import static pp.util.FloatMath.PI;
*/
class SeaSynchronizer extends ShipMapSynchronizer {
private static final String UNSHADED = "Common/MatDefs/Misc/Unshaded.j3md"; //NON-NLS
private static final String KING_GEORGE_V_MODEL = "Models/KingGeorgeV/KingGeorgeV.j3o"; //NON-NLS
private static final String KING_GEORGE_V_MODEL = "Models/Transporter/cr90.j3o"; //NON-NLS
private static final String TIE_FIGHTER = "Models/TieFighter/TieFighter.j3o"; //NON-NLS
private static final String TRANSPORTER = "Models/KingGeorgeV/KingGeorge.j3o"; //NON-NLS
//private static final String VENATOR = "Models/Venator/Venator.j3o"; //NON-NLS
private static final String WING = "Models/Wing/Wing.j3o"; //NON-NLS
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 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);
private static final String LIGHTING = "Common/MatDefs/Light/Lighting.j3md";
private final ShipMap map;
private final BattleshipApp app;
private final ParticleEffectFactory particleFactory;
/**
* Constructs a {@code SeaSynchronizer} object with the specified application, root node, and ship map.
@@ -56,6 +70,7 @@ class SeaSynchronizer extends ShipMapSynchronizer {
super(app.getGameLogic().getOwnMap(), root);
this.app = app;
this.map = map;
this.particleFactory = new ParticleEffectFactory(app);
addExisting();
}
@@ -69,8 +84,35 @@ class SeaSynchronizer extends ShipMapSynchronizer {
*/
@Override
public Spatial visit(Shot shot) {
return shot.isHit() ? handleHit(shot) : createCylinder(shot);
return shot.isHit() ? handleHit(shot) : handleMiss(shot);
}
private Spatial handleMiss(Shot shot) {
Node shotNode = new Node("ShotNode");
Geometry shotCylinder = createCylinder(shot);
shotNode.attachChild(shotCylinder);
ParticleEmitter waterSplash = particleFactory.createWaterSplash();
waterSplash.setLocalTranslation(shot.getY() + 0.5f, 0f, shot.getX() + 0.5f);
shotNode.attachChild(waterSplash);
waterSplash.emitAllParticles();
return shotNode;
}
private void sinkAndRemoveShip(Battleship ship) {
Battleship wilkeningklaunichtmeinencode = ship;
final Node shipNode = (Node) getSpatial(wilkeningklaunichtmeinencode);
if (shipNode == null) return;
// Add sinking control to animate the sinking
shipNode.addControl(new SinkingControl(shipNode));
// Add particle effects
ParticleEmitter bubbles = particleFactory.createWaterSplash();
bubbles.setLocalTranslation(shipNode.getLocalTranslation());
shipNode.attachChild(bubbles);
bubbles.emitAllParticles();
}
/**
* Handles a hit by attaching its representation to the node that
@@ -84,9 +126,50 @@ class SeaSynchronizer extends ShipMapSynchronizer {
final Battleship ship = requireNonNull(map.findShipAt(shot), "Missing ship");
final Node shipNode = requireNonNull((Node) getSpatial(ship), "Missing ship node");
final Geometry representation = createCylinder(shot);
representation.getLocalTranslation().subtractLocal(shipNode.getLocalTranslation());
shipNode.attachChild(representation);
Node hitEffectNode = new Node("HitEffectNode");
// Create particle effects
ParticleEmitter flame = particleFactory.createFlame();
ParticleEmitter flash = particleFactory.createFlash();
ParticleEmitter spark = particleFactory.createSpark();
ParticleEmitter roundSpark = particleFactory.createRoundSpark();
ParticleEmitter smokeTrail = particleFactory.createSmokeTrail();
ParticleEmitter debris = particleFactory.createDebris();
ParticleEmitter shockwave = particleFactory.createShockwave();
ParticleEmitter movingSmoke = particleFactory.createMovingSmokeEmitter();
// Attach all effects to the hitEffectNode
hitEffectNode.attachChild(flame);
hitEffectNode.attachChild(flash);
hitEffectNode.attachChild(spark);
hitEffectNode.attachChild(roundSpark);
hitEffectNode.attachChild(smokeTrail);
hitEffectNode.attachChild(debris);
hitEffectNode.attachChild(shockwave);
hitEffectNode.attachChild(movingSmoke);
// Set the local translation for the hit effect to the point of impact
hitEffectNode.setLocalTranslation(shot.getY() + 0.5f - shipNode.getLocalTranslation().x,
0.5f, // Adjust as needed for height above the ship
shot.getX() + 0.5f - shipNode.getLocalTranslation().z);
// Attach the hitEffectNode to the shipNode so it moves with the ship
shipNode.attachChild(hitEffectNode);
// Emit particles when the hit happens
flash.emitAllParticles();
spark.emitAllParticles();
smokeTrail.emitAllParticles();
debris.emitAllParticles();
shockwave.emitAllParticles();
flame.emitAllParticles();
roundSpark.emitAllParticles();
if (ship.isDestroyed()) {
sinkAndRemoveShip(ship);
}
return null;
}
@@ -101,15 +184,16 @@ class SeaSynchronizer extends ShipMapSynchronizer {
private Geometry createCylinder(Shot shot) {
final ColorRGBA color = shot.isHit() ? HIT_COLOR : SPLASH_COLOR;
final float height = shot.isHit() ? 1.2f : 0.1f;
final Cylinder cylinder = new Cylinder(2, 20, 0.45f, height, true);
final Geometry geometry = new Geometry(SHOT, cylinder);
geometry.setMaterial(createColoredMaterial(color));
geometry.rotate(HALF_PI, 0f, 0f);
// compute the center of the shot in world coordinates
geometry.setLocalTranslation(shot.getY() + 0.5f, 0f, shot.getX() + 0.5f);
// compute the center of the shot in world coordinates, with an additional 2f height
geometry.setLocalTranslation(shot.getY() + 0.5f, 2f + height / 2, shot.getX() + 0.5f);
return geometry;
}
@@ -141,8 +225,20 @@ class SeaSynchronizer extends ShipMapSynchronizer {
* @return the spatial representing the battleship
*/
private Spatial createShip(Battleship ship) {
return ship.getLength() == 4 ? createBattleship(ship) : createBox(ship);
if (ship.getLength() == 1) {
return createTie_Fighter(ship);
} else if (ship.getLength() == 2) {
return createWing(ship);
} else if (ship.getLength() == 3) {
return createTransporter(ship);
} else if (ship.getLength() == 4) {
return createBattleship(ship);
} else {
return createBox(ship);
}
}
/**
* Creates a simple box to represent a battleship that is not of the "King George V" type.
@@ -181,20 +277,100 @@ class SeaSynchronizer extends ShipMapSynchronizer {
}
/**
* Creates a detailed 3D model to represent a "King George V" battleship.
* Creates a detailed 3D model to represent all battleships.
*
* @param ship the battleship to be represented
* @return the spatial representing the "King George V" battleship
*/
private Spatial createBattleship(Battleship ship) {
final Spatial model = app.getAssetManager().loadModel(KING_GEORGE_V_MODEL);
model.rotate(-HALF_PI, calculateRotationAngle(ship.getRot()), 0f);
model.scale(1.48f);
// Berechne den Rotationswinkel
float rotationAngle = calculateRotationAngle(ship.getRot())+HALF_PI;
model.setLocalTranslation(new Vector3f(model.getLocalTranslation().x, 2f, model.getLocalTranslation().z));
model.rotate(0f, rotationAngle, -HALF_PI);
model.scale(1.2f);
model.setShadowMode(ShadowMode.CastAndReceive);
// Bestimme die Verschiebung basierend auf der Rotation
Vector3f translation = model.getLocalTranslation();
// Bei 0 oder 180 Grad wird auf der Z-Achse verschoben, bei 90 oder 270 Grad auf der X-Achse
if (rotationAngle == 0 || rotationAngle == FastMath.PI) {
// Verschiebe auf der Z-Achse und um 2f nach oben
translation = translation.subtract(0,0,1); // Nach hinten auf der Z-Achse, und um 2f nach oben
} else if (rotationAngle == FastMath.HALF_PI || rotationAngle == 3 * FastMath.HALF_PI) {
// Verschiebe auf der X-Achse und um 2f nach oben
translation = translation.subtract(1,0,0); // Nach hinten auf der X-Achse, und um 2f nach oben
}
model.setLocalTranslation(translation);
return model;
}
private Spatial createTransporter(Battleship ship) {
final Spatial model = app.getAssetManager().loadModel(TRANSPORTER);
float rotationAngle = calculateRotationAngle(ship.getRot())+HALF_PI;
model.rotate(-HALF_PI, calculateRotationAngle(ship.getRot())+ PI, 0f);
model.scale(0.008f);
model.setShadowMode(ShadowMode.CastAndReceive);
model.setLocalTranslation(new Vector3f(model.getLocalTranslation().x, 2f, model.getLocalTranslation().z));
Vector3f translation = model.getLocalTranslation();
// Bei 0 oder 180 Grad wird auf der Z-Achse verschoben, bei 90 oder 270 Grad auf der X-Achse
if (rotationAngle == 0 || rotationAngle == FastMath.PI) {
// Verschiebe auf der Z-Achse und um 2f nach oben
translation = translation.subtract(0,0,1);
} else if (rotationAngle == FastMath.HALF_PI || rotationAngle == 3 * FastMath.HALF_PI) {
// Verschiebe auf der X-Achse und um 2f nach oben
translation = translation.add(1,0,0);
}
model.setLocalTranslation(translation);
return model;
}
private Spatial createWing(Battleship ship) {
final Spatial model = app.getAssetManager().loadModel(WING);
model.setLocalTranslation(new Vector3f(model.getLocalTranslation().x, 2f, model.getLocalTranslation().z));
// Berechne den Rotationswinkel
float rotationAngle = calculateRotationAngle(ship.getRot())+HALF_PI;
model.rotate(0f, rotationAngle, 0f);
model.scale(0.0008f);
model.setShadowMode(ShadowMode.CastAndReceive);
// Bestimme die Verschiebung basierend auf der Rotation
Vector3f translation = model.getLocalTranslation();
// Bei 0 oder 180 Grad wird auf der Z-Achse verschoben, bei 90 oder 270 Grad auf der X-Achse
if (rotationAngle == 0 || rotationAngle == FastMath.PI) {
// Verschiebe auf der Z-Achse und um 2f nach oben
translation = translation.add(0,0,0); // Nach hinten auf der Z-Achse, und um 2f nach oben
} else if (rotationAngle == FastMath.HALF_PI || rotationAngle == 3 * FastMath.HALF_PI) {
// Verschiebe auf der X-Achse und um 2f nach oben
translation = translation.add(0,0,0); // Nach hinten auf der X-Achse, und um 2f nach oben
}
model.setLocalTranslation(translation);
return model;
}
private Spatial createTie_Fighter(Battleship ship) {
final Spatial model = app.getAssetManager().loadModel(TIE_FIGHTER);
model.rotate(-0f, calculateRotationAngle(ship.getRot()), 0f);
model.scale(0.07f);
model.setShadowMode(ShadowMode.CastAndReceive);
model.setLocalTranslation(new Vector3f(model.getLocalTranslation().x, 2f, model.getLocalTranslation().z));
return model;
}
/**
* Calculates the rotation angle for the specified rotation.
@@ -210,4 +386,25 @@ class SeaSynchronizer extends ShipMapSynchronizer {
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 + 2f, 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

@@ -0,0 +1,60 @@
package pp.battleship.client.gui;
import com.jme3.math.FastMath;
import com.jme3.math.Quaternion;
import com.jme3.math.Vector3f;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.Node;
import com.jme3.scene.control.AbstractControl;
/**
* Control that handles the sinking effect for destroyed ships.
* It will gradually move the ship downwards and then remove it from the scene.
*/
class SinkingControl extends AbstractControl {
private static final float SINK_DURATION = 2f; // Duration of the sinking animation
private static final float SINK_SPEED = 0.6f; // Speed at which the ship sinks
private float elapsedTime = 0;
private final Node shipNode;
/**
* Constructs a {@code SinkingControl} object with the shipNode to be to be sunk
* @param shipNode the node to handeld
*/
public SinkingControl(Node shipNode) {
this.shipNode = shipNode;
}
float tiltAngle= 0;
/**
* Updated the Map to sink the ship
*
* @param tpf time per frame
*/
@Override
protected void controlUpdate(float tpf) {
// Update the sinking effect
elapsedTime += tpf;
// Move the ship down over time
Vector3f currentPos = shipNode.getLocalTranslation();
shipNode.setLocalTranslation(currentPos.x+SINK_SPEED*tpf, currentPos.y - SINK_SPEED * tpf*2, currentPos.z+SINK_SPEED*tpf*2);
// Check if sinking duration has passed
if (elapsedTime >= SINK_DURATION) {
// Remove the ship from the scene
shipNode.removeFromParent();
}
// Apply the tilt angle and rotation during sinking
float sinkingTiltAngle = FastMath.DEG_TO_RAD * tiltAngle * tpf;
float sinkingRotationAngle = FastMath.DEG_TO_RAD * 45f * tpf; // Additional rotation during sinking
Quaternion tiltRotation = new Quaternion().fromAngles(-sinkingTiltAngle, sinkingRotationAngle, 0);
spatial.setLocalRotation(tiltRotation);
}
@Override
protected void controlRender(RenderManager rm, ViewPort vp) {
// No rendering-related code needed
}
}

View File

@@ -0,0 +1,140 @@
package pp.battleship.client.gui;
import com.jme3.math.FastMath;
import com.jme3.math.Quaternion;
import com.jme3.math.Vector3f;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import com.jme3.scene.control.AbstractControl;
/**
* Controls the burning, tilting, and sinking behavior of a battleship.
* The ship will burn and tilt for a specified duration, then sink below the water surface.
*/
public class SinkingShip extends AbstractControl {
private float elapsedTime = 0.2f;
private final float burnTiltDuration;
private final float sinkDuration;
private final float sinkDepth;
private final float tiltAngle;
private final Vector3f initialPosition;
private boolean sinkingStarted = false;
/**
* Constructs a new ShipSinkingControl instance.
*
* @param burnTiltDuration Time in seconds for the ship to burn and tilt on the surface
* @param sinkDuration Time in seconds for the ship to fully sink
* @param sinkDepth Depth below the water to sink the ship
* @param tiltAngle Final tilt angle in degrees
*/
public SinkingShip(float burnTiltDuration, float sinkDuration, float sinkDepth, float tiltAngle) {
this.burnTiltDuration = burnTiltDuration;
this.sinkDuration = sinkDuration;
this.sinkDepth = sinkDepth;
this.tiltAngle = tiltAngle;
this.initialPosition = new Vector3f(); // Placeholder; will be set in controlUpdate
}
/**
* Overrides controlUpdate in AbstractControl
* regulates the burn and tilt timeframe
* @param tpf time per frame (in seconds)
*/
@Override
protected void controlUpdate(float tpf) {
if (spatial == null) return;
elapsedTime += tpf;
if (elapsedTime < burnTiltDuration) {
float progress = elapsedTime / burnTiltDuration;
float angleInRadians = FastMath.DEG_TO_RAD * FastMath.interpolateLinear(progress, 0f, -tiltAngle);
Quaternion tiltRotation = new Quaternion().fromAngles(angleInRadians, 0, 0);
spatial.setLocalRotation(tiltRotation);
return;
}
// Start sinking if it hasn't started yet
if (!sinkingStarted) {
sinkingStarted = true;
// Save the initial position when sinking starts
initialPosition.set(spatial.getLocalTranslation());
// Remove the hitEffectNode
Node parentNode = (Node) spatial;
Spatial hitEffects = parentNode.getChild("HitEffectNode");
if (hitEffects != null) {
parentNode.detachChild(hitEffects);
}
}
// Calculate the progress of the sinking (0 to 1)
float progress = Math.min((elapsedTime - burnTiltDuration) / sinkDuration, 1f);
// Apply the tilt angle (remains constant during sinking)
float sinkingTiltAngle = FastMath.DEG_TO_RAD * tiltAngle * progress;
float sinkingRotationAngle = FastMath.DEG_TO_RAD * 45f * progress; // Additional rotation during sinking (test)
Quaternion tiltRotation = new Quaternion().fromAngles(-sinkingTiltAngle, sinkingRotationAngle, sinkingRotationAngle);
spatial.setLocalRotation(tiltRotation);
// Sink the ship by interpolating the Y position
float currentY = FastMath.interpolateLinear(progress, initialPosition.y, sinkDepth);
spatial.setLocalTranslation(initialPosition.x, currentY, initialPosition.z);
if (currentY <= sinkDepth) {
Node parentNode = (Node) spatial.getParent();
if (parentNode != null) {
parentNode.detachChild(spatial);
}
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
// }
}
/**
* This method is called during the rendering phase, but it does not perform any
* operations in this implementation as the control only influences the spatial's
* transformation, not its rendering process.
*
* @param rm the RenderManager rendering the controlled Spatial (not null)
* @param vp the ViewPort being rendered (not null)
*/
@Override
protected void controlRender(RenderManager rm, ViewPort vp) {
// No rendering logic is needed for this control
}
/**
* Starts the sinking process for the ship.
*/
public void startSinking() {
// --> sinkingControl
}
}

View File

@@ -0,0 +1,25 @@
package pp.battleship.client.gui;
import com.simsilica.lemur.Slider;
public class VolumeSlider extends Slider {
private final BgMusic music;
private double vol;
public VolumeSlider(BgMusic music) {
super();
this.music = music;
vol = BgMusic.volumeInPreferences();
getModel().setPercent(vol);
}
public void update() {
if (vol != getModel().getPercent()) {
vol = getModel().getPercent();
music.setVolume( (float) vol);
}
}
}

View File

@@ -0,0 +1,183 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.client.server;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.LogManager;
import com.jme3.network.ConnectionListener;
import com.jme3.network.HostedConnection;
import com.jme3.network.Message;
import com.jme3.network.MessageListener;
import com.jme3.network.Network;
import com.jme3.network.Server;
import com.jme3.network.serializing.Serializer;
import pp.battleship.BattleshipConfig;
import pp.battleship.game.server.Player;
import pp.battleship.game.server.ServerGameLogic;
import pp.battleship.game.server.ServerSender;
import pp.battleship.message.client.AnimationFinishedMessage;
import pp.battleship.message.client.ClientMessage;
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.StartBattleMessage;
import pp.battleship.model.Battleship;
import pp.battleship.model.IntPoint;
import pp.battleship.model.Shot;
/**
* Server implementing the visitor pattern as MessageReceiver for ClientMessages
*/
public class BattleshipSelfhostServer implements MessageListener<HostedConnection>, ConnectionListener, ServerSender {
private static final Logger LOGGER = System.getLogger(BattleshipSelfhostServer.class.getName());
private static final File CONFIG_FILE = new File("server.properties");
private final BattleshipConfig config = new BattleshipConfig();
private Server myServer;
private final ServerGameLogic logic;
private final BlockingQueue<ReceivedMessageSelfhost> pendingMessages = new LinkedBlockingQueue<>();
static {
// Configure logging
LogManager manager = LogManager.getLogManager();
try {
manager.readConfiguration(new FileInputStream("logging.properties"));
LOGGER.log(Level.INFO, "Successfully read logging properties"); //NON-NLS
}
catch (IOException e) {
LOGGER.log(Level.INFO, e.getMessage());
}
}
/**
* Starts the Battleships server.
*/
public static void main(String[] args) {
new BattleshipSelfhostServer().run();
}
/**
* Creates the server.
*/
BattleshipSelfhostServer() {
config.readFromIfExists(CONFIG_FILE);
LOGGER.log(Level.INFO, "Configuration: {0}", config); //NON-NLS
logic = new ServerGameLogic(this, config);
}
public void run() {
startServer();
while (true)
processNextMessage();
}
private void startServer() {
try {
LOGGER.log(Level.INFO, "Starting server..."); //NON-NLS
myServer = Network.createServer(config.getPort());
initializeSerializables();
myServer.start();
registerListeners();
LOGGER.log(Level.INFO, "Server started: {0}", myServer.isRunning()); //NON-NLS
}
catch (IOException e) {
LOGGER.log(Level.ERROR, "Couldn't start server: {0}", e.getMessage()); //NON-NLS
exit(1);
}
}
private void processNextMessage() {
try {
pendingMessages.take().process(logic);
}
catch (InterruptedException ex) {
LOGGER.log(Level.INFO, "Interrupted while waiting for messages"); //NON-NLS
Thread.currentThread().interrupt();
}
}
private void initializeSerializables() {
Serializer.registerClass(GameDetails.class);
Serializer.registerClass(StartBattleMessage.class);
Serializer.registerClass(MapMessage.class);
Serializer.registerClass(ShootMessage.class);
Serializer.registerClass(EffectMessage.class);
Serializer.registerClass(Battleship.class);
Serializer.registerClass(IntPoint.class);
Serializer.registerClass(Shot.class);
Serializer.registerClass(AnimationFinishedMessage.class);
}
private void registerListeners() {
myServer.addMessageListener(this, MapMessage.class);
myServer.addMessageListener(this, ShootMessage.class);
myServer.addConnectionListener(this);
myServer.addMessageListener(this, AnimationFinishedMessage.class);
}
@Override
public void messageReceived(HostedConnection source, Message message) {
LOGGER.log(Level.INFO, "message received from {0}: {1}", source.getId(), message); //NON-NLS
if (message instanceof ClientMessage clientMessage)
pendingMessages.add(new ReceivedMessageSelfhost(clientMessage, source.getId()));
}
@Override
public void connectionAdded(Server server, HostedConnection hostedConnection) {
LOGGER.log(Level.INFO, "new connection {0}", hostedConnection); //NON-NLS
logic.addPlayer(hostedConnection.getId());
}
@Override
public void connectionRemoved(Server server, HostedConnection hostedConnection) {
LOGGER.log(Level.INFO, "connection closed: {0}", hostedConnection); //NON-NLS
final Player player = logic.getPlayerById(hostedConnection.getId());
if (player == null)
LOGGER.log(Level.INFO, "closed connection does not belong to an active player"); //NON-NLS
else { //NON-NLS
LOGGER.log(Level.INFO, "closed connection belongs to {0}", player); //NON-NLS
exit(0);
}
}
private void exit(int exitValue) { //NON-NLS
LOGGER.log(Level.INFO, "close request"); //NON-NLS
if (myServer != null)
for (HostedConnection client : myServer.getConnections()) //NON-NLS
if (client != null) client.close("Game over"); //NON-NLS
System.exit(exitValue);
}
/**
* Send the specified message to the specified connection.
*
* @param id the connection id
* @param message the message
*/
public void send(int id, ServerMessage message) {
if (myServer == null || !myServer.isRunning()) {
LOGGER.log(Level.ERROR, "no server running when trying to send {0}", message); //NON-NLS
return;
}
final HostedConnection connection = myServer.getConnection(id);
if (connection != null)
connection.send(message);
else
LOGGER.log(Level.ERROR, "there is no connection with id={0}", id); //NON-NLS
}
}

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 235 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 94 KiB

View File

@@ -1,3 +0,0 @@
based on:
https://free3d.com/3d-model/wwii-ship-uk-king-george-v-class-battleship-v1--185381.html
License: Free Personal Use Only

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 354 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 164 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 220 KiB

View File

@@ -1,6 +1,6 @@
Material Water : Common/MatDefs/Light/Lighting.j3md {
MaterialParameters {
Shininess : 64
Shininess : 6
DiffuseMap : Repeat Textures/Terrain/Water/Water_002_COLOR.jpg
NormalMap : Repeat Textures/Terrain/Water/Water_002_NORM.jpg
SpecularMap : Repeat Textures/Terrain/Water/Water_002_ROUGH.jpg

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 17 KiB

View File

@@ -0,0 +1,2 @@
[LocalizedFileNames]
Water_002_NORM.jpg=@Water_002_NORM,0

View File

@@ -1,12 +1,10 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.exporter;
import java.io.File;
import java.io.IOException;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import com.jme3.app.SimpleApplication;
import com.jme3.export.JmeExporter;
import com.jme3.export.binary.BinaryExporter;
@@ -14,11 +12,6 @@ import com.jme3.scene.Spatial;
import com.jme3.system.JmeContext;
import com.jme3.util.TangentBinormalGenerator;
import java.io.File;
import java.io.IOException;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
/**
* This class transforms models into j3o format.
*/
@@ -41,7 +34,13 @@ public class ModelExporter extends SimpleApplication {
*/
@Override
public void simpleInitApp() {
export("Models/KingGeorgeV/King_George_V.obj", "KingGeorgeV.j3o"); //NON-NLS
export("Models/45.obj", "45.j3o");//NON-NLS passt
//export("Models/.j3o");
// export("Models/Transporter/Transporter.obj", "Transporter.j3o"); //NON-NLS passt
// export("Models/TieFighter.obj", "TieFighter.j3o"); //NON-NLS
// export("Models/Venator/Venator.obj", "Venator.j3o"); //NON-NLS kickt
stop();
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,72 @@
# Blender MTL File: 'SpaceShipDetailed.blend'
# Material Count: 7
newmtl Material.001
Ns 96.078431
Ka 1.000000 1.000000 1.000000
Kd 0.640000 0.640000 0.640000
Ks 0.500000 0.500000 0.500000
Ke 0.000000 0.000000 0.000000
Ni 1.000000
d 1.000000
illum 2
newmtl Material.002
Ns 96.078431
Ka 1.000000 1.000000 1.000000
Kd 0.640000 0.640000 0.640000
Ks 0.500000 0.500000 0.500000
Ke 0.000000 0.000000 0.000000
Ni 1.000000
d 1.000000
illum 2
newmtl Material.003
Ns 96.078431
Ka 1.000000 1.000000 1.000000
Kd 0.640000 0.640000 0.640000
Ks 0.500000 0.500000 0.500000
Ke 0.000000 0.000000 0.000000
Ni 1.000000
d 1.000000
illum 2
newmtl Material.004
Ns 96.078431
Ka 1.000000 1.000000 1.000000
Kd 0.640000 0.640000 0.640000
Ks 0.500000 0.500000 0.500000
Ke 0.000000 0.000000 0.000000
Ni 1.000000
d 1.000000
illum 2
newmtl Material.005
Ns 96.078431
Ka 1.000000 1.000000 1.000000
Kd 0.640000 0.640000 0.640000
Ks 0.500000 0.500000 0.500000
Ke 0.000000 0.000000 0.000000
Ni 1.000000
d 1.000000
illum 2
newmtl Material.006
Ns 96.078431
Ka 1.000000 1.000000 1.000000
Kd 0.640000 0.640000 0.640000
Ks 0.500000 0.500000 0.500000
Ke 0.000000 0.000000 0.000000
Ni 1.000000
d 1.000000
illum 2
newmtl Material.007
Ns 96.078431
Ka 1.000000 1.000000 1.000000
Kd 0.640000 0.640000 0.640000
Ks 0.500000 0.500000 0.500000
Ke 0.000000 0.000000 0.000000
Ni 1.000000
d 1.000000
illum 2

File diff suppressed because it is too large Load Diff

Binary file not shown.

Before

Width:  |  Height:  |  Size: 235 KiB

View File

@@ -1,18 +0,0 @@
# 3ds Max Wavefront OBJ Exporter v0.97b - (c)2007 guruware
# File Created: 16.03.2012 14:15:53
newmtl _King_George_V
Ns 60.0000
Ni 1.5000
d 1.0000
Tr 0.0000
Tf 1.0000 1.0000 1.0000
illum 2
Ka 1.0000 1.0000 1.0000
Kd 1.0000 1.0000 1.0000
Ks 0.4500 0.4500 0.4500
Ke 0.0000 0.0000 0.0000
map_Ka King_George_V.jpg
map_Kd King_George_V.jpg
map_bump King_George_V_bump.jpg
bump King_George_V_bump.jpg

Binary file not shown.

Before

Width:  |  Height:  |  Size: 94 KiB

View File

@@ -1,3 +0,0 @@
based on:
https://free3d.com/3d-model/wwii-ship-uk-king-george-v-class-battleship-v1--185381.html
License: Free Personal Use Only

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,48 @@
# WaveFront *.mtl file (generated by CINEMA 4D)
newmtl small parts
Kd 0.50599998235703 0.53606665134430 0.55000001192093
Ks 1.00000000000000 1.00000000000000 1.00000000000000
Ns 100
illum 7
newmtl body . blue
Kd 0.08579999953508 0.18754999339581 0.33000001311302
Ks 1.00000000000000 1.00000000000000 1.00000000000000
Ns 100
illum 7
newmtl Mat
Ka 1.44000005722046 1.11624002456665 0.41760000586510
Kd 1.00000000000000 1.00000000000000 1.00000000000000
d 0
Tf 1.00000000000000 1.00000000000000 1.00000000000000
illum 7
newmtl Body
Kd 0.62400001287460 0.64219999313354 0.64999997615814
Ks 1.00000000000000 1.00000000000000 1.00000000000000
Ns 100
illum 7
newmtl body . Red .1
Kd 0.70999997854233 0.16329999268055 0.16329999268055
Ks 1.00000000000000 1.00000000000000 1.00000000000000
Ns 100
illum 7
newmtl Mat.1
Kd 0.00000000000000 0.00000000000000 0.00000000000000
Ks 0.72000002861023 0.72000002861023 0.72000002861023
Ns 100
d 0
Tf 0.60000002384186 0.60000002384186 0.60000002384186
Ni 1.517
illum 7
newmtl Body 2 Dark
Kd 0.20460000634193 0.21537999808788 0.21999999880791
Ks 1.00000000000000 1.00000000000000 1.00000000000000
Ns 100
illum 7

File diff suppressed because it is too large Load Diff

View File

@@ -7,14 +7,15 @@
package pp.battleship.game.client;
import java.lang.System.Logger.Level;
import pp.battleship.message.client.ShootMessage;
import pp.battleship.message.server.EffectMessage;
import pp.battleship.model.IntPoint;
import pp.battleship.model.Shell;
import pp.battleship.model.ShipMap;
import pp.battleship.notification.Sound;
import java.lang.System.Logger.Level;
/**
* 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
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.getOwnMap()::add);
logic.setState(new GameOverState(logic));
}
Shell shell = new Shell(msg.getShot());
affectedMap(msg).add(shell);
logic.playSound(Sound.SHELL_FLYING);
logic.setState(new ShootingState(logic, shell, myTurn, msg));
}
/**
@@ -81,22 +79,4 @@ class BattleState extends ClientState {
* @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

@@ -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

@@ -7,7 +7,15 @@
package pp.battleship.game.server;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import pp.battleship.BattleshipConfig;
import pp.battleship.message.client.AnimationFinishedMessage;
import pp.battleship.message.client.ClientInterpreter;
import pp.battleship.message.client.MapMessage;
import pp.battleship.message.client.ShootMessage;
@@ -18,12 +26,6 @@ import pp.battleship.message.server.StartBattleMessage;
import pp.battleship.model.Battleship;
import pp.battleship.model.IntPoint;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Controls the server-side game logic for Battleship.
@@ -38,6 +40,7 @@ public class ServerGameLogic implements ClientInterpreter {
private final ServerSender serverSender;
private Player activePlayer;
private ServerState state = ServerState.WAIT;
private Set<Player> waitPlayers = new HashSet<>();
/**
* Constructs a ServerGameLogic with the specified sender and configuration.
@@ -134,6 +137,7 @@ public class ServerGameLogic implements ClientInterpreter {
/**
* Handles the reception of a MapMessage.
* Also tests valid ship placement on the Map.
*
* @param msg the received MapMessage
* @param from the ID of the sender client
@@ -142,7 +146,16 @@ public class ServerGameLogic implements ClientInterpreter {
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
List<Battleship> ships = msg.getShips();
if (! mapTest(ships)){
LOGGER.log(Level.ERROR, "Geladene Karte von Spieler {0} enthält unzulässige Schiffe", from);
send(getPlayerById(from),null);
return;
}
playerReady(getPlayerById(from), msg.getShips());
}
@@ -217,4 +230,47 @@ public class ServerGameLogic implements ClientInterpreter {
}
}
}
//Aufgabe 8
private boolean isInBounds(Battleship ship){
return ship.getMinX() >= 0 && ship.getMaxX() < config.getMapWidth() &&
ship.getMinY() >= 0 && ship.getMaxY() < config.getMapHeight();
}
private boolean mapTest(List<Battleship> ships) {
Set<IntPoint> belegt = new HashSet<>();
return ships.stream().allMatch(ship -> isInBounds(ship) &&
ship.getPositions().stream().allMatch(belegt::add));
}
/**
* Handles the reception of a AnimationFinishedMessage.
*
* @param msg the received MapMessage
* @param from the ID of the sender client
*/
@Override
public void received(AnimationFinishedMessage msg, int from) {
if (state != ServerState.ANIMATION) {
LOGGER.log(Level.ERROR, "animation finished not allowed in {0}", state);
}
else {
LOGGER.log(Level.DEBUG, "anim received from {0}", getPlayerById(from));
Player player = getPlayerById(from);
if (!waitPlayers.add(player)) {
LOGGER.log(Level.ERROR, "{0} already sent animation finished", player); //NON-NLS
return;
}
if (waitPlayers.size() == 2) {
waitPlayers = new HashSet<>();
setState(ServerState.BATTLE);
}
}
}
}

View File

@@ -29,5 +29,10 @@ enum ServerState {
/**
* The game has ended because all the ships of one player have been destroyed.
*/
GAME_OVER
GAME_OVER,
/**
* The server is waiting for all clients to finish the shoot animation.
*/
ANIMATION
}

View File

@@ -7,6 +7,7 @@
package pp.battleship.game.singlemode;
import pp.battleship.message.client.AnimationFinishedMessage;
import pp.battleship.message.client.ClientInterpreter;
import pp.battleship.message.client.ClientMessage;
import pp.battleship.message.client.MapMessage;
@@ -72,4 +73,10 @@ class Copycat implements ClientInterpreter {
private static Battleship copy(Battleship ship) {
return new Battleship(ship.getLength(), ship.getX(), ship.getY(), ship.getRot());
}
@Override
public void received(AnimationFinishedMessage msg, int from) {
copiedMessage = msg;
}
}

View File

@@ -0,0 +1,25 @@
package pp.battleship.message.client;
import com.jme3.network.serializing.Serializable;
/**
* Represents a message indicating that an animation has finished on the client side.
*/
@Serializable
public class AnimationFinishedMessage extends ClientMessage {
public AnimationFinishedMessage() {
super();
}
/**
* Accepts a visitor to process this message.
*
* @param interpreter the visitor to process this message
* @param from the connection ID from which the message was received
*/
@Override
public void accept(ClientInterpreter interpreter, int from) {
interpreter.received(this, from);
}
}

View File

@@ -26,4 +26,12 @@ public interface ClientInterpreter {
* @param from the connection ID from which the message was received
*/
void received(MapMessage msg, int from);
/**
* Processes a received AnimationFinishedMessage.
*
* @param msg the MapMessage to be processed
* @param from the connection ID from which the message was received
*/
void received(AnimationFinishedMessage msg, int from);
}

View File

@@ -7,14 +7,15 @@
package pp.battleship.model;
import com.jme3.network.serializing.Serializable;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import static java.lang.Math.max;
import static java.lang.Math.min;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.jme3.network.serializing.Serializable;
/**
* Represents a battleship in the game. A battleship is characterized by its length, position,
@@ -321,4 +322,14 @@ public class Battleship implements Item {
public void accept(VoidVisitor visitor) {
visitor.visit(this);
}
public List<IntPoint> getPositions() {
List<IntPoint> positions = new ArrayList<>();
for (int x = getMinX(); x <= getMaxX(); x++) {
for (int y = getMinY(); y <= getMaxY(); y++) {
positions.add(new IntPoint(x, y));
}
}
return positions;
}
}

View File

@@ -0,0 +1,126 @@
package pp.battleship.model;
import com.jme3.math.Quaternion;
import com.jme3.math.Vector3f;
/**
* The {@code Shell} class represents a projectile fired by a ship in the Battleship game.
* It models the position and rotation of the projectile and allows for its movement along
* a Bezier curve.
*/
public class Shell implements Item {
/**
* Initial position of the shell
*/
private final static Vector3f INIT_POS = new Vector3f(-3, 7, -3);
/**
* The overshot difference vector used to get a shallower flight path
*/
private final static Vector3f OVER_SHOT_DIFF = new Vector3f(-1, -1, -1);
// Target shot position
private final Vector3f shotPosition;
// Position on top of shotPosition used for Bezier curve
private final Vector3f overShotPosition;
// Current position of the shell
private Vector3f position;
// Current rotation of the shell
private final Quaternion rotation;
/**
* Constructs a new {@code Shell} object using the given {@code Shot} target.
* The initial position, target position, and overshot position are calculated.
*
* @param shot The target {@code Shot} object containing the destination coordinates.
*/
public Shell(Shot shot) {
this.shotPosition = new Vector3f(shot.getX(), 0, shot.getY());
this.overShotPosition = new Vector3f(shotPosition.x, INIT_POS.y, shotPosition.z).add(OVER_SHOT_DIFF);
this.position = INIT_POS;
this.rotation = new Quaternion();
}
/**
* Gets the current position of the shell.
*
* @return The current position as a {@code Vector3f}.
*/
public Vector3f getPosition() {
return this.position;
}
/**
* Gets the current rotation of the shell.
*
* @return The current rotation as a {@code Quaternion}.
*/
public Quaternion getRotation() {
return this.rotation;
}
/**
* Moves the shell along a Bezier curve based on the given time factor {@code t}.
* The position and rotation of the shell are updated.
*
* @param t The time factor between 0 and 1, representing the progress of the shell's flight.
*/
public void move(float t) {
if (t > 1f) t = 1f;
Vector3f newPosition = bezInt(INIT_POS, overShotPosition, shotPosition, t);
updateRotation(position, newPosition);
this.position = newPosition;
}
/**
* Performs a quadratic Bezier interpolation between three points based on the time factor {@code t}.
*
* @param p1 The start position.
* @param p2 The overshot position.
* @param p3 The target position.
* @param t The time factor for interpolation.
* @return The interpolated position as a {@code Vector3f}.
*/
private Vector3f bezInt(Vector3f p1, Vector3f p2, Vector3f p3, float t) {
Vector3f inA = linInt(p1, p2, t);
Vector3f inB = linInt(p2, p3, t);
return linInt(inA, inB, t);
}
/**
* Performs linear interpolation between two points {@code p1} and {@code p2} based on the time factor {@code t}.
*
* @param p1 The start position.
* @param p2 The end position.
* @param t The time factor for interpolation.
* @return The interpolated position as a {@code Vector3f}.
*/
private Vector3f linInt(Vector3f p1, Vector3f p2, float t) {
float x = p1.getX() + t * (p2.getX() - p1.getX());
float y = p1.getY() + t * (p2.getY() - p1.getY());
float z = p1.getZ() + t * (p2.getZ() - p1.getZ());
return new Vector3f(x, y, z);
}
/**
* Updates the rotation of the shell to face the new position along its flight path.
*
* @param oldPos The previous position of the shell.
* @param newPos The new position of the shell.
*/
private void updateRotation(Vector3f oldPos, Vector3f newPos) {
Vector3f direction = newPos.subtract(oldPos).normalize();
if (direction.lengthSquared() > 0) {
this.rotation.lookAt(direction, Vector3f.UNIT_Y);
}
}
@Override
public <T> T accept(Visitor<T> visitor) {
return visitor.visit(this);
}
@Override
public void accept(VoidVisitor visitor) {
visitor.visit(this);
}
}

View File

@@ -7,15 +7,16 @@
package pp.battleship.model;
import pp.battleship.notification.GameEvent;
import pp.battleship.notification.GameEventBroker;
import pp.battleship.notification.ItemAddedEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;
import pp.battleship.notification.GameEvent;
import pp.battleship.notification.GameEventBroker;
import pp.battleship.notification.ItemAddedEvent;
import pp.battleship.notification.ItemRemovedEvent;
/**
* Represents a rectangular map that holds ships and registers shots fired.
* It also supports event notification for game state changes such as item addition or removal.
@@ -97,7 +98,7 @@ public class ShipMap {
*/
public void remove(Item item) {
items.remove(item);
notifyListeners(new ItemAddedEvent(item, this));
notifyListeners(new ItemRemovedEvent(item, this));
}
/**
@@ -248,4 +249,8 @@ public class ShipMap {
if (eventBroker != null)
eventBroker.notifyListeners(event);
}
public void add(Shell shell) {
addItem(shell);
}
}

View File

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

View File

@@ -25,4 +25,11 @@ public interface VoidVisitor {
* @param ship the Battleship element to visit
*/
void visit(Battleship ship);
/**
* Visits a Shell element
* @param shell the Shell element to visit
*/
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 flying Shell
*/
SHELL_FLYING
}

View File

@@ -25,10 +25,12 @@ button.cancel=Cancel
server.dialog=Server
host.name=Host
port.number=Port
server.host= Self-Host Game
wait.its.not.your.turn=Wait, it's not your turn!!
menu.quit=Quit game
menu.return-to-game=Return to game
menu.sound-enabled=Sound switched on
menu.background-sound-enabled=Music switched on
menu.map.load=Load map from file...
menu.map.save=Save map in file...
label.file=File:

View File

@@ -25,10 +25,12 @@ button.cancel=Abbruch
server.dialog=Server
host.name=Host
port.number=Port
server.host= Spiel selbst hosten
wait.its.not.your.turn=Warte, Du bist nicht dran!!
menu.quit=Spiel beenden
menu.return-to-game=Zurück zum Spiel
menu.sound-enabled=Sound eingeschaltet
menu.background-sound-enabled=Musik eingeschaltet
menu.map.load=Karte von Datei laden...
menu.map.save=Karte in Datei speichern...
label.file=Datei:
@@ -37,3 +39,4 @@ dialog.error=Fehler
dialog.question=Frage
port.must.be.integer=Der Port muss eine ganze Zahl sein
map.doesnt.fit=Diese Karte passt nicht zu diesem Spiel

View File

@@ -7,6 +7,15 @@
package pp.battleship.server;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.LogManager;
import com.jme3.network.ConnectionListener;
import com.jme3.network.HostedConnection;
import com.jme3.network.Message;
@@ -14,10 +23,12 @@ import com.jme3.network.MessageListener;
import com.jme3.network.Network;
import com.jme3.network.Server;
import com.jme3.network.serializing.Serializer;
import pp.battleship.BattleshipConfig;
import pp.battleship.game.server.Player;
import pp.battleship.game.server.ServerGameLogic;
import pp.battleship.game.server.ServerSender;
import pp.battleship.message.client.AnimationFinishedMessage;
import pp.battleship.message.client.ClientMessage;
import pp.battleship.message.client.MapMessage;
import pp.battleship.message.client.ShootMessage;
@@ -29,15 +40,6 @@ import pp.battleship.model.Battleship;
import pp.battleship.model.IntPoint;
import pp.battleship.model.Shot;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.LogManager;
/**
* Server implementing the visitor pattern as MessageReceiver for ClientMessages
*/
@@ -118,12 +120,14 @@ public class BattleshipServer implements MessageListener<HostedConnection>, Conn
Serializer.registerClass(Battleship.class);
Serializer.registerClass(IntPoint.class);
Serializer.registerClass(Shot.class);
Serializer.registerClass(AnimationFinishedMessage.class);
}
private void registerListeners() {
myServer.addMessageListener(this, MapMessage.class);
myServer.addMessageListener(this, ShootMessage.class);
myServer.addConnectionListener(this);
myServer.addMessageListener(this, AnimationFinishedMessage.class);
}
@Override