14 Commits

Author SHA1 Message Date
Timo Brennförder
a38366600c fixed a bug where the SHIPDESTROYED Sound was played everytime 2024-10-14 11:12:07 +02:00
Timo Brennförder
8c45784246 Code cleanup
added JavaDocs
removed unnecessary lines
2024-10-13 01:59:46 +02:00
Timo Brennförder
febdd63422 solution for number 13
added an AnimationState in Client and Server
added 2D and 3D representation of a missile
added missile launch sound
updated Singlemode to continue functionality
2024-10-12 18:24:33 +02:00
Timo Brennförder
264b854cbe bug fix
fixed first few fire frames being displayed at the edge of the map
added README.txt files for used images
2024-10-10 23:26:15 +02:00
Timo Brennförder
24f20f855f solution for number 12
added water splash for misfires
added explosion, debris and fire for hit
2024-10-10 21:51:11 +02:00
Timo Brennförder
dac84388fc added different music for different game states 2024-10-05 20:56:26 +02:00
Timo Brennförder
329d3d7372 reworked ex 8
return to EditorState if map is invalid
2024-10-05 12:59:38 +02:00
Timo Brennförder
22bcd55024 added JavaDocs
corrected typos
2024-10-04 18:05:26 +02:00
Timo Brennförder
161fa5cb22 Solution for exercise 11
added possibility to start own Server from client
added a Checkbox to the connection menu to manage starting own server
2024-10-04 17:57:45 +02:00
Timo Brennförder
9cfabdb15d added background music and improved model code
reduced switch case for creating different ship models
created a new class for background music
added a button to toggle background music
added a slider so adjust volume
added new style for labeling the slider
2024-10-03 22:08:26 +02:00
Timo Brennförder
3bcaca8810 activated Singlemode and added different ship models depending on size
1 -> Patrol boat
2 -> BattleshipV2
3 -> Uboat
4 -> King George V
default -> boxes of given length
2024-10-03 16:49:44 +02:00
Timo Brennförder
0f70f4691d added logic for server- and clientside verification of JSON-files 2024-10-02 19:38:42 +02:00
Timo Brennförder
b56f4d35a3 corrected an error in the BattleState class
receivedEffect-function added remaining Opponent Ships to ownMap instead of opponentMap
2024-10-02 12:12:51 +02:00
Timo Brennförder
09f3e9e403 corrected an error in ShipMap.java.
remove-function called a new ItemAddedEvent instead of a ItemRemovedEvent
2024-10-02 11:48:58 +02:00
162 changed files with 906754 additions and 1484 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -9,7 +9,6 @@ implementation project(":jme-common")
implementation project(":battleship:model")
implementation libs.jme3.desktop
runtimeOnly libs.jme3.awt.dialogs
runtimeOnly libs.jme3.plugins
runtimeOnly libs.jme3.jogg

View File

@@ -9,7 +9,7 @@
#
# Specifies the map used by the opponent in single mode.
# Single mode is activated if this property is set.
#map.opponent=maps/map2.json
map.opponent=maps/map2.json
#
# Specifies the map used by the player in single mode.
# The player must define their own map if this property is not set.

View File

@@ -0,0 +1,238 @@
package pp.battleship.client;
import com.jme3.app.Application;
import com.jme3.audio.AudioData.DataType;
import com.jme3.audio.AudioNode;
import com.jme3.audio.AudioSource.Status;
import pp.battleship.notification.Music;
import pp.battleship.notification.MusicEvent;
import pp.battleship.notification.GameEventListener;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import java.util.prefs.Preferences;
/**
* Class to play Background music in game
*/
public class BackgroundMusic implements GameEventListener {
private static final String VOLUME_PREF = "volume";
private static final String MUSIC_ENABLED_PREF = "musicEnabled";
private final Preferences pref = Preferences.userNodeForPackage(BackgroundMusic.class);
static final Logger LOGGER = System.getLogger(BackgroundMusic.class.getName());
private static final String MENU_MUSIC = "Sound/Music/menu/cinematictrailerelite.ogg";
private static final String GAME_MUSIC = "Sound/Music/game/Aluminum.ogg";
private static final String VICTORY_MUSIC = "Sound/Music/victory/victorymarchofvalor.ogg";
private static final String LOSE_MUSIC = "Sound/Music/lose/TouchofDream.ogg";
private final AudioNode menuMusic;
private final AudioNode gameMusic;
private final AudioNode victoryMusic;
private final AudioNode loseMusic;
private String lastPlayedMusic;
private boolean musicEnabled;
private float volume;
private Application app;
/**
* Constructor for BackgroundMusic class
*
* @param app The main Application
*/
public BackgroundMusic(Application app) {
this.volume = pref.getFloat(VOLUME_PREF, 1.0f);
this.musicEnabled = pref.getBoolean(MUSIC_ENABLED_PREF, true);
this.app = app;
menuMusic = createMusicNode(MENU_MUSIC);
gameMusic = createMusicNode(GAME_MUSIC);
victoryMusic = createMusicNode(VICTORY_MUSIC);
loseMusic = createMusicNode(LOSE_MUSIC);
stop(gameMusic);
stop(victoryMusic);
stop(loseMusic);
lastPlayedMusic = menuMusic.getName();
if (musicEnabled) {
play(menuMusic);
}
}
/**
* Creates an audio node for the music
*
* @param musicFilePath the file path to the music
* @return the created audio node
*/
private AudioNode createMusicNode(String musicFilePath) {
AudioNode audioNode = new AudioNode(app.getAssetManager(), musicFilePath, DataType.Stream);
audioNode.setVolume(volume);
audioNode.setPositional(false);
audioNode.setLooping(true);
audioNode.setName(musicFilePath);
return audioNode;
}
/**
* Starts the music
*
* @param audioNode the audio node to be played
*/
public void play(AudioNode audioNode) {
if (musicEnabled && (audioNode.getStatus() == Status.Stopped || audioNode.getStatus() == Status.Paused)) {
audioNode.play();
lastPlayedMusic = audioNode.getName();
}
}
/**
* Pauses the music
*
* @param audioNode the audio node to be paused
*/
public void pause(AudioNode audioNode) {
if (audioNode.getStatus() == Status.Playing) {
audioNode.pause();
}
}
/**
* Stops the music
*
* @param audioNode the audio node to be stopped
*/
public void stop(AudioNode audioNode) {
if (audioNode.getStatus() == Status.Playing) {
audioNode.stop();
}
}
/**
* Controls which music should be played
*/
public void toggleMusic() {
this.musicEnabled = !this.musicEnabled;
if (musicEnabled) {
switch (lastPlayedMusic) {
case MENU_MUSIC:
play(menuMusic);
break;
case GAME_MUSIC:
play(gameMusic);
break;
case VICTORY_MUSIC:
play(victoryMusic);
break;
case LOSE_MUSIC:
play(loseMusic);
break;
}
}
else {
pause(menuMusic);
pause(gameMusic);
pause(victoryMusic);
pause(loseMusic);
}
pref.putBoolean(MUSIC_ENABLED_PREF, musicEnabled);
}
/**
* Changes the music to the specified music if it isn't already playing
*
* @param music the music to play
*/
public void changeMusic(Music music) {
if (music == Music.MENU_THEME && !lastPlayedMusic.equals(MENU_MUSIC)) {
LOGGER.log(Level.DEBUG, "Received Music change Event {0}", music.toString());
stop(gameMusic);
stop(victoryMusic);
stop(loseMusic);
play(menuMusic);
lastPlayedMusic = menuMusic.getName();
}
else if (music == Music.GAME_THEME && !lastPlayedMusic.equals(GAME_MUSIC)) {
LOGGER.log(Level.DEBUG, "Received Music change Event {0}", music.toString());
stop(menuMusic);
stop(loseMusic);
stop(victoryMusic);
play(gameMusic);
lastPlayedMusic = gameMusic.getName();
}
else if (music == Music.VICTORY_THEME && !lastPlayedMusic.equals(VICTORY_MUSIC)) {
LOGGER.log(Level.DEBUG, "Received Music change Event {0}", music.toString());
stop(menuMusic);
stop(gameMusic);
stop(loseMusic);
play(victoryMusic);
lastPlayedMusic = victoryMusic.getName();
}
else if (music == Music.LOSE_THEME && !lastPlayedMusic.equals(LOSE_MUSIC)) {
LOGGER.log(Level.DEBUG, "Received Music change Event {0}", music.toString());
stop(menuMusic);
stop(gameMusic);
stop(victoryMusic);
play(loseMusic);
lastPlayedMusic = loseMusic.getName();
}
}
/**
* Receives the different MusicEvents
*
* @param music the received Event
*/
@Override
public void receivedEvent(MusicEvent music) {
LOGGER.log(Level.DEBUG, "Received Music change Event {0}", music.toString());
switch (music.music()) {
case MENU_THEME:
changeMusic(Music.MENU_THEME);
break;
case GAME_THEME:
changeMusic(Music.GAME_THEME);
break;
case VICTORY_THEME:
changeMusic(Music.VICTORY_THEME);
break;
case LOSE_THEME:
changeMusic(Music.LOSE_THEME);
break;
}
}
/**
* Set the volume for the music
*
* @param volume float to transfer the new volume
*/
public void setVolume(float volume) {
this.volume = volume;
menuMusic.setVolume(volume);
gameMusic.setVolume(volume);
victoryMusic.setVolume(volume);
loseMusic.setVolume(volume);
pref.putFloat(VOLUME_PREF, volume);
}
/**
* Returns the volume
*
* @return the current volume as a float
*/
public float getVolume() {
return volume;
}
/**
* Returns if music should be played or not
*
* @return boolean value in music should be played
*/
public boolean isMusicEnabled() {
return musicEnabled;
}
}

View File

@@ -1,10 +1,3 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.client;
import com.jme3.app.DebugKeysAppState;
@@ -122,6 +115,11 @@ public class BattleshipApp extends SimpleApplication implements BattleshipClient
*/
private final ActionListener escapeListener = (name, isPressed, tpf) -> escape(isPressed);
/**
* Object handling the background music
*/
private BackgroundMusic backgroundMusic;
static {
// Configure logging
LogManager manager = LogManager.getLogManager();
@@ -225,6 +223,8 @@ public void simpleInitApp() {
setupStates();
setupGui();
serverConnection.connect();
backgroundMusic = new BackgroundMusic(this);
logic.addListener(backgroundMusic);
}
/**
@@ -315,6 +315,10 @@ public Draw getDraw() {
return draw;
}
public BackgroundMusic getBackgroundMusic() {
return backgroundMusic;
}
/**
* Handles a request to close the application.
* If the request is initiated by pressing ESC, this parameter is true.

View File

@@ -1,10 +1,3 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.client;
import com.jme3.math.ColorRGBA;

View File

@@ -1,10 +1,3 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.client;
import com.jme3.app.Application;

View File

@@ -1,10 +1,3 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.client;
import com.jme3.app.Application;
@@ -15,6 +8,7 @@
import com.jme3.audio.AudioData;
import com.jme3.audio.AudioNode;
import pp.battleship.notification.GameEventListener;
import pp.battleship.notification.Sound;
import pp.battleship.notification.SoundEvent;
import java.lang.System.Logger;
@@ -27,13 +21,14 @@
* An application state that plays sounds.
*/
public class GameSound extends AbstractAppState implements GameEventListener {
private static final Logger LOGGER = System.getLogger(GameSound.class.getName());
static final Logger LOGGER = System.getLogger(GameSound.class.getName());
private static final Preferences PREFERENCES = getPreferences(GameSound.class);
private static final String ENABLED_PREF = "enabled"; //NON-NLS
private AudioNode splashSound;
private AudioNode shipDestroyedSound;
private AudioNode explosionSound;
private AudioNode missileLaunch;
/**
* Checks if sound is enabled in the preferences.
@@ -78,6 +73,7 @@ public void initialize(AppStateManager stateManager, Application app) {
shipDestroyedSound = loadSound(app, "Sound/Effects/sunken.wav"); //NON-NLS
splashSound = loadSound(app, "Sound/Effects/splash.wav"); //NON-NLS
explosionSound = loadSound(app, "Sound/Effects/explosion.wav"); //NON-NLS
missileLaunch = loadSound(app, "Sound/Effects/missilefiring.wav"); //NON-NLS
}
/**
@@ -100,6 +96,14 @@ private AudioNode loadSound(Application app, String name) {
return null;
}
/**
* Plays the splash sound effect.
*/
public void missileLaunch() {
if (isEnabled() && missileLaunch != null)
missileLaunch.playInstance();
}
/**
* Plays the splash sound effect.
*/
@@ -124,12 +128,18 @@ public void shipDestroyed() {
shipDestroyedSound.playInstance();
}
/**
* Plays sound according to the received SoundEvent
*
* @param event the received SoundEvent
*/
@Override
public void receivedEvent(SoundEvent event) {
switch (event.sound()) {
case EXPLOSION -> explosion();
case SPLASH -> splash();
case DESTROYED_SHIP -> shipDestroyed();
case MISSILE_LAUNCH -> missileLaunch();
}
}
}

View File

@@ -1,15 +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;
import com.simsilica.lemur.Button;
import com.simsilica.lemur.Checkbox;
import com.simsilica.lemur.DefaultRangedValueModel;
import com.simsilica.lemur.Label;
import com.simsilica.lemur.Slider;
import com.simsilica.lemur.core.VersionedReference;
import com.simsilica.lemur.style.ElementId;
import pp.dialog.Dialog;
import pp.dialog.StateCheckboxModel;
@@ -33,6 +29,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 VersionedReference<Double> volumeRef;
/**
* Constructs the Menu dialog for the Battleship application.
@@ -45,6 +42,19 @@ public Menu(BattleshipApp app) {
addChild(new Label(lookup("battleship.name"), new ElementId("header"))); //NON-NLS
addChild(new Checkbox(lookup("menu.sound-enabled"),
new StateCheckboxModel(app, GameSound.class)));
Checkbox musicToggle = new Checkbox(lookup("menu.music.toggle"));
musicToggle.setChecked(app.getBackgroundMusic().isMusicEnabled());
musicToggle.addClickCommands(s -> toggleMusic());
addChild(musicToggle);
addChild(new Label(lookup("menu.music.volume"), new ElementId("slider_label")));
Slider volumeSlider = new Slider();
volumeSlider.setModel(new DefaultRangedValueModel(0.00, 1.00, app.getBackgroundMusic().getVolume()));
volumeSlider.setDelta(0.05);
addChild(volumeSlider);
volumeRef = volumeSlider.getModel().createReference();
addChild(loadButton)
.addClickCommands(s -> ifTopDialog(this::loadDialog));
addChild(saveButton)
@@ -53,9 +63,39 @@ public Menu(BattleshipApp app) {
.addClickCommands(s -> ifTopDialog(this::close));
addChild(new Button(lookup("menu.quit")))
.addClickCommands(s -> ifTopDialog(app::closeApp));
update();
}
/**
* Updates the volume when the slider is moved
*
* @param tpf time per frame
*/
@Override
public void update(float tpf) {
if (volumeRef.update()) {
double newVolume = volumeRef.get();
adjustVolume(newVolume);
}
}
/**
* Adjusts the volume for the background music
*
* @param volume is the double value of the volume
*/
private void adjustVolume(double volume) {
app.getBackgroundMusic().setVolume((float) volume);
}
/**
* Toggles the background music on and off
*/
private void toggleMusic() {
app.getBackgroundMusic().toggleMusic();
}
/**
* Updates the state of the load and save buttons based on the game logic.
*/

View File

@@ -1,12 +1,6 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.client;
import com.simsilica.lemur.Checkbox;
import com.simsilica.lemur.Container;
import com.simsilica.lemur.Label;
import com.simsilica.lemur.TextField;
@@ -14,6 +8,7 @@
import pp.dialog.Dialog;
import pp.dialog.DialogBuilder;
import pp.dialog.SimpleDialog;
import server.BattleshipServer;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
@@ -37,6 +32,7 @@ class NetworkDialog extends SimpleDialog {
private int portNumber;
private Future<Object> connectionFuture;
private Dialog progressDialog;
private boolean hostServer = false;
/**
* Constructs a new NetworkDialog.
@@ -50,12 +46,17 @@ class NetworkDialog extends SimpleDialog {
host.setPreferredWidth(400f);
port.setSingleLine(true);
Checkbox hostServer = new Checkbox(lookup("start.own.server"));
hostServer.setChecked(false);
hostServer.addClickCommands(s -> toggleOwnServer());
final BattleshipApp app = network.getApp();
final Container input = new Container(new SpringGridLayout());
input.addChild(new Label(lookup("host.name") + ": "));
input.addChild(host, 1);
input.addChild(new Label(lookup("port.number") + ": "));
input.addChild(port, 1);
input.addChild(hostServer);
DialogBuilder.simple(app.getDialogManager())
.setTitle(lookup("server.dialog"))
@@ -68,10 +69,10 @@ class NetworkDialog extends SimpleDialog {
}
/**
* Handles the action for the connect button in the connection dialog.
* Handles the action for establishing the connection to a server.
* Tries to parse the port number and initiate connection to the server.
*/
private void connect() {
private void connectToServer() {
LOGGER.log(Level.INFO, "connect to host={0}, port={1}", host, port); //NON-NLS
try {
hostname = host.getText().trim().isEmpty() ? LOCALHOST : host.getText();
@@ -150,4 +151,46 @@ private void failure(Throwable e) {
network.getApp().errorDialog(lookup("server.connection.failed"));
network.getApp().setInfoText(e.getLocalizedMessage());
}
/**
* Handles the action for the connect-button.
* If hostServer-Checkbox is active, starts a new Server on the clients machine, else tries to connect to existing server
*/
private void connect() {
if (hostServer) {
startServer();
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
LOGGER.log(Level.WARNING, e.getMessage(), e);
}
connectToServer();
}
else {
connectToServer();
}
}
/**
* Starts a server on the clients machine
*/
private void startServer() {
new Thread(() -> {
try {
BattleshipServer battleshipServer = new BattleshipServer(Integer.parseInt(port.getText()));
battleshipServer.run();
}
catch (Exception e) {
LOGGER.log(Level.ERROR, e);
}
}).start();
}
/**
* Handles the action for the hostServer-Checkbox
*/
private void toggleOwnServer() {
hostServer = !hostServer;
}
}

View File

@@ -1,10 +1,3 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.client;
import com.jme3.network.Client;

View File

@@ -1,9 +1,4 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.client.gui;

View File

@@ -1,9 +1,4 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.client.gui;

View File

@@ -0,0 +1,181 @@
package pp.battleship.client.gui;
import com.jme3.app.Application;
import com.jme3.asset.AssetManager;
import com.jme3.effect.ParticleEmitter;
import com.jme3.effect.ParticleMesh.Type;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector3f;
import com.jme3.scene.Node;
import com.jme3.scene.control.AbstractControl;
import pp.battleship.model.Shot;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
public class HitEffectHandler {
private final AssetManager assetManager;
private static final Logger LOGGER = System.getLogger(HitEffectHandler.class.getName());
/**
* Constructor for the HitEffectHandler class
*
* @param app the main application
*/
public HitEffectHandler(Application app) {
assetManager = app.getAssetManager();
}
/**
* Creates explosion, debris and fire effects when ship gets hit
*
* @param battleshipNode the node of the ship that gets hit and the effect should be attached to
* @param shot The shot taken on a field
*/
public void hitEffect(Node battleshipNode, Shot shot) {
//Explosion
ParticleEmitter explosion = new ParticleEmitter("Explosion", Type.Triangle, 30);
explosion.setMaterial(new Material(assetManager, "Common/MatDefs/Misc/Particle.j3md"));
explosion.setImagesX(2);
explosion.setImagesY(2);
explosion.setStartColor(new ColorRGBA(0.96f, 0.82f, 0.6f, 1f));
explosion.setEndColor(new ColorRGBA(0.88f, 0.32f, 0.025f, 1f));
explosion.getParticleInfluencer().setInitialVelocity(new Vector3f(0, 1, 0));
explosion.setStartSize(0.45f);
explosion.setEndSize(0.1f);
explosion.setGravity(0, -0.5f, 0);
explosion.setLowLife(1f);
explosion.setHighLife(3.5f);
explosion.setParticlesPerSec(0);
explosion.setLocalTranslation(shot.getY() + 0.5f, 0, shot.getX() + 0.5f);
explosion.emitAllParticles();
//Debris
ParticleEmitter debris = new ParticleEmitter("Debris", Type.Triangle, 6);
Material debrisMaterial = new Material(assetManager, "Common/MatDefs/Misc/Particle.j3md");
debrisMaterial.setTexture("Texture", assetManager.loadTexture("Textures/Debris/debris.png"));
debris.setMaterial(debrisMaterial);
debris.setImagesX(2);
debris.setImagesY(2);
debris.setStartColor(ColorRGBA.White);
debris.setEndColor(ColorRGBA.White);
debris.getParticleInfluencer().setInitialVelocity(new Vector3f(0.25f, 2f, 0.25f));
debris.setStartSize(0.25f);
debris.setEndSize(0.1f);
debris.setGravity(0, 1.5f, 0);
debris.getParticleInfluencer().setVelocityVariation(0.3f);
debris.setLowLife(1f);
debris.setHighLife(3.5f);
debris.setParticlesPerSec(0);
debris.setLocalTranslation(shot.getY() + 0.5f, 0, shot.getX() + 0.5f);
debris.emitAllParticles();
//Fire
ParticleEmitter fire = new ParticleEmitter("Fire", Type.Triangle, 30);
Material fireMaterial = new Material(assetManager, "Common/MatDefs/Misc/Particle.j3md");
fireMaterial.setTexture("Texture", assetManager.loadTexture("Textures/Fire/fire.png"));
fire.setMaterial(fireMaterial);
fire.setImagesX(2);
fire.setImagesY(2);
fire.setStartColor(ColorRGBA.Orange);
fire.setEndColor(ColorRGBA.Red);
fire.getParticleInfluencer().setInitialVelocity(new Vector3f(0, 1.5f, 0));
fire.setStartSize(0.2f);
fire.setEndSize(0.05f);
fire.setLowLife(1f);
fire.setHighLife(2f);
fire.getParticleInfluencer().setVelocityVariation(0.2f);
fire.setLocalTranslation(shot.getY() + 0.5f, 0f, shot.getX() + 0.5f);
fire.getLocalTranslation().subtractLocal(battleshipNode.getLocalTranslation());
battleshipNode.attachChild(fire);
fire.emitAllParticles();
// LOGGER.log(Level.DEBUG, "Created HitEffect at {0}", explosion.getLocalTranslation().toString());
// LOGGER.log(Level.DEBUG, "Created HitEffect at {0}", debris.getLocalTranslation().toString());
// LOGGER.log(Level.INFO, "Created HitEffect at {0}", fire.getLocalTranslation().toString());
battleshipNode.attachChild(explosion);
explosion.addControl(new EffectControl(explosion, battleshipNode));
fire.addControl(new EffectControl(fire, battleshipNode));
battleshipNode.attachChild(debris);
debris.addControl(new EffectControl(debris, battleshipNode));
}
/**
* Creates a splash effect if the shot hits the water
*
* @param shot The shot taken on a field
*/
public ParticleEmitter missEffect(Shot shot) {
ParticleEmitter missEffect = new ParticleEmitter("HitEffect", Type.Triangle, 45);
missEffect.setMaterial(new Material(assetManager, "Common/MatDefs/Misc/Particle.j3md"));
missEffect.setImagesX(2);
missEffect.setImagesY(2);
missEffect.setStartColor(new ColorRGBA(0.067f, 0.06f, 0.37f, 0.87f));
missEffect.setEndColor(new ColorRGBA(0.32f, 0.55f, 0.87f, 0.79f));
missEffect.getParticleInfluencer().setInitialVelocity(new Vector3f(0, 1, 0));
missEffect.setStartSize(0.1f);
missEffect.setEndSize(0.08f);
missEffect.setGravity(0, 0.36f, 0);
missEffect.setLowLife(0.7f);
missEffect.setHighLife(1.8f);
missEffect.setParticlesPerSec(0);
missEffect.setLocalTranslation(shot.getY() + 0.5f, 0, shot.getX() + 0.5f);
LOGGER.log(Level.DEBUG, "Created MissEffect at {0}", missEffect.getLocalTranslation().toString());
missEffect.emitAllParticles();
missEffect.addControl(new EffectControl(missEffect));
return missEffect;
}
/**
* Inner class to control effects
*/
private static class EffectControl extends AbstractControl {
private final ParticleEmitter emitter;
private final Node parentNode;
/**
* Constructor used to attach effect to a node
*
* @param emitter the particle emitter to be controlled
* @param parentNode the node to be attached
*/
public EffectControl(ParticleEmitter emitter, Node parentNode) {
this.emitter = emitter;
this.parentNode = parentNode;
}
/**
* Constructor used if the effect shouldn't be attached to a node
*
* @param emitter the particle emitter to be controlled
*/
public EffectControl(ParticleEmitter emitter) {
this.emitter = emitter;
this.parentNode = null;
}
/**
* Checks if the Effect is not rendered anymore so it can be removed
*
* @param tpf time per frame (in seconds)
*/
@Override
protected void controlUpdate(float tpf) {
if (emitter.getParticlesPerSec() == 0 && emitter.getNumVisibleParticles() == 0) {
if (parentNode != null)
parentNode.detachChild(emitter);
}
}
/**
* @param rm the RenderManager rendering the controlled Spatial (not null)
* @param vp the ViewPort being rendered (not null)
*/
@Override
protected void controlRender(com.jme3.renderer.RenderManager rm, com.jme3.renderer.ViewPort vp) {}
}
}

View File

@@ -1,9 +1,4 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.client.gui;

View File

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

View File

@@ -1,9 +1,4 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.client.gui;

View File

@@ -1,15 +1,12 @@
////////////////////////////////////////
// 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 com.jme3.material.Material;
import com.jme3.material.RenderState;
import com.jme3.material.RenderState.BlendMode;
import com.jme3.math.ColorRGBA;
import com.jme3.renderer.queue.RenderQueue;
import com.jme3.renderer.queue.RenderQueue.ShadowMode;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
@@ -18,6 +15,7 @@
import com.jme3.scene.shape.Cylinder;
import pp.battleship.client.BattleshipApp;
import pp.battleship.model.Battleship;
import pp.battleship.model.Shell;
import pp.battleship.model.Rotation;
import pp.battleship.model.ShipMap;
import pp.battleship.model.Shot;
@@ -34,13 +32,21 @@
*/
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/KingGeorgeV/KingGeorgeV.j3o";
private static final String UBOAT_MODEL = "Models/UBOAT/14084_WWII_Ship_German_Type_II_U-boat_v2_L1.obj";
private static final String PATROL_BOAT_MODEL = "Models/PATROL_BOAT/12219_boat_v2_L2.obj";
private static final String MODERN_BATTLESHIP_MODEL = "Models/BATTLESHIP/10619_Battleship.obj";
private static final String MODERN_BATTLESHIP_TEXTURES = "Models/BATTLESHIP/BattleshipC.jpg";
private static final String MISSILE_MODEL = "Models/Missile/AIM120D.obj";
private static final String MISSILE_TEXTURE = "Models/Missile/texture.png";
private static final String COLOR = "Color"; //NON-NLS
private static final String SHIP = "ship"; //NON-NLS
private static final String SHOT = "shot"; //NON-NLS
private static final String MISSILE = "missile"; //NON-NLS
private static final ColorRGBA BOX_COLOR = ColorRGBA.Gray;
private static final ColorRGBA SPLASH_COLOR = new ColorRGBA(0f, 0f, 1f, 0.4f);
private static final ColorRGBA HIT_COLOR = new ColorRGBA(1f, 0f, 0f, 0.4f);
private final HitEffectHandler hitEffectHandler;
private final ShipMap map;
private final BattleshipApp app;
@@ -56,6 +62,7 @@ public SeaSynchronizer(BattleshipApp app, Node root, ShipMap map) {
super(app.getGameLogic().getOwnMap(), root);
this.app = app;
this.map = map;
hitEffectHandler = new HitEffectHandler(app);
addExisting();
}
@@ -69,7 +76,7 @@ public SeaSynchronizer(BattleshipApp app, Node root, ShipMap map) {
*/
@Override
public Spatial visit(Shot shot) {
return shot.isHit() ? handleHit(shot) : createCylinder(shot);
return shot.isHit() ? handleHit(shot) : hitEffectHandler.missEffect(shot);
}
/**
@@ -84,9 +91,7 @@ private Spatial handleHit(Shot shot) {
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);
hitEffectHandler.hitEffect(shipNode, shot);
return null;
}
@@ -133,6 +138,24 @@ public Spatial visit(Battleship ship) {
return node;
}
/**
* Visits a Shell and creates a graphical representation of it.
*
* @param shell the Shell to be represented
* @return the node containing the graphical representation of the Shell
*/
@Override
public Spatial visit(Shell shell) {
final Node node = new Node(MISSILE);
node.attachChild(createMissile());
final float x = shell.getY();
final float z = shell.getX();
node.setLocalTranslation(x + 0.5f, 10f, z + 0.5f);
node.addControl(new ShellControl(shell, app));
return node;
}
/**
* Creates the appropriate graphical representation of the specified battleship.
* The representation is either a detailed model or a simple box based on the length of the ship.
@@ -141,7 +164,13 @@ public Spatial visit(Battleship ship) {
* @return the spatial representing the battleship
*/
private Spatial createShip(Battleship ship) {
return ship.getLength() == 4 ? createBattleship(ship) : createBox(ship);
return switch (ship.getLength()) {
case 1 -> createPatrolBoat(ship);
case 2 -> createModernBattleship(ship);
case 3 -> createUboat(ship);
case 4 -> createBattleship(ship);
default -> createBox(ship);
};
}
/**
@@ -196,6 +225,86 @@ private Spatial createBattleship(Battleship ship) {
return model;
}
/**
* Creates a detailed 3D model to represent a modern battleship.
*
* @param ship the battleship to be represented
* @return the spatial representing the battleship
*/
private Spatial createModernBattleship(Battleship ship) {
final Spatial model = app.getAssetManager().loadModel(MODERN_BATTLESHIP_MODEL);
Material mat = new Material(app.getAssetManager(), UNSHADED);
mat.setTexture("ColorMap", app.getAssetManager().loadTexture(MODERN_BATTLESHIP_TEXTURES));
mat.getAdditionalRenderState().setBlendMode(RenderState.BlendMode.Off);
model.setMaterial(mat);
model.setQueueBucket(RenderQueue.Bucket.Opaque);
model.rotate(-HALF_PI, calculateRotationAngle(ship.getRot()) + HALF_PI, 0f);
model.scale(0.000075f);
model.setShadowMode(ShadowMode.CastAndReceive);
model.move(0, 0.2f, 0);
return model;
}
/**
* Creates a detailed 3D model to represent a missile.
*
* @return the spatial representing the missile
*/
private Spatial createMissile() {
final Spatial model = app.getAssetManager().loadModel(MISSILE_MODEL);
Material mat = new Material(app.getAssetManager(), UNSHADED);
mat.setTexture("ColorMap", app.getAssetManager().loadTexture(MISSILE_TEXTURE));
mat.getAdditionalRenderState().setBlendMode(RenderState.BlendMode.Off);
model.setMaterial(mat);
model.setQueueBucket(RenderQueue.Bucket.Opaque);
model.rotate(-HALF_PI, 0, 0);
model.scale(0.009f);
model.setShadowMode(ShadowMode.CastAndReceive);
model.move(0, 0f, 0);
return model;
}
/**
* Creates a detailed 3D model to represent a Uboat.
*
* @param ship the battleship to be represented
* @return the spatial representing the Uboat
*/
private Spatial createUboat(Battleship ship) {
final Spatial model = app.getAssetManager().loadModel(UBOAT_MODEL);
model.rotate(-HALF_PI, calculateRotationAngle(ship.getRot()), 0f);
model.scale(0.45f);
model.setShadowMode(ShadowMode.CastAndReceive);
model.move(0, -0.25f, 0);
return model;
}
/**
* Creates a detailed 3D model to represent a Patrol boat.
*
* @param ship the battleship to be represented
* @return the spatial representing the Patrol boat
*/
private Spatial createPatrolBoat(Battleship ship) {
final Spatial model = app.getAssetManager().loadModel(PATROL_BOAT_MODEL);
model.rotate(-HALF_PI, calculateRotationAngle(ship.getRot()), 0f);
model.scale(0.00045f);
model.setShadowMode(ShadowMode.CastAndReceive);
return model;
}
/**
* Calculates the rotation angle for the specified rotation.
*

View File

@@ -0,0 +1,62 @@
package pp.battleship.client.gui;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.control.AbstractControl;
import pp.battleship.client.BattleshipApp;
import pp.battleship.message.client.EndAnimationMessage;
import pp.battleship.model.IntPoint;
import pp.battleship.model.Shell;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
/**
* Class to control the 3D representation of a shell
*/
public class ShellControl extends AbstractControl {
private final Shell shell;
private final BattleshipApp app;
private static final float TRAVEL_SPEED = 8.5f;
static final Logger LOGGER = System.getLogger(BattleshipApp.class.getName());
/**
* Constructor for ShellControl class
*
* @param shell The Shell to be displayed
* @param app the main application
*/
public ShellControl(Shell shell, BattleshipApp app) {
this.shell = shell;
this.app = app;
}
/**
* Method to control movement of the Shell and remove it when target is reached
*
* @param tpf time per frame (in seconds)
*/
@Override
public void controlUpdate(float tpf) {
//LOGGER.log(Level.DEBUG, "missile at x=" + shell.getX() + ", y=" + shell.getY());
spatial.move(0, -TRAVEL_SPEED * tpf, 0);
if (spatial.getLocalTranslation().getY() <= 0.2) {
spatial.getParent().detachChild(spatial);
app.getGameLogic().send(new EndAnimationMessage(new IntPoint(shell.getX(), shell.getY())));
}
}
/**
* 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) {
}
}

View File

@@ -0,0 +1,62 @@
package pp.battleship.client.gui;
import com.jme3.math.Vector3f;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.control.AbstractControl;
import pp.battleship.client.BattleshipApp;
import pp.battleship.message.client.EndAnimationMessage;
import pp.battleship.model.IntPoint;
import pp.util.Position;
/**
* Class to control the 2D representation of a shell
*/
public class ShellMapControl extends AbstractControl {
private final Position position;
private final IntPoint pos;
private static final Vector3f VECTOR_3_F = new Vector3f();
private final BattleshipApp app;
/**
* Constructor for ShellMapControl
*
* @param position the target position of the shell
* @param app the main application
* @param pos the position the then to render shot goes to
*/
public ShellMapControl(Position position, BattleshipApp app, IntPoint pos) {
super();
this.position = position;
this.pos = pos;
this.app = app;
VECTOR_3_F.set(new Vector3f(position.getX(), position.getY(), 0));
}
/**
* Method to control movement of the Shell on the map and remove it when target is reached
*
* @param tpf time per frame (in seconds)
*/
@Override
protected void controlUpdate(float tpf) {
spatial.move(VECTOR_3_F.mult(tpf));
if (spatial.getLocalTranslation().getX() >= position.getX() && spatial.getLocalTranslation().getY() >= position.getY()) {
spatial.getParent().detachChild(spatial);
app.getGameLogic().send(new EndAnimationMessage(pos));
}
}
/**
* 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) {
}
}

View File

@@ -1,9 +1,4 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.client.gui;
@@ -14,6 +9,9 @@
import com.jme3.scene.control.AbstractControl;
import pp.battleship.model.Battleship;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import static pp.util.FloatMath.DEG_TO_RAD;
import static pp.util.FloatMath.TWO_PI;
import static pp.util.FloatMath.sin;
@@ -47,6 +45,12 @@ class ShipControl extends AbstractControl {
* The current time within the oscillation cycle, used to calculate the ship's pitch angle.
*/
private float time;
/**
* Ship to be controlled
*/
private final Battleship battleship;
private static final Logger LOGGER = System.getLogger(ShipControl.class.getName());
/**
* Constructs a new ShipControl instance for the specified Battleship.
@@ -56,6 +60,7 @@ class ShipControl extends AbstractControl {
* @param ship the Battleship object to control
*/
public ShipControl(Battleship ship) {
this.battleship = ship;
// Determine the axis of rotation based on the ship's orientation
axis = switch (ship.getRot()) {
case LEFT, RIGHT -> Vector3f.UNIT_X;
@@ -63,7 +68,7 @@ public ShipControl(Battleship ship) {
};
// Set the cycle duration and amplitude based on the ship's length
cycle = ship.getLength() * 2f;
cycle = battleship.getLength() * 2f;
amplitude = 5f * DEG_TO_RAD / ship.getLength();
}
@@ -78,14 +83,23 @@ protected void controlUpdate(float tpf) {
// If spatial is null, do nothing
if (spatial == null) return;
// Update the time within the oscillation cycle
time = (time + tpf) % cycle;
if (battleship.isDestroyed() && spatial.getLocalTranslation().getY() < -0.6f) {
LOGGER.log(Level.INFO, "Ship removed {0}", spatial.getName());
spatial.getParent().detachChild(spatial);
}
else if (battleship.isDestroyed()) {
spatial.move(0, -0.2f * tpf, 0);
}
else {
// Update the time within the oscillation cycle
time = (time + tpf) % cycle;
// Calculate the current angle of the oscillation
final float angle = amplitude * sin(time * TWO_PI / cycle);
// Calculate the current angle of the oscillation
final float angle = amplitude * sin(time * TWO_PI / cycle);
// Update the pitch Quaternion with the new angle
pitch.fromAngleAxis(angle, axis);
// Update the pitch Quaternion with the new angle
pitch.fromAngleAxis(angle, axis);
}
// Apply the pitch rotation to the spatial
spatial.setLocalRotation(pitch);

View File

@@ -1,9 +1,4 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.client.gui;

View File

@@ -0,0 +1,211 @@
package server;
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.ClientMessage;
import pp.battleship.message.client.EndAnimationMessage;
import pp.battleship.message.client.MapMessage;
import pp.battleship.message.client.ShootMessage;
import pp.battleship.message.server.EffectMessage;
import pp.battleship.message.server.GameDetails;
import pp.battleship.message.server.ServerMessage;
import pp.battleship.message.server.StartAnimationMessage;
import pp.battleship.message.server.StartBattleMessage;
import pp.battleship.message.server.SwitchToBattleState;
import pp.battleship.model.Battleship;
import pp.battleship.model.IntPoint;
import pp.battleship.model.Shot;
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
*/
public class BattleshipServer implements MessageListener<HostedConnection>, ConnectionListener, ServerSender {
private static final Logger LOGGER = System.getLogger(BattleshipServer.class.getName());
private static final File CONFIG_FILE = new File("server.properties");
private static int port;
private final BattleshipConfig config = new BattleshipConfig();
private Server myServer;
private final ServerGameLogic logic;
private final BlockingQueue<ReceivedMessage> 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());
}
}
/**
* Creates the server.
*/
public BattleshipServer(int port) {
config.readFromIfExists(CONFIG_FILE);
BattleshipServer.port = port;
LOGGER.log(Level.INFO, "Configuration: {0}", config); //NON-NLS
logic = new ServerGameLogic(this, config);
}
/**
* Runs a server
*/
public void run() {
startServer();
while (true)
processNextMessage();
}
/**
* Starts a server
*/
private void startServer() {
try {
LOGGER.log(Level.INFO, "Starting server..."); //NON-NLS
myServer = Network.createServer(port);
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);
}
}
/**
* Processes next received message
*/
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();
}
}
/**
* Registers all serializable classes
*/
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(StartAnimationMessage.class);
Serializer.registerClass(EndAnimationMessage.class);
Serializer.registerClass(SwitchToBattleState.class);
}
/**
* Registers all listeners
*/
private void registerListeners() {
myServer.addMessageListener(this, MapMessage.class);
myServer.addMessageListener(this, ShootMessage.class);
myServer.addMessageListener(this, EndAnimationMessage.class);
myServer.addConnectionListener(this);
}
/**
* Handles a received message
* @param source the connection the message comes from
* @param message the received message
*/
@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 ReceivedMessage(clientMessage, source.getId()));
}
/**
* Adds a new connection to a server
* @param server the server to add the connection to
* @param hostedConnection the connection to be added
*/
@Override
public void connectionAdded(Server server, HostedConnection hostedConnection) {
LOGGER.log(Level.INFO, "new connection {0}", hostedConnection); //NON-NLS
logic.addPlayer(hostedConnection.getId());
}
/**
* Removes a standing connection from a server
* @param server the server to add the connection to
* @param hostedConnection the connection to be added
*/
@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);
}
}
/**
* Shuts down the server and terminates the application with the given exit code
* @param exitValue the exit status code
*/
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 @@
package server;
import pp.battleship.message.client.ClientInterpreter;
import pp.battleship.message.client.ClientMessage;
/**
* Represents a message received from a client
* @param message the received message
* @param from the ID of the client that sent the message
*/
record ReceivedMessage(ClientMessage message, int from) {
void process(ClientInterpreter interpreter) {
message.accept(interpreter, from);
}
}

View File

@@ -0,0 +1,73 @@
newmtl Battleship
illum 4
Kd 0.00 0.00 0.00
Ka 0.00 0.00 0.00
Tf 1.00 1.00 1.00
map_Kd BattleshipC.jpg
Ni 1.00
Ks 0.00 0.00 0.00
Ns 256.00
newmtl blinn1SG
illum 4
Kd 0.50 0.50 0.50
Ka 0.00 0.00 0.00
Tf 1.00 1.00 1.00
Ni 1.00
Ks 0.00 0.00 0.00
Ns 256.00
newmtl blinn2SG
illum 4
Kd 0.50 0.50 0.50
Ka 0.00 0.00 0.00
Tf 1.00 1.00 1.00
Ni 1.00
Ks 0.00 0.00 0.00
Ns 256.00
newmtl blinn3SG
illum 4
Kd 0.50 0.50 0.50
Ka 0.00 0.00 0.00
Tf 1.00 1.00 1.00
Ni 1.00
Ks 0.50 0.50 0.50
Ns 256.00
newmtl blinn4SG
illum 4
Kd 0.50 0.50 0.50
Ka 0.00 0.00 0.00
Tf 1.00 1.00 1.00
Ni 1.00
Ks 0.50 0.50 0.50
Ns 256.00
newmtl blinn5SG
illum 4
Kd 0.50 0.50 0.50
Ka 0.00 0.00 0.00
Tf 1.00 1.00 1.00
Ni 1.00
Ks 0.50 0.50 0.50
Ns 256.00
newmtl blinn6SG
illum 4
Kd 0.50 0.50 0.50
Ka 0.00 0.00 0.00
Tf 1.00 1.00 1.00
Ni 1.00
Ks 0.50 0.50 0.50
Ns 256.00
newmtl blinn7SG
illum 4
Kd 0.50 0.50 0.50
Ka 0.00 0.00 0.00
Tf 1.00 1.00 1.00
Ni 1.00
Ks 0.50 0.50 0.50
Ns 256.00
newmtl blinn8SG
illum 4
Kd 0.50 0.50 0.50
Ka 0.00 0.00 0.00
Tf 1.00 1.00 1.00
Ni 1.00
Ks 0.50 0.50 0.50
Ns 256.00

File diff suppressed because it is too large Load Diff

Binary file not shown.

After

Width:  |  Height:  |  Size: 360 KiB

View File

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

File diff suppressed because it is too large Load Diff

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 MiB

View File

@@ -0,0 +1,104 @@
# 3ds Max Wavefront OBJ Exporter v0.97b - (c)2007 guruware
# File Created: 16.12.2011 14:18:52
newmtl white
Ns 53.0000
Ni 1.5000
d 1.0000
Tr 0.0000
Tf 1.0000 1.0000 1.0000
illum 2
Ka 0.6667 0.6667 0.6667
Kd 0.6667 0.6667 0.6667
Ks 0.1800 0.1800 0.1800
Ke 0.0000 0.0000 0.0000
newmtl boat_elements_black
Ns 55.0000
Ni 1.5000
d 1.0000
Tr 0.0000
Tf 1.0000 1.0000 1.0000
illum 2
Ka 0.0000 0.0000 0.0000
Kd 0.0000 0.0000 0.0000
Ks 0.3600 0.3600 0.3600
Ke 0.0000 0.0000 0.0000
newmtl boat_glass
Ns 60.0000
Ni 7.0000
d 0.4000
Tr 0.6000
Tf 0.4000 0.4000 0.4000
illum 2
Ka 0.1059 0.1569 0.1451
Kd 0.1059 0.1569 0.1451
Ks 0.6750 0.6750 0.6750
Ke 0.0000 0.0000 0.0000
newmtl boat_screw_hooks_bronze
Ns 80.0000
Ni 1.5000
d 1.0000
Tr 0.0000
Tf 1.0000 1.0000 1.0000
illum 2
Ka 0.2941 0.2157 0.0510
Kd 0.2941 0.2157 0.0510
Ks 0.7200 0.7200 0.7200
Ke 0.0000 0.0000 0.0000
newmtl boat_silver
Ns 80.0000
Ni 1.5000
d 1.0000
Tr 0.0000
Tf 1.0000 1.0000 1.0000
illum 2
Ka 0.3333 0.3333 0.3333
Kd 0.3333 0.3333 0.3333
Ks 0.7200 0.7200 0.7200
Ke 0.0000 0.0000 0.0000
newmtl boat_buffer
Ns 10.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.2700 0.2700 0.2700
Ke 0.0000 0.0000 0.0000
map_Ka boat_buffer_diffuse.jpg
map_Kd boat_buffer_diffuse.jpg
newmtl boat_roof_accessory
Ns 15.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.3600 0.3600 0.3600
Ke 0.0000 0.0000 0.0000
map_Ka boat_roof_accessory_diffuse.jpg
map_Kd boat_roof_accessory_diffuse.jpg
newmtl boat_body
Ns 55.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.3600 0.3600 0.3600
Ke 0.0000 0.0000 0.0000
map_Ka boat_body_diffuse.jpg
map_Kd boat_body_diffuse.jpg

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 166 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

View File

@@ -0,0 +1,16 @@
# 3ds Max Wavefront OBJ Exporter v0.97b - (c)2007 guruware
# File Created: 29.03.2012 14:25:39
newmtl default
Ns 35.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.5400 0.5400 0.5400
Ke 0.0000 0.0000 0.0000
map_Ka 14084_WWII_ship_German_Type_II_U-boat_diff.jpg
map_Kd 14084_WWII_ship_German_Type_II_U-boat_diff.jpg

Binary file not shown.

After

Width:  |  Height:  |  Size: 168 KiB

View File

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

View File

@@ -0,0 +1 @@
Aluminum | Roie Shpigler | https://artlist.io/royalty-free-music/song/aluminum/122360

View File

@@ -0,0 +1 @@
A Touch of Dream | Max H. | https://artlist.io/royalty-free-music/song/a-touch-of-dream/126111

View File

@@ -0,0 +1,4 @@
Epic Cinematic Trailer | ELITE by Alex-Productions | https://onsound.eu/
Music promoted by https://www.chosic.com/free-music/all/
Creative Commons CC BY 3.0
https://creativecommons.org/licenses/by/3.0/

View File

@@ -0,0 +1 @@
Victory march of Valor | Land_of_Books_YouTube | https://pixabay.com/users/land_of_books_youtube-7733644/s

View File

@@ -0,0 +1,2 @@
Created using Metal Plates 13 from ambientCG.com,
licensed under the Creative Commons CC0 1.0 Universal License.

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 MiB

View File

@@ -0,0 +1,2 @@
https://www.rawpixel.com/image/13141087/png-fire-bonfire-illuminated-destruction-generated-image-rawpixel
Licence: Free for personal use

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 MiB

View File

@@ -1,9 +1,4 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.exporter;
@@ -41,7 +36,7 @@ public static void main(String[] args) {
*/
@Override
public void simpleInitApp() {
export("Models/KingGeorgeV/King_George_V.obj", "KingGeorgeV.j3o"); //NON-NLS
export("Models/KingGeorgeV/King_George_V.obj", "Models/KingGeorgeV/KingGeorgeV.j3o"); //NON-NLS
stop();
}

View File

@@ -6,7 +6,7 @@ newmtl _King_George_V
Ni 1.5000
d 1.0000
Tr 0.0000
Tf 1.0000 1.0000 1.0000
Tf 1.0000 1.0000 1.0000
illum 2
Ka 1.0000 1.0000 1.0000
Kd 1.0000 1.0000 1.0000

View File

@@ -1,10 +1,3 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship;
import pp.util.config.Config;

View File

@@ -1,10 +1,3 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship;
import java.util.ResourceBundle;

View File

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

View File

@@ -1,16 +1,13 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.game.client;
import pp.battleship.message.client.ShootMessage;
import pp.battleship.message.server.EffectMessage;
import pp.battleship.message.server.StartAnimationMessage;
import pp.battleship.model.IntPoint;
import pp.battleship.model.ShipMap;
import pp.battleship.notification.Music;
import pp.battleship.notification.Sound;
import java.lang.System.Logger.Level;
@@ -29,14 +26,25 @@ class BattleState extends ClientState {
*/
public BattleState(ClientGameLogic logic, boolean myTurn) {
super(logic);
logic.playMusic(Music.GAME_THEME);
this.myTurn = myTurn;
}
/**
* Makes sure the client renders the correct view
*
* @return true
*/
@Override
public boolean showBattle() {
return true;
}
/**
* Triggers a shoot event if it's client's turn
*
* @param pos the position where the click occurred
*/
@Override
public void clickOpponentMap(IntPoint pos) {
if (!myTurn)
@@ -46,57 +54,13 @@ else if (logic.getOpponentMap().isValid(pos))
}
/**
* Reports the effect of a shot based on the server message.
* Triggers an animation if StartAnimationMessage is received
*
* @param msg the message containing the effect of the shot
* @param msg the received Startanimation message
*/
@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));
}
}
/**
* Determines which map (own or opponent's) should be affected by the shot based on the message.
*
* @param msg the effect message received from the server
* @return the map (either the opponent's or player's own map) that is affected by the shot
*/
private ShipMap affectedMap(EffectMessage msg) {
return msg.isOwnShot() ? logic.getOpponentMap() : logic.getOwnMap();
}
/**
* Checks if the opponent's ship was destroyed by the player's shot.
*
* @param msg the effect message received from the server
* @return true if the shot destroyed an opponent's ship, false otherwise
*/
private boolean destroyedOpponentShip(EffectMessage msg) {
return msg.getDestroyedShip() != null && msg.isOwnShot();
}
/**
* Plays a sound based on the outcome of the shot. Different sounds are played for a miss, hit,
* or destruction of a ship.
*
* @param msg the effect message containing the result of the shot
*/
private void playSound(EffectMessage msg) {
if (!msg.getShot().isHit())
logic.playSound(Sound.SPLASH);
else if (msg.getDestroyedShip() == null)
logic.playSound(Sound.EXPLOSION);
else
logic.playSound(Sound.DESTROYED_SHIP);
public void receivedStartAnimation(StartAnimationMessage msg) {
logic.setState(new AnimationState(logic, msg.isMyTurn(), msg.getPosition()));
logic.playSound(Sound.MISSILE_LAUNCH);
}
}

View File

@@ -1,9 +1,4 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.game.client;

View File

@@ -1,9 +1,4 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.game.client;
@@ -11,7 +6,9 @@
import pp.battleship.message.server.EffectMessage;
import pp.battleship.message.server.GameDetails;
import pp.battleship.message.server.ServerInterpreter;
import pp.battleship.message.server.StartAnimationMessage;
import pp.battleship.message.server.StartBattleMessage;
import pp.battleship.message.server.SwitchToBattleState;
import pp.battleship.model.IntPoint;
import pp.battleship.model.ShipMap;
import pp.battleship.model.dto.ShipMapDTO;
@@ -20,6 +17,8 @@
import pp.battleship.notification.GameEventBroker;
import pp.battleship.notification.GameEventListener;
import pp.battleship.notification.InfoTextEvent;
import pp.battleship.notification.Music;
import pp.battleship.notification.MusicEvent;
import pp.battleship.notification.Sound;
import pp.battleship.notification.SoundEvent;
@@ -226,6 +225,26 @@ public void received(EffectMessage msg) {
state.receivedEffect(msg);
}
/**
* Reports that client should play an animation
*
* @param msg
*/
@Override
public void received(StartAnimationMessage msg) {
state.receivedStartAnimation(msg);
}
/**
* Reports that client should switch to the battle state
*
* @param msg
*/
@Override
public void received(SwitchToBattleState msg) {
state.receivedSwitchToBattleState(msg);
}
/**
* Initializes the player's own map, opponent's map, and harbor based on the game details.
*
@@ -304,7 +323,7 @@ public void saveMap(File file) throws IOException {
*
* @param msg the message to be sent
*/
void send(ClientMessage msg) {
public void send(ClientMessage msg) {
if (clientSender == null)
LOGGER.log(Level.ERROR, "trying to send {0} with sender==null", msg); //NON-NLS
else
@@ -352,4 +371,13 @@ public void notifyListeners(GameEvent event) {
public void update(float delta) {
state.update(delta);
}
/**
* Triggers an event to play specified music
*
* @param music the music to be played
*/
public void playMusic(Music music) {
notifyListeners(new MusicEvent(music));
}
}

View File

@@ -1,9 +1,4 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.game.client;

View File

@@ -1,15 +1,12 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.game.client;
import pp.battleship.message.server.EffectMessage;
import pp.battleship.message.server.GameDetails;
import pp.battleship.message.server.StartAnimationMessage;
import pp.battleship.message.server.StartBattleMessage;
import pp.battleship.message.server.SwitchToBattleState;
import pp.battleship.model.IntPoint;
import java.io.File;
@@ -165,6 +162,24 @@ void receivedEffect(EffectMessage msg) {
ClientGameLogic.LOGGER.log(Level.ERROR, "receivedEffect not allowed in {0}", getName()); //NON-NLS
}
/**
* Reports that client should switch to battle state
*
* @param msg the received SwitchToBattleState message
*/
void receivedSwitchToBattleState(SwitchToBattleState msg) {
ClientGameLogic.LOGGER.log(Level.ERROR, "receivedSwitchToBattleState not allowed in {0}", getName());
}
/**
* Reports that the client should start an animation
*
* @param msg the received StartAnimation message
*/
void receivedStartAnimation(StartAnimationMessage msg) {
ClientGameLogic.LOGGER.log(Level.ERROR, "receivedStartAnimation not allowed in {0}", getName());
}
/**
* Loads a map from the specified file.
*

View File

@@ -1,9 +1,4 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.game.client;
@@ -16,8 +11,11 @@
import java.io.File;
import java.io.IOException;
import java.lang.System.Logger.Level;
import java.util.Arrays;
import java.util.List;
import static pp.battleship.Resources.lookup;
import static pp.battleship.game.client.ClientGameLogic.LOGGER;
import static pp.battleship.model.Battleship.Status.INVALID_PREVIEW;
import static pp.battleship.model.Battleship.Status.NORMAL;
import static pp.battleship.model.Battleship.Status.VALID_PREVIEW;
@@ -56,7 +54,7 @@ public boolean showEditor() {
*/
@Override
public void movePreview(IntPoint pos) {
ClientGameLogic.LOGGER.log(Level.DEBUG, "move preview to {0}", pos); //NON-NLS
LOGGER.log(Level.DEBUG, "move preview to {0}", pos); //NON-NLS
if (preview == null || !ownMap().isValid(pos)) return;
preview.moveTo(pos);
setPreviewStatus(preview);
@@ -71,7 +69,7 @@ public void movePreview(IntPoint pos) {
*/
@Override
public void clickOwnMap(IntPoint pos) {
ClientGameLogic.LOGGER.log(Level.DEBUG, "click at {0} in own map", pos); //NON-NLS
LOGGER.log(Level.DEBUG, "click at {0} in own map", pos); //NON-NLS
if (!ownMap().isValid(pos)) return;
if (preview == null)
modifyShip(pos);
@@ -125,7 +123,7 @@ private void placeShip(IntPoint cursor) {
*/
@Override
public void clickHarbor(IntPoint pos) {
ClientGameLogic.LOGGER.log(Level.DEBUG, "click at {0} in harbor", pos); //NON-NLS
LOGGER.log(Level.DEBUG, "click at {0} in harbor", pos); //NON-NLS
if (!harbor().isValid(pos)) return;
final Battleship shipAtCursor = harbor().findShipAt(pos);
if (preview != null) {
@@ -152,7 +150,7 @@ else if (shipAtCursor != null) {
*/
@Override
public void rotateShip() {
ClientGameLogic.LOGGER.log(Level.DEBUG, "pushed rotate"); //NON-NLS
LOGGER.log(Level.DEBUG, "pushed rotate"); //NON-NLS
if (preview == null) return;
preview.rotated();
ownMap().remove(preview);
@@ -238,6 +236,9 @@ public void loadMap(File file) throws IOException {
final ShipMapDTO dto = ShipMapDTO.loadFrom(file);
if (!dto.fits(logic.getDetails()))
throw new IOException(lookup("map.doesnt.fit"));
else if (!checkMapToLoad(dto)) {
throw new IOException(lookup("ships.dont.fit.the.map"));
}
ownMap().clear();
dto.getShips().forEach(ownMap()::add);
harbor().clear();
@@ -245,6 +246,39 @@ public void loadMap(File file) throws IOException {
selectedInHarbor = null;
}
/**
* Checks if the provided map meets the requirements
*
* @param dto the data transfer object to check
* @return boolean if the map meets the requirements
*/
private boolean checkMapToLoad(ShipMapDTO dto) {
int mapWidth = dto.getWidth();
int mapHeight = dto.getHeight();
// check if ship is out of bounds
for (int i = 0; i < dto.getShips().size(); i++) {
Battleship battleship = dto.getShips().get(i);
if (battleship.getMaxX() >= mapWidth || battleship.getMinX() < 0 || battleship.getMaxY() >= mapHeight || battleship.getMinY() < 0) {
LOGGER.log(Level.ERROR, "Ship is out of bounds ({0})", battleship.toString());
return false;
}
}
// check if ships overlap
List<Battleship> ships = dto.getShips();
for (Battleship ship : ships) {
for (Battleship compareShip : ships) {
if (!(ship == compareShip)) {
if (ship.collidesWith(compareShip)) {
return false;
}
}
}
}
return true;
}
/**
* Checks if the player's own map may be loaded from a file.
*

View File

@@ -1,12 +1,9 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.game.client;
import pp.battleship.notification.Music;
/**
* Represents the state of the client when the game is over.
*/
@@ -16,8 +13,14 @@ class GameOverState extends ClientState {
*
* @param logic the client game logic
*/
GameOverState(ClientGameLogic logic) {
GameOverState(ClientGameLogic logic, boolean loser) {
super(logic);
if (loser) {
logic.playMusic(Music.LOSE_THEME);
}
else {
logic.playMusic(Music.VICTORY_THEME);
}
}
/**

View File

@@ -1,9 +1,4 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.game.client;
@@ -58,6 +53,11 @@ private void fillHarbor(GameDetails details) {
}
}
/**
* Checks if map may be saved to file
*
* @return false
*/
@Override
public boolean maySaveMap() {
return false;

View File

@@ -1,9 +1,4 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.game.client;

View File

@@ -1,12 +1,8 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.game.client;
import pp.battleship.message.server.GameDetails;
import pp.battleship.message.server.StartBattleMessage;
import java.lang.System.Logger.Level;
@@ -38,4 +34,16 @@ public void receivedStartBattle(StartBattleMessage msg) {
logic.setInfoText(msg.getInfoTextKey());
logic.setState(new BattleState(logic, msg.isMyTurn()));
}
/**
* Reverts the client back to the editor state if an invalid map is provided
*
* @param details the game details including map size and ships
*/
@Override
public void receivedGameDetails(GameDetails details) {
ClientGameLogic.LOGGER.log(Level.WARNING, "Invalid Map"); //NON-NLS
logic.setInfoText("map.invalid");
logic.setState(new EditorState(logic));
}
}

View File

@@ -1,9 +1,4 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.game.server;

View File

@@ -1,20 +1,16 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.game.server;
import pp.battleship.BattleshipConfig;
import pp.battleship.message.client.ClientInterpreter;
import pp.battleship.message.client.EndAnimationMessage;
import pp.battleship.message.client.MapMessage;
import pp.battleship.message.client.ShootMessage;
import pp.battleship.message.server.EffectMessage;
import pp.battleship.message.server.GameDetails;
import pp.battleship.message.server.ServerMessage;
import pp.battleship.message.server.StartAnimationMessage;
import pp.battleship.message.server.StartBattleMessage;
import pp.battleship.message.server.SwitchToBattleState;
import pp.battleship.model.Battleship;
import pp.battleship.model.IntPoint;
@@ -39,6 +35,9 @@ public class ServerGameLogic implements ClientInterpreter {
private Player activePlayer;
private ServerState state = ServerState.WAIT;
private boolean p1AnimationFinished = false;
private boolean p2AnimationFinished = false;
/**
* Constructs a ServerGameLogic with the specified sender and configuration.
*
@@ -142,10 +141,78 @@ public Player addPlayer(int id) {
public void received(MapMessage msg, int from) {
if (state != ServerState.SET_UP)
LOGGER.log(Level.ERROR, "playerReady not allowed in {0}", state); //NON-NLS
else if (!checkMap(msg, from)) {
LOGGER.log(Level.ERROR, "The submitted map is not allowed");
send(players.get(from), new GameDetails(config));
}
else
playerReady(getPlayerById(from), msg.getShips());
}
/**
* Handles the reception of an EndAnimation message
* @param msg received EndAnimation message
*/
@Override
public void received(EndAnimationMessage msg, int from) {
if (state != ServerState.WAIT_ANIMATION)
LOGGER.log(Level.ERROR, "animation not allowed in {0}", state);
else if (getPlayerById(from) == players.get(0)) {
LOGGER.log(Level.DEBUG, "{0} set to true", getPlayerById(from));
p1AnimationFinished = true;
shoot(getPlayerById(from), msg.getPosition());
}
else if (getPlayerById(from) == players.get(1)) {
LOGGER.log(Level.DEBUG, "{0} set to true {1}", getPlayerById(from), getPlayerById(from).toString());
p2AnimationFinished = true;
shoot(getPlayerById(from), msg.getPosition());
}
if (p1AnimationFinished && p2AnimationFinished) {
setState(ServerState.BATTLE);
for (Player player : players)
send(player, new SwitchToBattleState(player == activePlayer));
p1AnimationFinished = false;
p2AnimationFinished = false;
}
}
/**
* Returns true if the map contains correct ship placement and is of the correct size
*
* @param msg the received MapMessage of the player
* @param from the ID of the Player
* @return a boolean based on if the transmitted map ist correct
*/
private boolean checkMap(MapMessage msg, int from) {
int mapWidth = getPlayerById(from).getMap().getWidth();
int mapHeight = getPlayerById(from).getMap().getHeight();
if (mapHeight != 10 || mapWidth != 10)
return false;
// check if ship is out of bounds
for (Battleship ship : msg.getShips()) {
if (ship.getMaxX() >= mapWidth || ship.getMinX() < 0 || ship.getMaxY() >= mapHeight || ship.getMinY() < 0) {
LOGGER.log(Level.ERROR, "Ship is out of bounds ({0})", ship.toString());
return false;
}
}
// check if ships overlap
List<Battleship> ships = msg.getShips();
for (Battleship ship : ships) {
for (Battleship compareShip : ships) {
if (!(ship == compareShip)) {
if (ship.collidesWith(compareShip)) {
return false;
}
}
}
}
return true;
}
/**
* Handles the reception of a ShootMessage.
*
@@ -157,7 +224,10 @@ public void received(ShootMessage msg, int from) {
if (state != ServerState.BATTLE)
LOGGER.log(Level.ERROR, "shoot not allowed in {0}", state); //NON-NLS
else
shoot(getPlayerById(from), msg.getPosition());
for (Player player : players) {
send(player, new StartAnimationMessage(msg.getPosition(), player == activePlayer));
setState(ServerState.WAIT_ANIMATION);
}
}
/**
@@ -181,40 +251,86 @@ void playerReady(Player player, List<Battleship> ships) {
}
/**
* Handles the shooting action by the player.
*
* @param p the player who shot
* @param pos the position of the shot
* Handles what Effect should be triggered based on the shot
* @param player the player receiving the message
* @param position the position the shot hit
*/
void shoot(Player p, IntPoint pos) {
if (p != activePlayer) return;
final Player otherPlayer = getOpponent(activePlayer);
final Battleship selectedShip = otherPlayer.getMap().findShipAt(pos);
void shoot(Player player, IntPoint position) {
final Battleship selectedShip;
selectedShip = getSelectedShip(player, position);
if (selectedShip == null) {
// shot missed
send(activePlayer, EffectMessage.miss(true, pos));
send(otherPlayer, EffectMessage.miss(false, pos));
activePlayer = otherPlayer;
shotMissed(player, position);
}
else {
// shot hit a ship
selectedShip.hit(pos);
if (otherPlayer.getMap().getRemainingShips().isEmpty()) {
// game is over
send(activePlayer, EffectMessage.won(pos, selectedShip));
send(otherPlayer, EffectMessage.lost(pos, selectedShip, activePlayer.getMap().getRemainingShips()));
shotHit(player, position, selectedShip);
}
}
/**
* Returns the ship at a given position
* @param player the player whose map will be checked for a ship
* @param position the position to be checked for a ship
* @return if there is a ship at the given position, returns the ship, else null
*/
Battleship getSelectedShip(Player player, IntPoint position) {
if (player != activePlayer) {
return player.getMap().findShipAt(position);
}
else {
return getOpponent(player).getMap().findShipAt(position);
}
}
/**
* Sends a message to the client that the shot missed
* @param player the player receiving the message
* @param position the position at which the shot hit in the water
*/
void shotMissed(Player player, IntPoint position) {
if (player != activePlayer) {
send(player, EffectMessage.miss(false, position));
}
else
send(activePlayer, EffectMessage.miss(true, position));
if (p1AnimationFinished && p2AnimationFinished)
if (player == activePlayer)
activePlayer = getOpponent(player);
else
activePlayer = player;
}
/**
* Sends a message to the client that the shot missed
* @param player the player receiving the message
* @param position the position at which the shot hit in the ship
* @param ship the ship that has been hit
*/
void shotHit(Player player, IntPoint position, Battleship ship) {
ship.hit(position);
if (getOpponent(activePlayer).getMap().getRemainingShips().isEmpty()) {
if (player != activePlayer)
send(player, EffectMessage.lost(position, ship, activePlayer.getMap().getRemainingShips()));
else
send(activePlayer, EffectMessage.won(position, ship));
if (p1AnimationFinished && p2AnimationFinished) {
setState(ServerState.GAME_OVER);
}
else if (selectedShip.isDestroyed()) {
// ship has been destroyed, but game is not yet over
send(activePlayer, EffectMessage.shipDestroyed(true, pos, selectedShip));
send(otherPlayer, EffectMessage.shipDestroyed(false, pos, selectedShip));
}
else if (ship.isDestroyed()) {
if (player != activePlayer)
send(player, EffectMessage.shipDestroyed(false, position, ship));
else
send(activePlayer, EffectMessage.shipDestroyed(true, position, ship));
}
else {
if (player != activePlayer) {
send(player, EffectMessage.hit(false, position));
}
else {
// ship has been hit, but it hasn't been destroyed
send(activePlayer, EffectMessage.hit(true, pos));
send(otherPlayer, EffectMessage.hit(false, pos));
send(activePlayer, EffectMessage.hit(true, position));
}
}
}
}
}

View File

@@ -1,10 +1,3 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.game.server;
import pp.battleship.message.server.ServerMessage;

View File

@@ -1,9 +1,4 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.game.server;
@@ -26,6 +21,11 @@ enum ServerState {
*/
BATTLE,
/**
* Waits for the Animation to finish
*/
WAIT_ANIMATION,
/**
* The game has ended because all the ships of one player have been destroyed.
*/

View File

@@ -1,10 +1,3 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.game.singlemode;
import pp.battleship.BattleshipConfig;

View File

@@ -1,14 +1,10 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.game.singlemode;
import pp.battleship.message.client.ClientInterpreter;
import pp.battleship.message.client.ClientMessage;
import pp.battleship.message.client.EndAnimationMessage;
import pp.battleship.message.client.MapMessage;
import pp.battleship.message.client.ShootMessage;
import pp.battleship.model.Battleship;
@@ -63,6 +59,16 @@ public void received(MapMessage msg, int from) {
copiedMessage = new MapMessage(msg.getShips().stream().map(Copycat::copy).toList());
}
/**
* Creates a copy of the provided EndAnimation message
* @param msg thr received EndAnimation message
* @param from the identifier of the sender
*/
@Override
public void received(EndAnimationMessage msg, int from) {
copiedMessage = new EndAnimationMessage(msg.getPosition());
}
/**
* Creates a copy of the provided {@link Battleship}.
*

View File

@@ -1,19 +1,8 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.game.singlemode;
import pp.battleship.game.client.BattleshipClient;
import pp.battleship.game.client.ClientGameLogic;
import pp.battleship.message.server.EffectMessage;
import pp.battleship.message.server.GameDetails;
import pp.battleship.message.server.ServerInterpreter;
import pp.battleship.message.server.ServerMessage;
import pp.battleship.message.server.StartBattleMessage;
import pp.battleship.message.server.*;
import java.io.IOException;
@@ -24,11 +13,14 @@
class InterpreterProxy implements ServerInterpreter {
private final BattleshipClient playerClient;
static final System.Logger LOGGER = System.getLogger(InterpreterProxy.class.getName());
/**
* Constructs an InterpreterProxy with the specified BattleshipClient.
*
* @param playerClient the client to which the server messages are forwarded
*/
InterpreterProxy(BattleshipClient playerClient) {
this.playerClient = playerClient;
}
@@ -82,6 +74,27 @@ public void received(EffectMessage msg) {
forward(msg);
}
/**
* Forwards the received AnimationStartMessage to the client's game logic.
*
* @param msg the AnimationStartMessage received from the server
*/
@Override
public void received(StartAnimationMessage msg) {
forward(msg);
}
/**
* Forwards the received SwitchBattleState to the client's game logic.
*
* @param msg the SwitchBattleState received from the server
*/
@Override
public void received(SwitchToBattleState msg) {
LOGGER.log(System.Logger.Level.INFO, "Received SwitchBattleState");
forward(msg);
}
/**
* Forwards the specified ServerMessage to the client's game logic by enqueuing the message acceptance.
*

View File

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

View File

@@ -1,9 +1,4 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.game.singlemode;

View File

@@ -1,10 +1,3 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.message.client;
/**
@@ -26,4 +19,11 @@ public interface ClientInterpreter {
* @param from the connection ID from which the message was received
*/
void received(MapMessage msg, int from);
/**
* Processes a received EndAnimation message
* @param msg the received EndAnimation message
* @param from the connection ID from which the message was received
*/
void received(EndAnimationMessage msg, int from);
}

View File

@@ -1,10 +1,3 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.message.client;
import com.jme3.network.AbstractMessage;

View File

@@ -0,0 +1,45 @@
package pp.battleship.message.client;
import com.jme3.network.serializing.Serializable;
import pp.battleship.model.IntPoint;
/**
* A message sent by the client telling the server the animation is finished
*/
@Serializable
public class EndAnimationMessage extends ClientMessage {
private IntPoint position;
/**
* Default constructor for serialization purposes.
*/
private EndAnimationMessage() {/*do nothing */}
/**
* Constructs an EndAnimation message
* @param position the position to be effected
*/
public EndAnimationMessage(final IntPoint position) {
this.position = position;
}
/**
* Accepts a visitor for processing this message.
*
* @param interpreter the visitor to be used for processing
* @param from the connection ID of the sender
*/
@Override
public void accept(ClientInterpreter interpreter, int from) {
interpreter.received(this, from);
}
/**
* Getter for the position
* @return IntPoint position
*/
public IntPoint getPosition() {
return position;
}
}

View File

@@ -1,10 +1,3 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.message.client;
import com.jme3.network.serializing.Serializable;

View File

@@ -1,10 +1,3 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.message.client;
import com.jme3.network.serializing.Serializable;

View File

@@ -1,10 +1,3 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.message.server;
import com.jme3.network.serializing.Serializable;

View File

@@ -1,10 +1,3 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.message.server;
import com.jme3.network.serializing.Serializable;

View File

@@ -1,12 +1,7 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.message.server;
import pp.battleship.message.client.EndAnimationMessage;
/**
* An interface for processing server messages.
* Implementations of this interface can be used to handle different types of server messages.
@@ -33,4 +28,16 @@ public interface ServerInterpreter {
* @param msg the EffectMessage received
*/
void received(EffectMessage msg);
/**
* Handles a StartAnimation message received from the server
* @param msg the received StartAnimation message
*/
void received(StartAnimationMessage msg);
/**
* Handles a SwitchToBattleState message received from the server
* @param msg the received SwitchToBattleState message
*/
void received(SwitchToBattleState msg);
}

View File

@@ -1,10 +1,3 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.message.server;
import com.jme3.network.AbstractMessage;

View File

@@ -0,0 +1,62 @@
package pp.battleship.message.server;
import com.jme3.network.serializing.Serializable;
import pp.battleship.model.IntPoint;
/**
* A message sent by the server to inform clients about the start of an animation
*/
@Serializable
public class StartAnimationMessage extends ServerMessage {
private IntPoint position;
private boolean myTurn;
/**
* Default constructor for serialization purposes.
*/
private StartAnimationMessage() {/*do nothing */}
/**
* Constructs a StartAnimation message
* @param position the position a Shell will affect
* @param myTurn boolean if it's client's turn
*/
public StartAnimationMessage(IntPoint position, boolean myTurn) {
this.position = position;
this.myTurn = myTurn;
}
/**
* Accepts a visitor for processing this message.
*
* @param interpreter the visitor to be used for processing
*/
@Override
public void accept(ServerInterpreter interpreter) {
interpreter.received(this);
}
/**
* Gets the bundle key of the informational text to be shown at the client.
* This key is used to retrieve the appropriate localized text for display.
*
* @return the bundle key of the informational text
*/
@Override
public String getInfoTextKey() {
return "started animation at " + position;
}
/**
* Getter for the position
* @return IntPoint position
*/
public IntPoint getPosition() {return position;}
/**
* Getter for myTurn
* @return boolean myTurn
*/
public boolean isMyTurn() {return myTurn;}
}

View File

@@ -1,10 +1,3 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.message.server;
import com.jme3.network.serializing.Serializable;

View File

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

View File

@@ -1,10 +1,3 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.model;
import com.jme3.network.serializing.Serializable;

View File

@@ -1,10 +1,3 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.model;
import com.jme3.network.serializing.Serializable;

View File

@@ -1,10 +1,3 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.model;
/**

View File

@@ -1,10 +1,3 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.model;
/**

View File

@@ -1,10 +1,3 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.model;
import java.io.Serializable;

View File

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

View File

@@ -1,15 +1,9 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.model;
import pp.battleship.notification.GameEvent;
import pp.battleship.notification.GameEventBroker;
import pp.battleship.notification.ItemAddedEvent;
import pp.battleship.notification.ItemRemovedEvent;
import java.util.ArrayList;
import java.util.Collections;
@@ -90,6 +84,15 @@ public void add(Shot shot) {
addItem(shot);
}
/**
* Registers a Shell on the map
*
* @param shell the Shell to be registered
*/
public void add(Shell shell) {
addItem(shell);
}
/**
* Removes an item from the map and triggers an item removal event.
*
@@ -97,7 +100,7 @@ public void add(Shot shot) {
*/
public void remove(Item item) {
items.remove(item);
notifyListeners(new ItemAddedEvent(item, this));
notifyListeners(new ItemRemovedEvent(item, this));
}
/**

View File

@@ -1,10 +1,3 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.model;
import com.jme3.network.serializing.Serializable;

View File

@@ -1,10 +1,3 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.model;
/**
@@ -28,4 +21,11 @@ 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 visiting the Shell element
*/
T visit(Shell shell);
}

View File

@@ -1,10 +1,3 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.model;
/**
@@ -25,4 +18,10 @@ public interface VoidVisitor {
* @param ship the Battleship element to visit
*/
void visit(Battleship ship);
/**
* Visits a Shell element
* @param shell the Shell to be visited
*/
void visit(Shell shell);
}

View File

@@ -1,10 +1,3 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.model.dto;
import pp.battleship.model.Battleship;

Some files were not shown because too many files have changed in this diff Show More