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
185 changed files with 227733 additions and 130928 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -9,13 +9,10 @@ implementation project(":jme-common")
implementation project(":battleship:model") implementation project(":battleship:model")
implementation libs.jme3.desktop implementation libs.jme3.desktop
implementation libs.jme3.effects
runtimeOnly libs.jme3.awt.dialogs runtimeOnly libs.jme3.awt.dialogs
runtimeOnly libs.jme3.plugins runtimeOnly libs.jme3.plugins
runtimeOnly libs.jme3.jogg runtimeOnly libs.jme3.jogg
runtimeOnly libs.jme3.testdata runtimeOnly libs.jme3.testdata
} }
application { application {

View File

@@ -9,7 +9,7 @@
# #
# Specifies the map used by the opponent in single mode. # Specifies the map used by the opponent in single mode.
# Single mode is activated if this property is set. # 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. # Specifies the map used by the player in single mode.
# The player must define their own map if this property is not set. # The player must define their own map if this property is not set.
@@ -29,7 +29,7 @@ robot.targets=2, 0,\
2, 3 2, 3
# #
# Delay in milliseconds between each shot fired by the RobotClient. # Delay in milliseconds between each shot fired by the RobotClient.
robot.delay=2000 robot.delay=500
# #
# The dimensions of the game map used in single mode. # The dimensions of the game map used in single mode.
# 'map.width' defines the number of columns, and 'map.height' defines the number of rows. # 'map.width' defines the number of columns, and 'map.height' defines the number of rows.

View File

@@ -1,267 +1,238 @@
package pp.battleship.client; package pp.battleship.client;
import com.jme3.app.Application; import com.jme3.app.Application;
import com.jme3.app.state.AbstractAppState;
import com.jme3.app.state.AppStateManager;
import com.jme3.asset.AssetLoadException;
import com.jme3.asset.AssetNotFoundException;
import com.jme3.audio.AudioData.DataType; import com.jme3.audio.AudioData.DataType;
import com.jme3.audio.AudioNode; import com.jme3.audio.AudioNode;
import pp.battleship.notification.GameEventListener; import com.jme3.audio.AudioSource.Status;
import pp.battleship.notification.Music;
import pp.battleship.notification.MusicEvent; import pp.battleship.notification.MusicEvent;
import pp.battleship.notification.GameEventListener;
import java.lang.System.Logger; import java.lang.System.Logger;
import java.lang.System.Logger.Level; import java.lang.System.Logger.Level;
import java.util.prefs.Preferences; import java.util.prefs.Preferences;
import static pp.util.PreferencesUtils.getPreferences;
/** /**
* The BackgroundMusic class represents the background music in the Battleship game application. * Class to play Background music in game
* It extends the AbstractAppState class and provides functionalities for playing the menu music,
* game music, victory music, and defeat music.
*/ */
public class BackgroundMusic extends AbstractAppState implements GameEventListener { public class BackgroundMusic implements GameEventListener {
/** private static final String VOLUME_PREF = "volume";
* Logger for the BackgroundMusic class. private static final String MUSIC_ENABLED_PREF = "musicEnabled";
*/ private final Preferences pref = Preferences.userNodeForPackage(BackgroundMusic.class);
private static final Logger LOGGER = System.getLogger(BackgroundMusic.class.getName()); static final Logger LOGGER = System.getLogger(BackgroundMusic.class.getName());
/** private static final String MENU_MUSIC = "Sound/Music/menu/cinematictrailerelite.ogg";
* Preferences for storing music settings. 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 Preferences PREFERENCES = getPreferences(BackgroundMusic.class); private static final String LOSE_MUSIC = "Sound/Music/lose/TouchofDream.ogg";
private final AudioNode menuMusic;
/** private final AudioNode gameMusic;
* Preference key for enabling/disabling music. private final AudioNode victoryMusic;
*/ private final AudioNode loseMusic;
private static final String ENABLED_PREF = "enabled"; //NON-NLS private String lastPlayedMusic;
private boolean musicEnabled;
/**
* Preference key for storing the volume level.
*/
private static final String VOLUME_PREF = "volume"; //NON-NLS
/**
* Path to the menu music file.
*/
private static final String MENU_MUSIC_PATH = "Sound/Music/menu_music.ogg";
/**
* Path to the game music file.
*/
private static final String GAME_MUSIC_PATH = "Sound/Music/pirates.ogg";
/**
* Path to the victory music file.
*/
private static final String VICTORY_MUSIC_PATH = "Sound/Music/win_the_game.ogg";
/**
* Path to the defeat music file.
*/
private static final String DEFEAT_MUSIC_PATH = "Sound/Music/defeat.ogg";
/**
* AudioNode for the menu music.
*/
private AudioNode menuMusic;
/**
* AudioNode for the game music.
*/
private AudioNode gameMusic;
/**
* AudioNode for the victory music.
*/
private AudioNode victoryMusic;
/**
* AudioNode for the defeat music.
*/
private AudioNode defeatMusic;
/**
* The currently playing AudioNode.
*/
private AudioNode currentMusic;
/**
* The volume level for the background music.
*/
private float volume; private float volume;
private Application app;
/** /**
* Checks if music is enabled in the preferences. * Constructor for BackgroundMusic class
* *
* @return {@code true} if music is enabled, {@code false} otherwise. * @param app The main Application
*/ */
public static boolean enabledInPreferences() { public BackgroundMusic(Application app) {
return PREFERENCES.getBoolean(ENABLED_PREF, true); 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);
}
} }
/** /**
* Sets the enabled state of this AppState. * Creates an audio node for the music
* Overrides {@link com.jme3.app.state.AbstractAppState#setEnabled(boolean)}
* *
* @param enabled {@code true} to enable the AppState, {@code false} to disable it. * @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 @Override
public void setEnabled(boolean enabled) { public void receivedEvent(MusicEvent music) {
if (isEnabled() == enabled) return; LOGGER.log(Level.DEBUG, "Received Music change Event {0}", music.toString());
super.setEnabled(enabled); switch (music.music()) {
LOGGER.log(Level.INFO, "Music enabled: {0}", enabled); //NON-NLS case MENU_THEME:
PREFERENCES.putBoolean(ENABLED_PREF, enabled); changeMusic(Music.MENU_THEME);
playCurrentMusic(); 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;
}
} }
/** /**
* Initializes the music for the game. * Set the volume for the music
* Overrides {@link AbstractAppState#initialize(AppStateManager, Application)}
* *
* @param stateManager The state manager * @param volume float to transfer the new volume
* @param app The application
*/
@Override
public void initialize(AppStateManager stateManager, Application app) {
LOGGER.log(Level.INFO, "Initializing background music"); //NON-NLS
super.initialize(stateManager, app);
menuMusic = loadMusic(app, MENU_MUSIC_PATH);
gameMusic = loadMusic(app, GAME_MUSIC_PATH);
victoryMusic = loadMusic(app, VICTORY_MUSIC_PATH);
defeatMusic = loadMusic(app, DEFEAT_MUSIC_PATH);
currentMusic = menuMusic;
playCurrentMusic();
}
/**
* Loads a music file and initializes an AudioNode with the specified settings.
*
* @param app The application instance.
* @param name The name of the music file to load.
* @return The initialized AudioNode, or {@code null} if the file could not be loaded.
*/
private AudioNode loadMusic(Application app, String name) {
try {
this.volume = PREFERENCES.getFloat(VOLUME_PREF, 0.5f);
final AudioNode music = new AudioNode(app.getAssetManager(), name, DataType.Stream);
music.setLooping(true);
music.setVolume(volume);
music.setPositional(false);
music.setDirectional(false);
return music;
} catch (AssetLoadException | AssetNotFoundException ex) {
LOGGER.log(Level.ERROR, ex.getMessage(), ex);
}
return null;
}
/**
* Plays the current music if the music is enabled.
* Stops the current music if the music is disabled.
*/
private void playCurrentMusic() {
if (isEnabled()) {
if (currentMusic != null) {
LOGGER.log(Level.INFO, "Playing current music"); //NON-NLS
currentMusic.play();
}
} else {
if (currentMusic != null) {
currentMusic.stop();
}
}
}
/**
* Plays the game music.
*/
private void gameMusic() {
if (isEnabled() && gameMusic != null) {
stopAll();
LOGGER.log(Level.INFO, "Playing game music"); //NON-NLS
PREFERENCES.putFloat(VOLUME_PREF, volume);
gameMusic.play();
}
}
/**
* Plays the victory music.
*/
private void victoryMusic() {
if (isEnabled() && victoryMusic != null) {
stopAll();
LOGGER.log(Level.INFO, "Playing victory music"); //NON-NLS
PREFERENCES.putFloat(VOLUME_PREF, volume);
victoryMusic.play();
}
}
/**
* Plays the defeat music.
*/
private void defeatMusic() {
if (isEnabled() && defeatMusic != null) {
stopAll();
LOGGER.log(Level.INFO, "Playing defeat music"); //NON-NLS
PREFERENCES.putFloat(VOLUME_PREF, volume);
defeatMusic.play();
}
}
/**
* Stops all music.
*/
private void stopAll() {
if (menuMusic != null) menuMusic.stop();
if (gameMusic != null) gameMusic.stop();
if (victoryMusic != null) victoryMusic.stop();
if (defeatMusic != null) defeatMusic.stop();
}
/**
* Handles the received music event and plays the corresponding music.
*
* @param event The music event to handle.
*/
@Override
public void receivedEvent(MusicEvent event) {
switch (event.music()) {
case GAME_MUSIC -> {
gameMusic();
currentMusic = gameMusic;
}
case VICTORY_MUSIC -> {
victoryMusic();
currentMusic = victoryMusic;
}
case DEFEAT_MUSIC -> {
defeatMusic();
currentMusic = defeatMusic;
}
}
}
/**
* Sets the volume for the background music and updates the preferences.
*
* @param volume The volume level to set.
*/ */
public void setVolume(float volume) { public void setVolume(float volume) {
LOGGER.log(Level.INFO, "Setting volume to {0}", volume); //NON-NLS
this.volume = volume; this.volume = volume;
currentMusic.setVolume(volume); menuMusic.setVolume(volume);
PREFERENCES.putFloat(VOLUME_PREF, volume); gameMusic.setVolume(volume);
victoryMusic.setVolume(volume);
loseMusic.setVolume(volume);
pref.putFloat(VOLUME_PREF, volume);
} }
/** /**
* Returns the volume level for the background music. * Returns the volume
* *
* @return The volume level as a float. * @return the current volume as a float
*/ */
public float getVolume() { public float getVolume() {
return volume; 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; package pp.battleship.client;
import com.jme3.app.DebugKeysAppState; import com.jme3.app.DebugKeysAppState;
@@ -122,13 +115,19 @@ public class BattleshipApp extends SimpleApplication implements BattleshipClient
*/ */
private final ActionListener escapeListener = (name, isPressed, tpf) -> escape(isPressed); private final ActionListener escapeListener = (name, isPressed, tpf) -> escape(isPressed);
/**
* Object handling the background music
*/
private BackgroundMusic backgroundMusic;
static { static {
// Configure logging // Configure logging
LogManager manager = LogManager.getLogManager(); LogManager manager = LogManager.getLogManager();
try { try {
manager.readConfiguration(new FileInputStream("logging.properties")); manager.readConfiguration(new FileInputStream("logging.properties"));
LOGGER.log(Level.INFO, "Successfully read logging properties"); //NON-NLS LOGGER.log(Level.INFO, "Successfully read logging properties"); //NON-NLS
} catch (IOException e) { }
catch (IOException e) {
LOGGER.log(Level.INFO, e.getMessage()); LOGGER.log(Level.INFO, e.getMessage());
} }
} }
@@ -224,6 +223,8 @@ public void simpleInitApp() {
setupStates(); setupStates();
setupGui(); setupGui();
serverConnection.connect(); serverConnection.connect();
backgroundMusic = new BackgroundMusic(this);
logic.addListener(backgroundMusic);
} }
/** /**
@@ -266,7 +267,6 @@ private void setupStates() {
stateManager.detach(stateManager.getState(DebugKeysAppState.class)); stateManager.detach(stateManager.getState(DebugKeysAppState.class));
attachGameSound(); attachGameSound();
attachBackgroundSound();
stateManager.attachAll(new EditorAppState(), new BattleAppState(), new SeaAppState()); stateManager.attachAll(new EditorAppState(), new BattleAppState(), new SeaAppState());
} }
@@ -280,19 +280,6 @@ private void attachGameSound() {
stateManager.attach(gameSound); stateManager.attach(gameSound);
} }
/**
* Attaches the background music state and sets its initial enabled state.
* The background music state is responsible for managing the background music
* playback in the game. It listens to the game logic for any changes in the
* background music settings.
*/
private void attachBackgroundSound() {
final BackgroundMusic backgroundMusic = new BackgroundMusic();
logic.addListener(backgroundMusic);
backgroundMusic.setEnabled(BackgroundMusic.enabledInPreferences());
stateManager.attach(backgroundMusic);
}
/** /**
* Updates the application state every frame. * Updates the application state every frame.
* This method is called once per frame during the game loop. * This method is called once per frame during the game loop.
@@ -328,6 +315,10 @@ public Draw getDraw() {
return draw; return draw;
} }
public BackgroundMusic getBackgroundMusic() {
return backgroundMusic;
}
/** /**
* Handles a request to close the application. * Handles a request to close the application.
* If the request is initiated by pressing ESC, this parameter is true. * If the request is initiated by pressing ESC, this parameter is true.
@@ -418,12 +409,12 @@ public void stop(boolean waitFor) {
*/ */
void confirmDialog(String question, Runnable yesAction) { void confirmDialog(String question, Runnable yesAction) {
DialogBuilder.simple(dialogManager) DialogBuilder.simple(dialogManager)
.setTitle(lookup("dialog.question")) .setTitle(lookup("dialog.question"))
.setText(question) .setText(question)
.setOkButton(lookup("button.yes"), yesAction) .setOkButton(lookup("button.yes"), yesAction)
.setNoButton(lookup("button.no")) .setNoButton(lookup("button.no"))
.build() .build()
.open(); .open();
} }
/** /**
@@ -433,10 +424,10 @@ void confirmDialog(String question, Runnable yesAction) {
*/ */
void errorDialog(String errorMessage) { void errorDialog(String errorMessage) {
DialogBuilder.simple(dialogManager) DialogBuilder.simple(dialogManager)
.setTitle(lookup("dialog.error")) .setTitle(lookup("dialog.error"))
.setText(errorMessage) .setText(errorMessage)
.setOkButton(lookup("button.ok")) .setOkButton(lookup("button.ok"))
.build() .build()
.open(); .open();
} }
} }

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; package pp.battleship.client;
import com.jme3.math.ColorRGBA; 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; package pp.battleship.client;
import com.jme3.app.Application; 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; package pp.battleship.client;
import com.jme3.app.Application; import com.jme3.app.Application;
@@ -15,6 +8,7 @@
import com.jme3.audio.AudioData; import com.jme3.audio.AudioData;
import com.jme3.audio.AudioNode; import com.jme3.audio.AudioNode;
import pp.battleship.notification.GameEventListener; import pp.battleship.notification.GameEventListener;
import pp.battleship.notification.Sound;
import pp.battleship.notification.SoundEvent; import pp.battleship.notification.SoundEvent;
import java.lang.System.Logger; import java.lang.System.Logger;
@@ -27,14 +21,14 @@
* An application state that plays sounds. * An application state that plays sounds.
*/ */
public class GameSound extends AbstractAppState implements GameEventListener { 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 Preferences PREFERENCES = getPreferences(GameSound.class);
private static final String ENABLED_PREF = "enabled"; //NON-NLS private static final String ENABLED_PREF = "enabled"; //NON-NLS
private AudioNode splashSound; private AudioNode splashSound;
private AudioNode shipDestroyedSound; private AudioNode shipDestroyedSound;
private AudioNode explosionSound; private AudioNode explosionSound;
private AudioNode shellFiredSound; private AudioNode missileLaunch;
/** /**
* Checks if sound is enabled in the preferences. * Checks if sound is enabled in the preferences.
@@ -79,7 +73,7 @@ public void initialize(AppStateManager stateManager, Application app) {
shipDestroyedSound = loadSound(app, "Sound/Effects/sunken.wav"); //NON-NLS shipDestroyedSound = loadSound(app, "Sound/Effects/sunken.wav"); //NON-NLS
splashSound = loadSound(app, "Sound/Effects/splash.wav"); //NON-NLS splashSound = loadSound(app, "Sound/Effects/splash.wav"); //NON-NLS
explosionSound = loadSound(app, "Sound/Effects/explosion.wav"); //NON-NLS explosionSound = loadSound(app, "Sound/Effects/explosion.wav"); //NON-NLS
shellFiredSound = loadSound(app, "Sound/Effects/missle.wav"); //NON-NLS missileLaunch = loadSound(app, "Sound/Effects/missilefiring.wav"); //NON-NLS
} }
/** /**
@@ -95,12 +89,21 @@ private AudioNode loadSound(Application app, String name) {
sound.setLooping(false); sound.setLooping(false);
sound.setPositional(false); sound.setPositional(false);
return sound; return sound;
} catch (AssetLoadException | AssetNotFoundException ex) { }
catch (AssetLoadException | AssetNotFoundException ex) {
LOGGER.log(Level.ERROR, ex.getMessage(), ex); LOGGER.log(Level.ERROR, ex.getMessage(), ex);
} }
return null; return null;
} }
/**
* Plays the splash sound effect.
*/
public void missileLaunch() {
if (isEnabled() && missileLaunch != null)
missileLaunch.playInstance();
}
/** /**
* Plays the splash sound effect. * Plays the splash sound effect.
*/ */
@@ -126,20 +129,17 @@ public void shipDestroyed() {
} }
/** /**
* Plays sound effect when a shell has been fired. * Plays sound according to the received SoundEvent
*
* @param event the received SoundEvent
*/ */
public void shellFired() {
if (isEnabled() && shellFiredSound != null)
shellFiredSound.playInstance();
}
@Override @Override
public void receivedEvent(SoundEvent event) { public void receivedEvent(SoundEvent event) {
switch (event.sound()) { switch (event.sound()) {
case EXPLOSION -> explosion(); case EXPLOSION -> explosion();
case SPLASH -> splash(); case SPLASH -> splash();
case DESTROYED_SHIP -> shipDestroyed(); case DESTROYED_SHIP -> shipDestroyed();
case SHELL_FIRED -> shellFired(); case MISSILE_LAUNCH -> missileLaunch();
} }
} }
} }

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; package pp.battleship.client;
import com.simsilica.lemur.Button; import com.simsilica.lemur.Button;
@@ -22,8 +15,6 @@
import java.io.IOException; import java.io.IOException;
import java.util.prefs.Preferences; import java.util.prefs.Preferences;
import java.lang.System.Logger;
import static pp.battleship.Resources.lookup; import static pp.battleship.Resources.lookup;
import static pp.util.PreferencesUtils.getPreferences; import static pp.util.PreferencesUtils.getPreferences;
@@ -33,7 +24,6 @@
* returning to the game, and quitting the application. * returning to the game, and quitting the application.
*/ */
class Menu extends Dialog { class Menu extends Dialog {
private static final Logger LOGGER = System.getLogger(Menu.class.getName());
private static final Preferences PREFERENCES = getPreferences(Menu.class); private static final Preferences PREFERENCES = getPreferences(Menu.class);
private static final String LAST_PATH = "last.file.path"; private static final String LAST_PATH = "last.file.path";
private final BattleshipApp app; private final BattleshipApp app;
@@ -50,17 +40,19 @@ public Menu(BattleshipApp app) {
super(app.getDialogManager()); super(app.getDialogManager());
this.app = app; this.app = app;
addChild(new Label(lookup("battleship.name"), new ElementId("header"))); //NON-NLS addChild(new Label(lookup("battleship.name"), new ElementId("header"))); //NON-NLS
addChild(new Checkbox(lookup("menu.sound-enabled"), addChild(new Checkbox(lookup("menu.sound-enabled"),
new StateCheckboxModel(app, GameSound.class))); new StateCheckboxModel(app, GameSound.class)));
Checkbox musicToggle = new Checkbox(lookup("menu.music.toggle"));
addChild(new Checkbox(lookup("menu.music-toggle"), musicToggle.setChecked(app.getBackgroundMusic().isMusicEnabled());
new StateCheckboxModel(app, BackgroundMusic.class))); musicToggle.addClickCommands(s -> toggleMusic());
addChild(musicToggle);
addChild(new Label(lookup("menu.music.volume"), new ElementId("slider_label")));
Slider volumeSlider = new Slider(); Slider volumeSlider = new Slider();
volumeSlider.setModel(new DefaultRangedValueModel(0.0, 2.0, app.getStateManager().getState(BackgroundMusic.class).getVolume())); volumeSlider.setModel(new DefaultRangedValueModel(0.00, 1.00, app.getBackgroundMusic().getVolume()));
volumeSlider.setDelta(0.1f); volumeSlider.setDelta(0.05);
addChild(volumeSlider); addChild(volumeSlider);
volumeRef = volumeSlider.getModel().createReference(); volumeRef = volumeSlider.getModel().createReference();
addChild(loadButton) addChild(loadButton)
@@ -71,9 +63,39 @@ public Menu(BattleshipApp app) {
.addClickCommands(s -> ifTopDialog(this::close)); .addClickCommands(s -> ifTopDialog(this::close));
addChild(new Button(lookup("menu.quit"))) addChild(new Button(lookup("menu.quit")))
.addClickCommands(s -> ifTopDialog(app::closeApp)); .addClickCommands(s -> ifTopDialog(app::closeApp));
update(); 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. * Updates the state of the load and save buttons based on the game logic.
*/ */
@@ -83,28 +105,6 @@ public void update() {
saveButton.setEnabled(app.getGameLogic().maySaveMap()); saveButton.setEnabled(app.getGameLogic().maySaveMap());
} }
/**
* Updates the menu state based on the time per frame (tpf).
* If the volume reference has been updated, adjusts the volume accordingly.
*
* @param tpf the time per frame
*/
@Override
public void update(float tpf) {
if (volumeRef.update()) {
adjustVolume(volumeRef.get());
}
}
/**
* Adjusts the volume of the background music.
*
* @param volume the new volume level to set, as a double
*/
private void adjustVolume(double volume) {
app.getStateManager().getState(BackgroundMusic.class).setVolume((float) volume);
}
/** /**
* As an escape action, this method closes the menu if it is the top dialog. * As an escape action, this method closes the menu if it is the top dialog.
*/ */
@@ -139,7 +139,8 @@ private void handle(FileAction fileAction, TextInputDialog dialog) {
PREFERENCES.put(LAST_PATH, path); PREFERENCES.put(LAST_PATH, path);
fileAction.run(new File(path)); fileAction.run(new File(path));
dialog.close(); dialog.close();
} catch (IOException e) { }
catch (IOException e) {
app.errorDialog(e.getLocalizedMessage()); app.errorDialog(e.getLocalizedMessage());
} }
} }
@@ -153,13 +154,13 @@ private void handle(FileAction fileAction, TextInputDialog dialog) {
private void fileDialog(FileAction fileAction, String label) { private void fileDialog(FileAction fileAction, String label) {
final TextInputDialog dialog = final TextInputDialog dialog =
TextInputDialog.builder(app.getDialogManager()) TextInputDialog.builder(app.getDialogManager())
.setLabel(lookup("label.file")) .setLabel(lookup("label.file"))
.setFocus(TextInputDialog::getInput) .setFocus(TextInputDialog::getInput)
.setTitle(label) .setTitle(label)
.setOkButton(lookup("button.ok"), d -> handle(fileAction, d)) .setOkButton(lookup("button.ok"), d -> handle(fileAction, d))
.setNoButton(lookup("button.cancel")) .setNoButton(lookup("button.cancel"))
.setOkClose(false) .setOkClose(false)
.build(); .build();
final String path = PREFERENCES.get(LAST_PATH, null); final String path = PREFERENCES.get(LAST_PATH, null);
if (path != null) if (path != null)
dialog.getInput().setText(path.trim()); dialog.getInput().setText(path.trim());

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; package pp.battleship.client;
import com.simsilica.lemur.Checkbox; import com.simsilica.lemur.Checkbox;
@@ -15,6 +8,7 @@
import pp.dialog.Dialog; import pp.dialog.Dialog;
import pp.dialog.DialogBuilder; import pp.dialog.DialogBuilder;
import pp.dialog.SimpleDialog; import pp.dialog.SimpleDialog;
import server.BattleshipServer;
import java.lang.System.Logger; import java.lang.System.Logger;
import java.lang.System.Logger.Level; import java.lang.System.Logger.Level;
@@ -31,7 +25,6 @@ class NetworkDialog extends SimpleDialog {
private static final Logger LOGGER = System.getLogger(NetworkDialog.class.getName()); private static final Logger LOGGER = System.getLogger(NetworkDialog.class.getName());
private static final String LOCALHOST = "localhost"; //NON-NLS private static final String LOCALHOST = "localhost"; //NON-NLS
private static final String DEFAULT_PORT = "1234"; //NON-NLS private static final String DEFAULT_PORT = "1234"; //NON-NLS
private static final int START_SERVER_DELAY = 2000;
private final NetworkSupport network; private final NetworkSupport network;
private final TextField host = new TextField(LOCALHOST); private final TextField host = new TextField(LOCALHOST);
private final TextField port = new TextField(DEFAULT_PORT); private final TextField port = new TextField(DEFAULT_PORT);
@@ -53,9 +46,9 @@ class NetworkDialog extends SimpleDialog {
host.setPreferredWidth(400f); host.setPreferredWidth(400f);
port.setSingleLine(true); port.setSingleLine(true);
Checkbox hostCheckbox = new Checkbox(lookup("host.own-server")); Checkbox hostServer = new Checkbox(lookup("start.own.server"));
hostCheckbox.setChecked(false); hostServer.setChecked(false);
hostCheckbox.addClickCommands(s -> hostServer = !hostServer); hostServer.addClickCommands(s -> toggleOwnServer());
final BattleshipApp app = network.getApp(); final BattleshipApp app = network.getApp();
final Container input = new Container(new SpringGridLayout()); final Container input = new Container(new SpringGridLayout());
@@ -63,77 +56,42 @@ class NetworkDialog extends SimpleDialog {
input.addChild(host, 1); input.addChild(host, 1);
input.addChild(new Label(lookup("port.number") + ": ")); input.addChild(new Label(lookup("port.number") + ": "));
input.addChild(port, 1); input.addChild(port, 1);
input.addChild(hostCheckbox); input.addChild(hostServer);
DialogBuilder.simple(app.getDialogManager()) DialogBuilder.simple(app.getDialogManager())
.setTitle(lookup("server.dialog")) .setTitle(lookup("server.dialog"))
.setExtension(d -> d.addChild(input)) .setExtension(d -> d.addChild(input))
.setOkButton(lookup("button.connect"), d -> connectHostServer()) .setOkButton(lookup("button.connect"), d -> connect())
.setNoButton(lookup("button.cancel"), app::closeApp) .setNoButton(lookup("button.cancel"), app::closeApp)
.setOkClose(false) .setOkClose(false)
.setNoClose(false) .setNoClose(false)
.build(this); .build(this);
} }
/** /**
* 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. * 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 LOGGER.log(Level.INFO, "connect to host={0}, port={1}", host, port); //NON-NLS
try { try {
hostname = host.getText().trim().isEmpty() ? LOCALHOST : host.getText(); hostname = host.getText().trim().isEmpty() ? LOCALHOST : host.getText();
portNumber = Integer.parseInt(port.getText()); portNumber = Integer.parseInt(port.getText());
openProgressDialog(); openProgressDialog();
connectionFuture = network.getApp().getExecutor().submit(this::initNetwork); connectionFuture = network.getApp().getExecutor().submit(this::initNetwork);
} catch (NumberFormatException e) { }
catch (NumberFormatException e) {
network.getApp().errorDialog(lookup("port.must.be.integer")); network.getApp().errorDialog(lookup("port.must.be.integer"));
} }
} }
/**
* Connects to the host server. If the `hostServer` flag is set, it starts the server
* before attempting to connect. If the server fails to start, logs an error.
*/
private void connectHostServer() {
if (hostServer) {
startServer();
try {
Thread.sleep(START_SERVER_DELAY);
} catch (Exception e) {
LOGGER.log(Level.ERROR, "Server start failed", e); //NON-NLS
}
connect();
} else {
connect();
}
}
/**
* Starts the game server in a new thread.
* Logs an error if the server fails to start.
*/
private void startServer() {
LOGGER.log(Level.INFO, "start server"); //NON-NLS
new Thread(() -> {
try {
LOGGER.log(Level.INFO, "Starting server..."); //NON-NLS
BattleshipServer server = new BattleshipServer(Integer.parseInt(port.getText()));
LOGGER.log(Level.INFO, "Server started"); //NON-NLS
server.run();
} catch (Exception e) {
LOGGER.log(Level.ERROR, "Server start failed", e); //NON-NLS
}
}).start();
}
/** /**
* Creates a dialog indicating that the connection is in progress. * Creates a dialog indicating that the connection is in progress.
*/ */
private void openProgressDialog() { private void openProgressDialog() {
progressDialog = DialogBuilder.simple(network.getApp().getDialogManager()) progressDialog = DialogBuilder.simple(network.getApp().getDialogManager())
.setText(lookup("label.connecting")) .setText(lookup("label.connecting"))
.build(); .build();
progressDialog.open(); progressDialog.open();
} }
@@ -146,7 +104,8 @@ private Object initNetwork() {
try { try {
network.initNetwork(hostname, portNumber); network.initNetwork(hostname, portNumber);
return null; return null;
} catch (Exception e) { }
catch (Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
@@ -161,9 +120,11 @@ public void update(float delta) {
try { try {
connectionFuture.get(); connectionFuture.get();
success(); success();
} catch (ExecutionException e) { }
catch (ExecutionException e) {
failure(e.getCause()); failure(e.getCause());
} catch (InterruptedException e) { }
catch (InterruptedException e) {
LOGGER.log(Level.WARNING, "Interrupted!", e); //NON-NLS LOGGER.log(Level.WARNING, "Interrupted!", e); //NON-NLS
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
} }
@@ -190,4 +151,46 @@ private void failure(Throwable e) {
network.getApp().errorDialog(lookup("server.connection.failed")); network.getApp().errorDialog(lookup("server.connection.failed"));
network.getApp().setInfoText(e.getLocalizedMessage()); 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; package pp.battleship.client;
import com.jme3.network.Client; import com.jme3.network.Client;

View File

@@ -1,28 +0,0 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.client;
import pp.battleship.message.client.ClientInterpreter;
import pp.battleship.message.client.ClientMessage;
/**
* Represents a received message from a client.
*
* @param message the client message
* @param from the ID of the sender
*/
record ReceivedMessage(ClientMessage message, int from) {
/**
* Processes the received message using the specified interpreter.
*
* @param interpreter the client interpreter
*/
void process(ClientInterpreter interpreter) {
message.accept(interpreter, from);
}
}

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; 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; 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; package pp.battleship.client.gui;
@@ -143,10 +138,6 @@ public float getHeight() {
return FIELD_SIZE * map.getHeight(); return FIELD_SIZE * map.getHeight();
} }
public static float getFieldSize() {
return FIELD_SIZE;
}
/** /**
* Converts coordinates from view coordinates to model coordinates. * Converts coordinates from view coordinates to model coordinates.
* *

View File

@@ -1,25 +1,19 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.client.gui; package pp.battleship.client.gui;
import com.jme3.material.Material;
import com.jme3.material.RenderState;
import com.jme3.math.ColorRGBA; import com.jme3.math.ColorRGBA;
import com.jme3.scene.Geometry; import com.jme3.scene.Geometry;
import com.jme3.scene.Node; import com.jme3.scene.Node;
import com.jme3.scene.Spatial; import com.jme3.scene.Spatial;
import com.jme3.scene.shape.Sphere;
import pp.battleship.model.Battleship; import pp.battleship.model.Battleship;
import pp.battleship.model.IntPoint;
import pp.battleship.model.Shell; import pp.battleship.model.Shell;
import pp.battleship.model.Shot; import pp.battleship.model.Shot;
import pp.util.Position; import pp.util.Position;
import static com.jme3.material.Materials.UNSHADED; import java.lang.System.Logger;
import java.lang.System.Logger.Level;
/** /**
* Synchronizes the visual representation of the ship map with the game model. * Synchronizes the visual representation of the ship map with the game model.
@@ -32,6 +26,9 @@ class MapViewSynchronizer extends ShipMapSynchronizer {
private static final float SHOT_DEPTH = -2f; private static final float SHOT_DEPTH = -2f;
private static final float SHIP_DEPTH = 0f; private static final float SHIP_DEPTH = 0f;
private static final float INDENT = 4f; 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 // Colors used for different visual elements
private static final ColorRGBA HIT_COLOR = ColorRGBA.Red; private static final ColorRGBA HIT_COLOR = ColorRGBA.Red;
@@ -43,6 +40,8 @@ class MapViewSynchronizer extends ShipMapSynchronizer {
// The MapView associated with this synchronizer // The MapView associated with this synchronizer
private final MapView view; private final MapView view;
static final Logger LOGGER = System.getLogger(MapViewSynchronizer.class.getName());
/** /**
* Constructs a new MapViewSynchronizer for the given MapView. * Constructs a new MapViewSynchronizer for the given MapView.
* Initializes the synchronizer and adds existing elements from the model to the view. * Initializes the synchronizer and adds existing elements from the model to the view.
@@ -64,16 +63,14 @@ public MapViewSynchronizer(MapView view) {
*/ */
@Override @Override
public Spatial visit(Shot shot) { public Spatial visit(Shot shot) {
LOGGER.log(Level.DEBUG, "visiting" + shot);
// Convert the shot's model coordinates to view coordinates // Convert the shot's model coordinates to view coordinates
final Position p1 = view.modelToView(shot.getX(), shot.getY()); final Position p1 = view.modelToView(shot.getX(), shot.getY());
final Position p2 = view.modelToView(shot.getX() + 1, shot.getY() + 1); final Position p2 = view.modelToView(shot.getX() + 1, shot.getY() + 1);
final ColorRGBA color = shot.isHit() ? HIT_COLOR : MISS_COLOR; final ColorRGBA color = shot.isHit() ? HIT_COLOR : MISS_COLOR;
// Create and return a rectangle representing the shot // Create and return a rectangle representing the shot
return view.getApp().getDraw().makeRectangle(p1.getX(), p1.getY(), return view.getApp().getDraw().makeRectangle(p1.getX(), p1.getY(), SHOT_DEPTH, p2.getX() - p1.getX(), p2.getY() - p1.getY(), color);
SHOT_DEPTH,
p2.getX() - p1.getX(), p2.getY() - p1.getY(),
color);
} }
/** /**
@@ -116,22 +113,29 @@ public Spatial visit(Battleship ship) {
} }
/** /**
* Creates a visual representation of a shell on the map. * Creates a visual representation on the map
* The shell is represented as a black ellipse.
* *
* @param shell the Shell object representing the shell in the model * @param shell the Shell element to visit
* @return a Spatial representing the shell on the map * @return the node the visual representation gets attached to.
*/ */
@Override @Override
public Spatial visit(Shell shell) { public Spatial visit(Shell shell) {
Geometry ellipse = new Geometry("ellipse", new Sphere(50, 50, MapView.getFieldSize() / 2 * 0.8f)); LOGGER.log(Logger.Level.DEBUG, "Visiting {0}", shell);
Material mat = new Material(view.getApp().getAssetManager(), UNSHADED); //NON-NLS final Node missileNode = new Node("missile");
mat.getAdditionalRenderState().setBlendMode(RenderState.BlendMode.Alpha); final Position p1 = view.modelToView(shell.getX(), shell.getY());
mat.getAdditionalRenderState().setFaceCullMode(RenderState.FaceCullMode.Off); final Position p2 = view.modelToView(shell.getX() + MISSILE_SIZE, shell.getY() + MISSILE_SIZE);
mat.setColor("Color", ColorRGBA.Black);
ellipse.setMaterial(mat); final float x1 = p1.getX() + INDENT;
ellipse.addControl(new ShellMapControl(view, shell)); final float y1 = p1.getY() + INDENT;
return ellipse; 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;
} }
/** /**
@@ -145,6 +149,7 @@ public Spatial visit(Shell shell) {
* @return a Geometry representing the line * @return a Geometry representing the line
*/ */
private Geometry shipLine(float x1, float y1, float x2, float y2, ColorRGBA color) { private Geometry shipLine(float x1, float y1, float x2, float y2, ColorRGBA color) {
LOGGER.log(Logger.Level.DEBUG, "created Ship line");
return view.getApp().getDraw().makeFatLine(x1, y1, x2, y2, SHIP_DEPTH, color, SHIP_LINE_WIDTH); return view.getApp().getDraw().makeFatLine(x1, y1, x2, y2, SHIP_DEPTH, color, SHIP_LINE_WIDTH);
} }
} }

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; package pp.battleship.client.gui;

View File

@@ -1,26 +1,24 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.client.gui; package pp.battleship.client.gui;
import com.jme3.effect.ParticleEmitter;
import com.jme3.effect.ParticleMesh;
import com.jme3.material.Material; import com.jme3.material.Material;
import com.jme3.material.RenderState;
import com.jme3.material.RenderState.BlendMode; import com.jme3.material.RenderState.BlendMode;
import com.jme3.math.ColorRGBA; import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector3f;
import com.jme3.renderer.queue.RenderQueue; import com.jme3.renderer.queue.RenderQueue;
import com.jme3.renderer.queue.RenderQueue.ShadowMode; import com.jme3.renderer.queue.RenderQueue.ShadowMode;
import com.jme3.scene.Geometry; import com.jme3.scene.Geometry;
import com.jme3.scene.Node; import com.jme3.scene.Node;
import com.jme3.scene.Spatial; import com.jme3.scene.Spatial;
import com.jme3.scene.shape.Box; import com.jme3.scene.shape.Box;
import com.jme3.scene.shape.Cylinder;
import pp.battleship.client.BattleshipApp; import pp.battleship.client.BattleshipApp;
import pp.battleship.model.*; 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;
import static java.util.Objects.requireNonNull; import static java.util.Objects.requireNonNull;
import static pp.util.FloatMath.HALF_PI; import static pp.util.FloatMath.HALF_PI;
@@ -34,18 +32,21 @@
*/ */
class SeaSynchronizer extends ShipMapSynchronizer { class SeaSynchronizer extends ShipMapSynchronizer {
private static final String UNSHADED = "Common/MatDefs/Misc/Unshaded.j3md"; //NON-NLS 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 DESTROYER_MODEL = "Models/Destroyer/Destroyer.j3o"; //NON-NLS private static final String UBOAT_MODEL = "Models/UBOAT/14084_WWII_Ship_German_Type_II_U-boat_v2_L1.obj";
private static final String DESTROYER_TEXTURE = "Models/Destroyer/BattleshipC.jpg"; //NON-NLS private static final String PATROL_BOAT_MODEL = "Models/PATROL_BOAT/12219_boat_v2_L2.obj";
private static final String TYPE_II_UBOAT_MODEL = "Models/TypeIIUboat/TypeIIUboat.j3o"; //NON-NLS private static final String MODERN_BATTLESHIP_MODEL = "Models/BATTLESHIP/10619_Battleship.obj";
private static final String TYPE_II_UBOAT_TEXTURE = "Models/TypeIIUboat/Type_II_U-boat_diff.jpg"; //NON-NLS private static final String MODERN_BATTLESHIP_TEXTURES = "Models/BATTLESHIP/BattleshipC.jpg";
private static final String ATLANTICA_MODEL = "Models/Atlantica/Atlantica.j3o"; //NON-NLS private static final String MISSILE_MODEL = "Models/Missile/AIM120D.obj";
private static final String ROCKET = "Models/Rocket/Rocket.j3o"; //NON-NLS private static final String MISSILE_TEXTURE = "Models/Missile/texture.png";
private static final String COLOR = "Color"; //NON-NLS private static final String COLOR = "Color"; //NON-NLS
private static final String SHIP = "ship"; //NON-NLS private static final String SHIP = "ship"; //NON-NLS
private static final String SHELL = "shell"; //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 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 ShipMap map;
private final BattleshipApp app; private final BattleshipApp app;
@@ -61,6 +62,7 @@ public SeaSynchronizer(BattleshipApp app, Node root, ShipMap map) {
super(app.getGameLogic().getOwnMap(), root); super(app.getGameLogic().getOwnMap(), root);
this.app = app; this.app = app;
this.map = map; this.map = map;
hitEffectHandler = new HitEffectHandler(app);
addExisting(); addExisting();
} }
@@ -74,7 +76,7 @@ public SeaSynchronizer(BattleshipApp app, Node root, ShipMap map) {
*/ */
@Override @Override
public Spatial visit(Shot shot) { public Spatial visit(Shot shot) {
return shot.isHit() ? handleHit(shot) : handleMiss(shot); return shot.isHit() ? handleHit(shot) : hitEffectHandler.missEffect(shot);
} }
/** /**
@@ -89,120 +91,31 @@ private Spatial handleHit(Shot shot) {
final Battleship ship = requireNonNull(map.findShipAt(shot), "Missing ship"); final Battleship ship = requireNonNull(map.findShipAt(shot), "Missing ship");
final Node shipNode = requireNonNull((Node) getSpatial(ship), "Missing ship node"); final Node shipNode = requireNonNull((Node) getSpatial(ship), "Missing ship node");
final ParticleEmitter debris = createDebrisEffect(shot); hitEffectHandler.hitEffect(shipNode, shot);
shipNode.attachChild(debris);
final ParticleEmitter fire = createFireEffect(shot, shipNode);
shipNode.attachChild(fire);
return null; return null;
} }
private Spatial handleMiss(Shot shot) {
return createMissEffect(shot);
}
private ParticleEmitter createMissEffect(Shot shot) {
final ParticleEmitter water = new ParticleEmitter("WaterEmitter", ParticleMesh.Type.Triangle, 20);
Material waterMaterial = new Material(app.getAssetManager(), "Common/MatDefs/Misc/Particle.j3md");
waterMaterial.setTexture("Texture", app.getAssetManager().loadTexture("Effects/Explosion/flame.png"));
water.setMaterial(waterMaterial);
water.setImagesX(2);
water.setImagesY(2);
water.setStartColor(ColorRGBA.Cyan);
water.setEndColor(ColorRGBA.Blue);
water.getParticleInfluencer().setInitialVelocity(new Vector3f(0.1f, 0.1f, 0.1f));
water.setStartSize(0.4f);
water.setEndSize(0.45f);
water.setGravity(0, -0.5f, 0);
water.setLowLife(1f);
water.setHighLife(1f);
water.setParticlesPerSec(0);
water.setLocalTranslation(shot.getY() + 0.5f, 0f, shot.getX() + 0.5f);
water.emitAllParticles();
return water;
}
private ParticleEmitter createDebrisEffect(Shot shot) {
final ParticleEmitter debris = new ParticleEmitter("DebrisEmitter", ParticleMesh.Type.Triangle, 2);
Material debrisMaterial = new Material(app.getAssetManager(), "Common/MatDefs/Misc/Particle.j3md");
debrisMaterial.setTexture("Texture", app.getAssetManager().loadTexture("Effects/Explosion/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.1f, 2f, 0.1f));
debris.setStartSize(0.1f);
debris.setEndSize(0.5f);
debris.setGravity(0, 3f, 0);
debris.getParticleInfluencer().setVelocityVariation(.40f);
debris.setLowLife(1f);
debris.setHighLife(1.5f);
debris.setParticlesPerSec(0);
debris.setLocalTranslation(shot.getY() + 0.5f, 0f, shot.getX() + 0.5f);
debris.emitAllParticles();
return debris;
}
private ParticleEmitter createFireEffect(Shot shot, Node shipNode) {
ParticleEmitter fire = new ParticleEmitter("FireEmitter", ParticleMesh.Type.Triangle, 100);
Material fireMaterial = new Material(app.getAssetManager(), "Common/MatDefs/Misc/Particle.j3md");
fireMaterial.setTexture("Texture", app.getAssetManager().loadTexture("Effects/Explosion/flame.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(shipNode.getLocalTranslation());
return fire;
}
/** /**
* Visits a {@link Shell} and creates a graphical representation of it. * Creates a cylinder geometry representing the specified shot.
* The shell is represented as a node with a model attached to it. * The appearance of the cylinder depends on whether the shot is a hit or a miss.
* The node is then positioned and controlled by a {@link ShellControl}.
* *
* @param shell the shell to be represented * @param shot the shot to be represented
* @return the node containing the graphical representation of the shell * @return the geometry representing the shot
*/ */
@Override private Geometry createCylinder(Shot shot) {
public Spatial visit(Shell shell) { final ColorRGBA color = shot.isHit() ? HIT_COLOR : SPLASH_COLOR;
final Node node = new Node(SHELL); final float height = shot.isHit() ? 1.2f : 0.1f;
node.attachChild(createShell());
node.setLocalTranslation(shell.getY() + 0.5f, 10f, shell.getX() + 0.5f);
node.addControl(new ShellControl());
return node;
}
/** final Cylinder cylinder = new Cylinder(2, 20, 0.45f, height, true);
* Creates a graphical representation of a shell. final Geometry geometry = new Geometry(SHOT, cylinder);
*
* @return the spatial representing the shell geometry.setMaterial(createColoredMaterial(color));
*/ geometry.rotate(HALF_PI, 0f, 0f);
private Spatial createShell() { // compute the center of the shot in world coordinates
final Spatial model = app.getAssetManager().loadModel(ROCKET); geometry.setLocalTranslation(shot.getY() + 0.5f, 0f, shot.getX() + 0.5f);
model.scale(0.0025f);
model.rotate(PI, 0f, 0f); return geometry;
model.setShadowMode(ShadowMode.CastAndReceive);
return model;
} }
/** /**
@@ -225,6 +138,24 @@ public Spatial visit(Battleship ship) {
return node; 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. * 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. * The representation is either a detailed model or a simple box based on the length of the ship.
@@ -234,9 +165,9 @@ public Spatial visit(Battleship ship) {
*/ */
private Spatial createShip(Battleship ship) { private Spatial createShip(Battleship ship) {
return switch (ship.getLength()) { return switch (ship.getLength()) {
case 1 -> createVessel(ship); case 1 -> createPatrolBoat(ship);
case 2 -> createSubmarine(ship); case 2 -> createModernBattleship(ship);
case 3 -> createDestroyer(ship); case 3 -> createUboat(ship);
case 4 -> createBattleship(ship); case 4 -> createBattleship(ship);
default -> createBox(ship); default -> createBox(ship);
}; };
@@ -250,10 +181,10 @@ private Spatial createShip(Battleship ship) {
*/ */
private Spatial createBox(Battleship ship) { private Spatial createBox(Battleship ship) {
final Box box = new Box(0.5f * (ship.getMaxY() - ship.getMinY()) + 0.3f, final Box box = new Box(0.5f * (ship.getMaxY() - ship.getMinY()) + 0.3f,
0.3f, 0.3f,
0.5f * (ship.getMaxX() - ship.getMinX()) + 0.3f); 0.5f * (ship.getMaxX() - ship.getMinX()) + 0.3f);
final Geometry geometry = new Geometry(SHIP, box); final Geometry geometry = new Geometry(SHIP, box);
geometry.setMaterial(createColoredMaterial()); geometry.setMaterial(createColoredMaterial(BOX_COLOR));
geometry.setShadowMode(ShadowMode.CastAndReceive); geometry.setShadowMode(ShadowMode.CastAndReceive);
return geometry; return geometry;
@@ -265,14 +196,16 @@ private Spatial createBox(Battleship ship) {
* the material's render state is set to use alpha blending, allowing for * the material's render state is set to use alpha blending, allowing for
* semi-transparent rendering. * semi-transparent rendering.
* *
* @param color the {@link ColorRGBA} to be applied to the material. If the alpha value
* of the color is less than 1, the material will support transparency.
* @return a {@link Material} instance configured with the specified color and, * @return a {@link Material} instance configured with the specified color and,
* if necessary, alpha blending enabled. * if necessary, alpha blending enabled.
*/ */
private Material createColoredMaterial() { private Material createColoredMaterial(ColorRGBA color) {
final Material material = new Material(app.getAssetManager(), UNSHADED); final Material material = new Material(app.getAssetManager(), UNSHADED);
if (SeaSynchronizer.BOX_COLOR.getAlpha() < 1f) if (color.getAlpha() < 1f)
material.getAdditionalRenderState().setBlendMode(BlendMode.Alpha); material.getAdditionalRenderState().setBlendMode(BlendMode.Alpha);
material.setColor(COLOR, SeaSynchronizer.BOX_COLOR); material.setColor(COLOR, color);
return material; return material;
} }
@@ -293,62 +226,80 @@ private Spatial createBattleship(Battleship ship) {
} }
/** /**
* Creates a detailed 3D model to represent a destroyer battleship. * Creates a detailed 3D model to represent a modern battleship.
* *
* @param ship the battleship to be represented * @param ship the battleship to be represented
* @return the spatial representing the destroyer battleship * @return the spatial representing the battleship
*/ */
private Spatial createDestroyer(Battleship ship) {
final Spatial model = app.getAssetManager().loadModel(DESTROYER_MODEL);
private Spatial createModernBattleship(Battleship ship) {
final Spatial model = app.getAssetManager().loadModel(MODERN_BATTLESHIP_MODEL);
Material mat = new Material(app.getAssetManager(), UNSHADED); Material mat = new Material(app.getAssetManager(), UNSHADED);
mat.setTexture("ColorMap", app.getAssetManager().loadTexture(DESTROYER_TEXTURE)); mat.setTexture("ColorMap", app.getAssetManager().loadTexture(MODERN_BATTLESHIP_TEXTURES));
mat.getAdditionalRenderState().setBlendMode(BlendMode.Off); mat.getAdditionalRenderState().setBlendMode(RenderState.BlendMode.Off);
model.setMaterial(mat); model.setMaterial(mat);
model.setQueueBucket(RenderQueue.Bucket.Opaque); model.setQueueBucket(RenderQueue.Bucket.Opaque);
model.rotate(-HALF_PI, calculateRotationAngle(ship.getRot()), 0f); model.rotate(-HALF_PI, calculateRotationAngle(ship.getRot()) + HALF_PI, 0f);
model.scale(0.1f); model.scale(0.000075f);
model.setLocalTranslation(0f, 0.25f, 0f);
model.setShadowMode(ShadowMode.CastAndReceive); model.setShadowMode(ShadowMode.CastAndReceive);
model.move(0, 0.2f, 0);
return model; return model;
} }
/** /**
* Creates a detailed 3D model to represent a Type II U-boat submarine. * Creates a detailed 3D model to represent a missile.
* *
* @param ship the battleship to be represented * @return the spatial representing the missile
* @return the spatial representing the Type II U-boat submarine
*/ */
private Spatial createSubmarine(Battleship ship) {
final Spatial model = app.getAssetManager().loadModel(TYPE_II_UBOAT_MODEL);
private Spatial createMissile() {
final Spatial model = app.getAssetManager().loadModel(MISSILE_MODEL);
Material mat = new Material(app.getAssetManager(), UNSHADED); Material mat = new Material(app.getAssetManager(), UNSHADED);
mat.setTexture("ColorMap", app.getAssetManager().loadTexture(TYPE_II_UBOAT_TEXTURE)); mat.setTexture("ColorMap", app.getAssetManager().loadTexture(MISSILE_TEXTURE));
mat.getAdditionalRenderState().setBlendMode(RenderState.BlendMode.Off);
model.setMaterial(mat); model.setMaterial(mat);
model.rotate(-HALF_PI, calculateRotationAngle(ship.getRot()), 0f); model.setQueueBucket(RenderQueue.Bucket.Opaque);
model.scale(0.25f);
model.getLocalTranslation().addLocal(0f, -0.15f, 0f); model.rotate(-HALF_PI, 0, 0);
model.scale(0.009f);
model.setShadowMode(ShadowMode.CastAndReceive); 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; return model;
} }
/** /**
* Creates a detailed 3D model to represent a vessel. * Creates a detailed 3D model to represent a Patrol boat.
* *
* @param ship the battleship to be represented * @param ship the battleship to be represented
* @return the spatial representing the vessel * @return the spatial representing the Patrol boat
*/ */
private Spatial createVessel(Battleship ship) {
final Spatial model = app.getAssetManager().loadModel(ATLANTICA_MODEL); private Spatial createPatrolBoat(Battleship ship) {
final Spatial model = app.getAssetManager().loadModel(PATROL_BOAT_MODEL);
model.rotate(-HALF_PI, calculateRotationAngle(ship.getRot()), 0f); model.rotate(-HALF_PI, calculateRotationAngle(ship.getRot()), 0f);
model.scale(0.0003f); model.scale(0.00045f);
model.getLocalTranslation().addLocal(0f, -0.05f, 0f);
model.setShadowMode(ShadowMode.CastAndReceive); model.setShadowMode(ShadowMode.CastAndReceive);
return model; return model;

View File

@@ -3,40 +3,60 @@
import com.jme3.renderer.RenderManager; import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort; import com.jme3.renderer.ViewPort;
import com.jme3.scene.control.AbstractControl; 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;
/** /**
* Controls the movement and rotation of a shell in the game. * Class to control the 3D representation of a shell
* The shell moves downward at a constant speed and rotates around its Y-axis.
* When the shell reaches a certain Y-coordinate, it is removed from its parent node.
*/ */
public class ShellControl extends AbstractControl { public class ShellControl extends AbstractControl {
private final static float SHELL_SPEED = 7.5f;
private final static float SHELL_ROTATION_SPEED = 0.5f; private final Shell shell;
private final static float MIN_HEIGHT = 0.7f; private final BattleshipApp app;
private static final float TRAVEL_SPEED = 8.5f;
static final Logger LOGGER = System.getLogger(BattleshipApp.class.getName());
/** /**
* Updates the shell's position and rotation. * Constructor for ShellControl class
* If the shell's Y-coordinate is less than or equal to 1.0, it is detached from its parent node.
* *
* @param tpf time per frame, used to ensure consistent movement speed across different frame rates * @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 @Override
protected void controlUpdate(float tpf) { public void controlUpdate(float tpf) {
spatial.move(0, -SHELL_SPEED * tpf, 0); //LOGGER.log(Level.DEBUG, "missile at x=" + shell.getX() + ", y=" + shell.getY());
spatial.rotate(0, SHELL_ROTATION_SPEED, 0); spatial.move(0, -TRAVEL_SPEED * tpf, 0);
if (spatial.getLocalTranslation().getY() <= MIN_HEIGHT) { if (spatial.getLocalTranslation().getY() <= 0.2) {
spatial.getParent().detachChild(spatial); spatial.getParent().detachChild(spatial);
app.getGameLogic().send(new EndAnimationMessage(new IntPoint(shell.getX(), shell.getY())));
} }
} }
/** /**
* Renders the shell. This method is currently not used. * 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 * @param rm the RenderManager rendering the controlled Spatial (not null)
* @param vp the ViewPort * @param vp the ViewPort being rendered (not null)
*/ */
@Override @Override
protected void controlRender(RenderManager rm, ViewPort vp) { protected void controlRender(RenderManager rm, ViewPort vp) {
// nothing to do here
} }
} }

View File

@@ -4,79 +4,59 @@
import com.jme3.renderer.RenderManager; import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort; import com.jme3.renderer.ViewPort;
import com.jme3.scene.control.AbstractControl; import com.jme3.scene.control.AbstractControl;
import pp.battleship.model.Shell; import pp.battleship.client.BattleshipApp;
import pp.battleship.message.client.EndAnimationMessage;
import pp.battleship.model.IntPoint;
import pp.util.Position; import pp.util.Position;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
/** /**
* Controls the animation of a shell in the map view. * Class to control the 2D representation of a shell
* This class handles the movement of a shell from its starting position to its target position
* using linear interpolation over a specified duration.
*/ */
public class ShellMapControl extends AbstractControl { public class ShellMapControl extends AbstractControl {
private static final Logger LOGGER = System.getLogger(ShellMapControl.class.getName()); private final Position position;
private final IntPoint pos;
private static final Vector3f VECTOR_3_F = new Vector3f();
private final BattleshipApp app;
/** /**
* The duration of the shell animation in seconds. * Constructor for ShellMapControl
*/
private final static float ANIMATION_DURATION = 0.8f;
/**
* The end position of the shell in the map view.
*/
private final Position endPos;
/**
* The progress of the shell's movement, ranging from 0 to 1.
*/
private float progress = 0f;
/**
* Constructs a new instance of {@link ShellMapControl}.
* *
* @param view the map view * @param position the target position of the shell
* @param shell the shell to be controlled * @param app the main application
* @param pos the position the then to render shot goes to
*/ */
public ShellMapControl(MapView view, Shell shell) { public ShellMapControl(Position position, BattleshipApp app, IntPoint pos) {
Vector3f endPos = new Vector3f(shell.getX(), 0, shell.getY()); super();
this.endPos = view.modelToView(endPos.x, endPos.z); this.position = position;
LOGGER.log(Level.DEBUG, "ShellMapControl created with endPos: " + this.endPos); this.pos = pos;
this.app = app;
VECTOR_3_F.set(new Vector3f(position.getX(), position.getY(), 0));
} }
/** /**
* Updates the position of the shell in the view with linear interpolation. * Method to control movement of the Shell on the map and remove it when target is reached
* This method is called during the update phase.
* *
* @param tpf the time per frame * @param tpf time per frame (in seconds)
*/ */
@Override @Override
protected void controlUpdate(float tpf) { protected void controlUpdate(float tpf) {
// adjust speed by changing the multiplier spatial.move(VECTOR_3_F.mult(tpf));
progress += tpf * ANIMATION_DURATION; if (spatial.getLocalTranslation().getX() >= position.getX() && spatial.getLocalTranslation().getY() >= position.getY()) {
spatial.getParent().detachChild(spatial);
// progress is between 0 and 1 app.getGameLogic().send(new EndAnimationMessage(pos));
if (progress > 1f) {
progress = 1f;
} }
// linearly interpolate the current position between (0, 0) and endPos
float newX = (1 - progress) * 0 + progress * endPos.getX() + MapView.getFieldSize() / 2;
float newZ = (1 - progress) * 0 + progress * endPos.getY() + MapView.getFieldSize() / 2;
spatial.setLocalTranslation(newX, newZ, 0);
} }
/** /**
* This method is called during the render phase. * This method is called during the rendering phase, but it does not perform any
* Currently, it does nothing. * operations in this implementation as the control only influences the spatial's
* transformation, not its rendering process.
* *
* @param rm the RenderManager * @param rm the RenderManager rendering the controlled Spatial (not null)
* @param vp the ViewPort * @param vp the ViewPort being rendered (not null)
*/ */
@Override @Override
protected void controlRender(RenderManager rm, ViewPort vp) { protected void controlRender(RenderManager rm, ViewPort vp) {
// nothing to do here
} }
} }

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; package pp.battleship.client.gui;
@@ -14,6 +9,9 @@
import com.jme3.scene.control.AbstractControl; import com.jme3.scene.control.AbstractControl;
import pp.battleship.model.Battleship; 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.DEG_TO_RAD;
import static pp.util.FloatMath.TWO_PI; import static pp.util.FloatMath.TWO_PI;
import static pp.util.FloatMath.sin; import static pp.util.FloatMath.sin;
@@ -47,10 +45,12 @@ class ShipControl extends AbstractControl {
* The current time within the oscillation cycle, used to calculate the ship's pitch angle. * The current time within the oscillation cycle, used to calculate the ship's pitch angle.
*/ */
private float time; private float time;
/**
* Ship to be controlled
*/
private final Battleship battleship;
private final Battleship ship; private static final Logger LOGGER = System.getLogger(ShipControl.class.getName());
private static final float SINKING_HEIGHT = -0.6f;
/** /**
* Constructs a new ShipControl instance for the specified Battleship. * Constructs a new ShipControl instance for the specified Battleship.
@@ -60,6 +60,7 @@ class ShipControl extends AbstractControl {
* @param ship the Battleship object to control * @param ship the Battleship object to control
*/ */
public ShipControl(Battleship ship) { public ShipControl(Battleship ship) {
this.battleship = ship;
// Determine the axis of rotation based on the ship's orientation // Determine the axis of rotation based on the ship's orientation
axis = switch (ship.getRot()) { axis = switch (ship.getRot()) {
case LEFT, RIGHT -> Vector3f.UNIT_X; case LEFT, RIGHT -> Vector3f.UNIT_X;
@@ -67,10 +68,8 @@ public ShipControl(Battleship ship) {
}; };
// Set the cycle duration and amplitude based on the ship's length // 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(); amplitude = 5f * DEG_TO_RAD / ship.getLength();
this.ship = ship;
} }
/** /**
@@ -84,23 +83,23 @@ protected void controlUpdate(float tpf) {
// If spatial is null, do nothing // If spatial is null, do nothing
if (spatial == null) return; if (spatial == null) return;
// Handle ship sinking by moving it downwards if (battleship.isDestroyed() && spatial.getLocalTranslation().getY() < -0.6f) {
if (ship.isDestroyed()) { LOGGER.log(Level.INFO, "Ship removed {0}", spatial.getName());
if (spatial.getLocalTranslation().getY() < SINKING_HEIGHT) { spatial.getParent().detachChild(spatial);
spatial.getParent().detachChild(spatial);
} else {
spatial.move(0, -tpf * 0.1f, 0);
}
} }
else if (battleship.isDestroyed()) {
spatial.move(0, -0.2f * tpf, 0);
}
else {
// Update the time within the oscillation cycle
time = (time + tpf) % cycle;
// Update the time within the oscillation cycle // Calculate the current angle of the oscillation
time = (time + tpf) % cycle; final float angle = amplitude * sin(time * TWO_PI / cycle);
// Calculate the current angle of the oscillation // Update the pitch Quaternion with the new angle
final float angle = amplitude * sin(time * TWO_PI / cycle); pitch.fromAngleAxis(angle, axis);
}
// Update the pitch Quaternion with the new angle
pitch.fromAngleAxis(angle, axis);
// Apply the pitch rotation to the spatial // Apply the pitch rotation to the spatial
spatial.setLocalRotation(pitch); 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; package pp.battleship.client.gui;

View File

@@ -1,11 +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;
package server;
import com.jme3.network.ConnectionListener; import com.jme3.network.ConnectionListener;
import com.jme3.network.HostedConnection; import com.jme3.network.HostedConnection;
@@ -18,14 +13,16 @@
import pp.battleship.game.server.Player; import pp.battleship.game.server.Player;
import pp.battleship.game.server.ServerGameLogic; import pp.battleship.game.server.ServerGameLogic;
import pp.battleship.game.server.ServerSender; import pp.battleship.game.server.ServerSender;
import pp.battleship.message.client.AnimationMessage;
import pp.battleship.message.client.ClientMessage; import pp.battleship.message.client.ClientMessage;
import pp.battleship.message.client.EndAnimationMessage;
import pp.battleship.message.client.MapMessage; import pp.battleship.message.client.MapMessage;
import pp.battleship.message.client.ShootMessage; import pp.battleship.message.client.ShootMessage;
import pp.battleship.message.server.EffectMessage; import pp.battleship.message.server.EffectMessage;
import pp.battleship.message.server.GameDetails; import pp.battleship.message.server.GameDetails;
import pp.battleship.message.server.ServerMessage; import pp.battleship.message.server.ServerMessage;
import pp.battleship.message.server.StartAnimationMessage;
import pp.battleship.message.server.StartBattleMessage; import pp.battleship.message.server.StartBattleMessage;
import pp.battleship.message.server.SwitchToBattleState;
import pp.battleship.model.Battleship; import pp.battleship.model.Battleship;
import pp.battleship.model.IntPoint; import pp.battleship.model.IntPoint;
import pp.battleship.model.Shot; import pp.battleship.model.Shot;
@@ -43,39 +40,14 @@
* Server implementing the visitor pattern as MessageReceiver for ClientMessages * Server implementing the visitor pattern as MessageReceiver for ClientMessages
*/ */
public class BattleshipServer implements MessageListener<HostedConnection>, ConnectionListener, ServerSender { public class BattleshipServer implements MessageListener<HostedConnection>, ConnectionListener, ServerSender {
/**
* Logger for the BattleshipServer class.
*/
private static final Logger LOGGER = System.getLogger(BattleshipServer.class.getName()); private static final Logger LOGGER = System.getLogger(BattleshipServer.class.getName());
/**
* Configuration file for the server.
*/
private static final File CONFIG_FILE = new File("server.properties"); private static final File CONFIG_FILE = new File("server.properties");
/** private static int port;
* Port number for the server.
*/
private final int PORT_NUMBER;
/**
* Configuration settings for the Battleship server.
*/
private final BattleshipConfig config = new BattleshipConfig(); private final BattleshipConfig config = new BattleshipConfig();
/**
* The server instance.
*/
private Server myServer; private Server myServer;
/**
* Game logic for the server.
*/
private final ServerGameLogic logic; private final ServerGameLogic logic;
/**
* Queue for pending messages to be processed by the server.
*/
private final BlockingQueue<ReceivedMessage> pendingMessages = new LinkedBlockingQueue<>(); private final BlockingQueue<ReceivedMessage> pendingMessages = new LinkedBlockingQueue<>();
static { static {
@@ -84,7 +56,8 @@ public class BattleshipServer implements MessageListener<HostedConnection>, Conn
try { try {
manager.readConfiguration(new FileInputStream("logging.properties")); manager.readConfiguration(new FileInputStream("logging.properties"));
LOGGER.log(Level.INFO, "Successfully read logging properties"); //NON-NLS LOGGER.log(Level.INFO, "Successfully read logging properties"); //NON-NLS
} catch (IOException e) { }
catch (IOException e) {
LOGGER.log(Level.INFO, e.getMessage()); LOGGER.log(Level.INFO, e.getMessage());
} }
} }
@@ -92,15 +65,15 @@ public class BattleshipServer implements MessageListener<HostedConnection>, Conn
/** /**
* Creates the server. * Creates the server.
*/ */
public BattleshipServer(int PORT_NUMBER) { public BattleshipServer(int port) {
config.readFromIfExists(CONFIG_FILE); config.readFromIfExists(CONFIG_FILE);
this.PORT_NUMBER = PORT_NUMBER; BattleshipServer.port = port;
LOGGER.log(Level.INFO, "Configuration: {0}", config); //NON-NLS LOGGER.log(Level.INFO, "Configuration: {0}", config); //NON-NLS
logic = new ServerGameLogic(this, config); logic = new ServerGameLogic(this, config);
} }
/** /**
* Starts the server and processes incoming messages indefinitely. * Runs a server
*/ */
public void run() { public void run() {
startServer(); startServer();
@@ -109,73 +82,67 @@ public void run() {
} }
/** /**
* Starts the server and initializes necessary components. * Starts a server
* This method sets up the server, registers serializable classes,
* starts the server, and registers listeners for incoming connections and messages.
* If the server fails to start, it logs an error and exits the application.
*/ */
private void startServer() { private void startServer() {
try { try {
LOGGER.log(Level.INFO, "Starting server..."); //NON-NLS LOGGER.log(Level.INFO, "Starting server..."); //NON-NLS
myServer = Network.createServer(PORT_NUMBER); myServer = Network.createServer(port);
initializeSerializables(); initializeSerializables();
myServer.start(); myServer.start();
registerListeners(); registerListeners();
LOGGER.log(Level.INFO, "Server started: {0}", myServer.isRunning()); //NON-NLS LOGGER.log(Level.INFO, "Server started: {0}", myServer.isRunning()); //NON-NLS
} catch (IOException e) { }
catch (IOException e) {
LOGGER.log(Level.ERROR, "Couldn't start server: {0}", e.getMessage()); //NON-NLS LOGGER.log(Level.ERROR, "Couldn't start server: {0}", e.getMessage()); //NON-NLS
exit(1); exit(1);
} }
} }
/** /**
* Processes the next message in the queue. * Processes next received message
* This method blocks until a message is available, then processes it using the server logic.
* If interrupted while waiting, it logs the interruption and re-interrupts the thread.
*/ */
private void processNextMessage() { private void processNextMessage() {
try { try {
pendingMessages.take().process(logic); pendingMessages.take().process(logic);
} catch (InterruptedException ex) { }
catch (InterruptedException ex) {
LOGGER.log(Level.INFO, "Interrupted while waiting for messages"); //NON-NLS LOGGER.log(Level.INFO, "Interrupted while waiting for messages"); //NON-NLS
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
} }
} }
/** /**
* Registers the serializable classes used by the server. * Registers all serializable classes
* This method ensures that the necessary classes are registered with the serializer
* so that they can be correctly transmitted over the network.
*/ */
private void initializeSerializables() { private void initializeSerializables() {
Serializer.registerClass(GameDetails.class); Serializer.registerClass(GameDetails.class);
Serializer.registerClass(StartBattleMessage.class); Serializer.registerClass(StartBattleMessage.class);
Serializer.registerClass(MapMessage.class); Serializer.registerClass(MapMessage.class);
Serializer.registerClass(ShootMessage.class); Serializer.registerClass(ShootMessage.class);
Serializer.registerClass(AnimationMessage.class);
Serializer.registerClass(EffectMessage.class); Serializer.registerClass(EffectMessage.class);
Serializer.registerClass(Battleship.class); Serializer.registerClass(Battleship.class);
Serializer.registerClass(IntPoint.class); Serializer.registerClass(IntPoint.class);
Serializer.registerClass(Shot.class); Serializer.registerClass(Shot.class);
Serializer.registerClass(StartAnimationMessage.class);
Serializer.registerClass(EndAnimationMessage.class);
Serializer.registerClass(SwitchToBattleState.class);
} }
/** /**
* Registers listeners for incoming connections and messages. * Registers all listeners
* This method adds message listeners for `MapMessage` and `ShootMessage` classes,
* and a connection listener for handling connection events.
*/ */
private void registerListeners() { private void registerListeners() {
myServer.addMessageListener(this, MapMessage.class); myServer.addMessageListener(this, MapMessage.class);
myServer.addMessageListener(this, ShootMessage.class); myServer.addMessageListener(this, ShootMessage.class);
myServer.addMessageListener(this, AnimationMessage.class); myServer.addMessageListener(this, EndAnimationMessage.class);
myServer.addConnectionListener(this); myServer.addConnectionListener(this);
} }
/** /**
* Handles the reception of messages from clients. * Handles a received message
* * @param source the connection the message comes from
* @param source the connection from which the message was received * @param message the received message
* @param message the message received from the client
*/ */
@Override @Override
public void messageReceived(HostedConnection source, Message message) { public void messageReceived(HostedConnection source, Message message) {
@@ -185,10 +152,9 @@ public void messageReceived(HostedConnection source, Message message) {
} }
/** /**
* Called when a new connection is added to the server. * Adds a new connection to a server
* * @param server the server to add the connection to
* @param server the server to which the connection was added * @param hostedConnection the connection to be added
* @param hostedConnection the connection that was added
*/ */
@Override @Override
public void connectionAdded(Server server, HostedConnection hostedConnection) { public void connectionAdded(Server server, HostedConnection hostedConnection) {
@@ -197,10 +163,9 @@ public void connectionAdded(Server server, HostedConnection hostedConnection) {
} }
/** /**
* Called when a connection is removed from the server. * Removes a standing connection from a server
* * @param server the server to add the connection to
* @param server the server from which the connection was removed * @param hostedConnection the connection to be added
* @param hostedConnection the connection that was removed
*/ */
@Override @Override
public void connectionRemoved(Server server, HostedConnection hostedConnection) { public void connectionRemoved(Server server, HostedConnection hostedConnection) {
@@ -215,10 +180,8 @@ public void connectionRemoved(Server server, HostedConnection hostedConnection)
} }
/** /**
* Exits the application with the specified exit value. * Shuts down the server and terminates the application with the given exit code
* Closes all client connections and logs the close request. * @param exitValue the exit status code
*
* @param exitValue the exit value to be used when exiting the application
*/ */
private void exit(int exitValue) { //NON-NLS private void exit(int exitValue) { //NON-NLS
LOGGER.log(Level.INFO, "close request"); //NON-NLS LOGGER.log(Level.INFO, "close request"); //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

@@ -1,3 +0,0 @@
based on:
https://free3d.com/3d-model/boat-v2--225787.html
License: Free Personal Use Only

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

View File

@@ -1,92 +0,0 @@
# Blender 4.1.0 MTL File: 'None'
# www.blender.org
newmtl Battleship
Ns 256.000031
Ka 1.000000 1.000000 1.000000
Ks 0.000000 0.000000 0.000000
Ke 0.000000 0.000000 0.000000
Ni 1.000000
d 1.000000
illum 1
map_Kd BattleshipC.jpg
newmtl blinn1SG
Ns 256.000031
Ka 1.000000 1.000000 1.000000
Kd 0.500000 0.500000 0.500000
Ks 0.000000 0.000000 0.000000
Ke 0.000000 0.000000 0.000000
Ni 1.000000
d 1.000000
illum 1
newmtl blinn2SG
Ns 256.000031
Ka 1.000000 1.000000 1.000000
Kd 0.500000 0.500000 0.500000
Ks 0.000000 0.000000 0.000000
Ke 0.000000 0.000000 0.000000
Ni 1.000000
d 1.000000
illum 1
newmtl blinn3SG
Ns 256.000031
Ka 1.000000 1.000000 1.000000
Kd 0.500000 0.500000 0.500000
Ks 0.500000 0.500000 0.500000
Ke 0.000000 0.000000 0.000000
Ni 1.000000
d 1.000000
illum 2
newmtl blinn4SG
Ns 256.000031
Ka 1.000000 1.000000 1.000000
Kd 0.500000 0.500000 0.500000
Ks 0.500000 0.500000 0.500000
Ke 0.000000 0.000000 0.000000
Ni 1.000000
d 1.000000
illum 2
newmtl blinn5SG
Ns 256.000031
Ka 1.000000 1.000000 1.000000
Kd 0.500000 0.500000 0.500000
Ks 0.500000 0.500000 0.500000
Ke 0.000000 0.000000 0.000000
Ni 1.000000
d 1.000000
illum 2
newmtl blinn6SG
Ns 256.000031
Ka 1.000000 1.000000 1.000000
Kd 0.500000 0.500000 0.500000
Ks 0.500000 0.500000 0.500000
Ke 0.000000 0.000000 0.000000
Ni 1.000000
d 1.000000
illum 2
newmtl blinn7SG
Ns 256.000031
Ka 1.000000 1.000000 1.000000
Kd 0.500000 0.500000 0.500000
Ks 0.500000 0.500000 0.500000
Ke 0.000000 0.000000 0.000000
Ni 1.000000
d 1.000000
illum 2
newmtl blinn8SG
Ns 256.000031
Ka 1.000000 1.000000 1.000000
Kd 0.500000 0.500000 0.500000
Ks 0.500000 0.500000 0.500000
Ke 0.000000 0.000000 0.000000
Ni 1.000000
d 1.000000
illum 2

View File

@@ -1,3 +0,0 @@
based on:
https://free3d.com/3d-model/battleship-v1--611736.html
License: Free Personal Use Only

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

@@ -1,250 +0,0 @@
#
# Generated by Sweet Home 3D - ven. janv. 02 20:37:08 CET 2015
# http://www.sweethome3d.com/
#
newmtl FrontColorNoCulling
illum 1
Ka 0.2 0.2 0.2
Kd 0.2 0.2 0.2
Ks 0.0 0.0 0.0
Ns 0.0
newmtl ForegroundColor
illum 1
Ka 0.2 0.2 0.2
Kd 0.2 0.2 0.2
Ks 0.0 0.0 0.0
Ns 0.0
newmtl white
illum 1
Ka 0.48235294 0.5019608 0.5803922
Kd 0.48235294 0.5019608 0.5803922
Ks 0.0 0.0 0.0
Ns 0.0
newmtl white_Cylinder_5
illum 1
Ka 0.47843137 0.49803922 0.5764706
Kd 0.47843137 0.49803922 0.5764706
Ks 0.0 0.0 0.0
Ns 0.0
newmtl white_Cylinder_10
illum 1
Ka 0.8784314 0.8745098 0.8901961
Kd 0.8784314 0.8745098 0.8901961
Ks 0.0 0.0 0.0
Ns 0.0
newmtl FrontColorNoCulling_11
illum 1
Ka 0.8784314 0.8745098 0.8901961
Kd 0.8784314 0.8745098 0.8901961
Ks 0.0 0.0 0.0
Ns 0.0
newmtl ForegroundColor_12
illum 1
Ka 0.8784314 0.8745098 0.8901961
Kd 0.8784314 0.8745098 0.8901961
Ks 0.0 0.0 0.0
Ns 0.0
newmtl white_Mesh_13
illum 1
Ka 0.6 0.6 0.6
Kd 0.6 0.6 0.6
Ks 0.0 0.0 0.0
Ns 0.0
newmtl Cube_1_1_1
illum 1
Ka 0.0 0.0 0.0
Kd 0.0 0.0 0.0
Ks 0.0 0.0 0.0
Ns 1.0
newmtl Cylinder_7_7
illum 1
Ka 0.4 0.4 0.4
Kd 0.4 0.4 0.4
Ks 0.0 0.0 0.0
Ns 1.0
newmtl Cylinder_10_10
illum 1
Ka 0.8 0.4 0.0
Kd 0.8 0.4 0.0
Ks 0.0 0.0 0.0
Ns 1.0
newmtl Cylinder_11_11
illum 2
Ka 0.2 0.2 0.2
Kd 0.2 0.2 0.2
Ks 0.0 0.0 0.0
Ns 1.0
newmtl 12_12
illum 1
Ka 0.2 0.2 0.2
Kd 0.2 0.2 0.2
Ks 0.0 0.0 0.0
Ns 1.0
newmtl Cube_1_1_1_Cube_1_1_1_38
illum 1
Ka 0.6 0.6 0.6
Kd 0.6 0.6 0.6
Ks 0.0 0.0 0.0
Ns 1.0
newmtl white_Cylinder_58
illum 1
Ka 0.1882353 0.27058825 0.58431375
Kd 0.1882353 0.27058825 0.58431375
Ks 0.0 0.0 0.0
Ns 0.0
newmtl white_Cylinder_59
illum 1
Ka 0.3137255 0.14901961 0.011764706
Kd 0.3137255 0.14901961 0.011764706
Ks 0.0 0.0 0.0
Ns 0.0
newmtl 1_1
illum 2
Ka 0.2 0.2 0.2
Kd 1.0 1.0 1.0
Ks 0.5 0.5 0.5
Ns 64.0
Ni 1.0
d 0.48000002
map_Kd Missile_AIM-120_D_[AMRAAM]_1_1.png
newmtl Cube_1_2_2
illum 1
Ka 0.8 0.4 0.0
Kd 0.8 0.4 0.0
Ks 0.0 0.0 0.0
Ns 1.0
newmtl Cylinder_4_4
illum 2
Ka 0.6 0.6 0.6
Kd 0.6 0.6 0.6
Ks 0.5 0.5 0.5
Ns 64.0
newmtl Cylinder_5_5
illum 2
Ka 0.8 0.8 0.0
Kd 0.8 0.8 0.0
Ks 0.5 0.5 0.5
Ns 64.0
newmtl Cylinder_6_6
illum 2
Ka 0.8784314 0.8745098 0.8901961
Kd 0.8784314 0.8745098 0.8901961
Ks 0.5 0.5 0.5
Ns 64.0
newmtl Cylinder_10_10_Cylinder_10_10_73
illum 1
Ka 0.2 0.2 0.2
Kd 0.2 0.2 0.2
Ks 0.0 0.0 0.0
Ns 1.0
newmtl 11_11
illum 1
Ka 0.6 0.6 0.6
Kd 0.6 0.6 0.6
Ks 0.0 0.0 0.0
Ns 1.0
newmtl Cube_1_1_1_Cube_1_1_1_76
illum 1
Ka 0.2 0.2 0.2
Kd 1.0 1.0 1.0
Ks 0.0 0.0 0.0
Ns 1.0
Ni 1.0
map_Kd Missile_AIM-120_D_[AMRAAM]_Cube_1_1_1_Cube_1_1_1_76.png
newmtl Cylinder_2_2
illum 2
Ka 0.6 0.6 0.6
Kd 0.6 0.6 0.6
Ks 0.5 0.5 0.5
Ns 64.0
newmtl Cylinder_3_3
illum 1
Ka 0.4 0.4 0.0
Kd 0.4 0.4 0.0
Ks 0.0 0.0 0.0
Ns 1.0
newmtl Cylinder_4_4_Cylinder_4_4_79
illum 1
Ka 0.0 0.0 0.0
Kd 0.0 0.0 0.0
Ks 0.0 0.0 0.0
Ns 1.0
newmtl Cube_1_5_5
illum 1
Ka 0.2 0.2 0.2
Kd 1.0 1.0 1.0
Ks 0.0 0.0 0.0
Ns 1.0
map_Kd Missile_AIM-120_D_[AMRAAM]_Cube_1_5_5.png
newmtl Cube_1_6_6
illum 1
Ka 0.2 0.2 0.2
Kd 1.0 1.0 1.0
Ks 0.0 0.0 0.0
Ns 1.0
Ni 1.0
map_Kd Missile_AIM-120_D_[AMRAAM]_Cube_1_6_6.png
newmtl Cylinder_1_1
illum 1
Ka 0.4 0.4 0.4
Kd 0.4 0.4 0.4
Ks 0.0 0.0 0.0
Ns 1.0
newmtl Cube_1_5_5_Cube_1_5_5_86
illum 1
Ka 0.2 0.2 0.2
Kd 0.2 0.2 0.2
Ks 0.0 0.0 0.0
Ns 1.0
newmtl Cube_1_6_6_Cube_1_6_6_87
illum 1
Ka 0.8 0.0 0.0
Kd 0.8 0.0 0.0
Ks 0.0 0.0 0.0
Ns 1.0
newmtl Cylinder_7_7_Cylinder_7_7_88
illum 1
Ka 0.8 0.4 0.0
Kd 0.8 0.4 0.0
Ks 0.0 0.0 0.0
Ns 1.0
newmtl Cylinder_8_8
illum 1
Ka 0.4 0.6 0.0
Kd 0.4 0.6 0.0
Ks 0.0 0.0 0.0
Ns 1.0

Binary file not shown.

Before

Width:  |  Height:  |  Size: 210 KiB

View File

@@ -1,3 +0,0 @@
based on:
https://free3d.com/de/3d-model/aim-120d-missile-51025.html
License: Free Personal Use Only

View File

@@ -1,3 +0,0 @@
based on:
https://free3d.com/3d-model/wwii-ship-german-type-ii-uboat-v2--700733.html
License: Free Personal Use Only

View File

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

View File

@@ -1,10 +0,0 @@
Personal-use only.
menu_music.ogg
https://pixabay.com/de/music/szenen-aufbauen-demolition-outline-science-fiction-trailer-music-191960/
pirates.ogg
https://pixabay.com/de/music/epische-klassik-pirates-163389/
win_the_game.gg
https://pixabay.com/de/users/enrico_dering-31760131/
defeat.ogg
https://pixabay.com/de/music/dramaszene-defeat-charles-michel-140604/

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; package pp.battleship.exporter;
@@ -41,7 +36,7 @@ public static void main(String[] args) {
*/ */
@Override @Override
public void simpleInitApp() { 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(); stop();
} }

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; package pp.battleship;
import pp.util.config.Config; 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; package pp.battleship;
import java.util.ResourceBundle; import java.util.ResourceBundle;

View File

@@ -1,100 +1,82 @@
package pp.battleship.game.client; package pp.battleship.game.client;
import pp.battleship.message.client.AnimationMessage; import pp.battleship.message.client.EndAnimationMessage;
import pp.battleship.message.server.EffectMessage; import pp.battleship.message.server.EffectMessage;
import pp.battleship.model.Battleship; import pp.battleship.message.server.SwitchToBattleState;
import pp.battleship.model.IntPoint; import pp.battleship.model.IntPoint;
import pp.battleship.model.Shell; import pp.battleship.model.Shell;
import pp.battleship.model.ShipMap; import pp.battleship.model.ShipMap;
import pp.battleship.notification.Music; import pp.battleship.notification.Music;
import pp.battleship.notification.Sound; import pp.battleship.notification.Sound;
import java.lang.System.Logger.Level;
/** /**
* Represents the state of the game during an animation sequence. * Represents the state in which the animation is played
* This state handles the progress and completion of the animation,
* updates the game state accordingly, and transitions to the next state.
*/ */
public class AnimationState extends ClientState { public class AnimationState extends ClientState {
/**
* Progress of the current animation, ranging from 0 to 1. private boolean myTurn;
*/
private float animationProgress = 0;
/** /**
* Duration of the animation in seconds. * Constructor for the AnimationState class
*/
private final static float ANIMATION_DURATION = 0.375f;
/**
* Speed of the shell in the animation.
*/
private final static float SHELL_SPEED = 0.3f;
/**
* The effect message received from the server.
*/
private final EffectMessage msg;
/**
* The shell involved in the animation.
*/
private final Shell shell;
/**
* Constructs an AnimationState with the specified game logic, effect message, and shell.
* *
* @param logic the game logic associated with this state * @param logic the client logic
* @param msg the effect message received from the server * @param turn a boolean containing if it's the client's turn
* @param shell the shell involved in the animation * @param position the position a Shell gets created
*/ */
public AnimationState(ClientGameLogic logic, EffectMessage msg, Shell shell) { public AnimationState(ClientGameLogic logic, boolean turn, IntPoint position) {
super(logic); super(logic);
this.msg = msg; logic.playMusic(Music.GAME_THEME);
this.shell = shell; myTurn = turn;
} if (myTurn) {
logic.getOpponentMap().add(new Shell(position));
/** }
* Ends the animation state and transitions to the next state:<br> else {
* - Plays the appropriate sound.<br> logic.getOwnMap().add(new Shell(position));
* - Updates the affected map.<br>
* - Adds destroyed ships to the opponent's map.<br>
* - Sends an `AnimationMessage` to the server.<br>
* - If the game is over, transitions to `GameOverState` and plays music.<br>
* - Otherwise, transitions to `BattleState`.
*/
public void endState() {
playSound(msg);
affectedMap(msg).add(msg.getShot());
affectedMap(msg).remove(shell);
if (destroyedOpponentShip(msg))
logic.getOpponentMap().add(msg.getDestroyedShip());
logic.send(new AnimationMessage());
if (msg.isGameOver()) {
for (Battleship ship : msg.getRemainingOpponentShips()) {
logic.getOpponentMap().add(ship);
}
logic.setState(new GameOverState(logic));
if (msg.isOwnShot())
logic.playMusic(Music.VICTORY_MUSIC);
else
logic.playMusic(Music.DEFEAT_MUSIC);
} else {
logic.setState(new BattleState(logic, msg.isMyTurn()));
} }
} }
/** /**
* Checks if the battle state should be shown. * Makes sure the client renders the correct view
* *
* @return true if the battle state should be shown, false otherwise * @return true
*/ */
@Override @Override
public boolean showBattle() { boolean showBattle() {
return true; 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. * Determines which map (own or opponent's) should be affected by the shot based on the message.
* *
@@ -111,7 +93,6 @@ private ShipMap affectedMap(EffectMessage msg) {
* @param msg the effect message received from the server * @param msg the effect message received from the server
* @return true if the shot destroyed an opponent's ship, false otherwise * @return true if the shot destroyed an opponent's ship, false otherwise
*/ */
private boolean destroyedOpponentShip(EffectMessage msg) { private boolean destroyedOpponentShip(EffectMessage msg) {
return msg.getDestroyedShip() != null && msg.isOwnShot(); return msg.getDestroyedShip() != null && msg.isOwnShot();
} }
@@ -130,30 +111,4 @@ else if (msg.getDestroyedShip() == null)
else else
logic.playSound(Sound.DESTROYED_SHIP); logic.playSound(Sound.DESTROYED_SHIP);
} }
/**
* Handles a click on the opponent's map.
*
* @param pos the position where the click occurred
*/
@Override
public void clickOpponentMap(IntPoint pos) {
if (!msg.isMyTurn())
logic.setInfoText("wait.its.not.your.turn");
}
/**
* Updates the state of the animation. This method increments the animationProgress value
* until it exceeds a threshold, at which point the state ends.
*
* @param delta the time elapsed since the last update, in seconds
*/
@Override
public void update(float delta) {
if (animationProgress > ANIMATION_DURATION) {
endState();
} else {
animationProgress += delta * SHELL_SPEED;
}
}
} }

View File

@@ -1,19 +1,17 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.game.client; package pp.battleship.game.client;
import pp.battleship.message.client.ShootMessage; import pp.battleship.message.client.ShootMessage;
import pp.battleship.message.server.EffectMessage; import pp.battleship.message.server.EffectMessage;
import pp.battleship.message.server.StartAnimationMessage;
import pp.battleship.model.IntPoint; import pp.battleship.model.IntPoint;
import pp.battleship.model.Shell;
import pp.battleship.model.ShipMap; import pp.battleship.model.ShipMap;
import pp.battleship.notification.Music;
import pp.battleship.notification.Sound; import pp.battleship.notification.Sound;
import java.lang.System.Logger.Level;
/** /**
* Represents the state of the client where players take turns to attack each other's ships. * Represents the state of the client where players take turns to attack each other's ships.
*/ */
@@ -28,13 +26,14 @@ class BattleState extends ClientState {
*/ */
public BattleState(ClientGameLogic logic, boolean myTurn) { public BattleState(ClientGameLogic logic, boolean myTurn) {
super(logic); super(logic);
logic.playMusic(Music.GAME_THEME);
this.myTurn = myTurn; this.myTurn = myTurn;
} }
/** /**
* Checks if the battle state should be shown. * Makes sure the client renders the correct view
* *
* @return true if the battle state should be shown, false otherwise * @return true
*/ */
@Override @Override
public boolean showBattle() { public boolean showBattle() {
@@ -42,7 +41,7 @@ public boolean showBattle() {
} }
/** /**
* Handles a click on the opponent's map. * Triggers a shoot event if it's client's turn
* *
* @param pos the position where the click occurred * @param pos the position where the click occurred
*/ */
@@ -55,31 +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 @Override
public void receivedEffect(EffectMessage msg) { public void receivedStartAnimation(StartAnimationMessage msg) {
ClientGameLogic.LOGGER.log(System.Logger.Level.INFO, "report effect: {0}", msg); //NON-NLS logic.setState(new AnimationState(logic, msg.isMyTurn(), msg.getPosition()));
// Update turn and info text logic.playSound(Sound.MISSILE_LAUNCH);
myTurn = msg.isMyTurn();
logic.setInfoText(msg.getInfoTextKey());
// Add the shell to the affected map
Shell shell = new Shell(msg.getShot());
affectedMap(msg).add(shell);
// Change state to AnimationState
logic.playSound(Sound.SHELL_FIRED);
logic.setState(new AnimationState(logic, msg, shell));
}
/**
* 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();
} }
} }

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; 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; package pp.battleship.game.client;
@@ -11,11 +6,21 @@
import pp.battleship.message.server.EffectMessage; import pp.battleship.message.server.EffectMessage;
import pp.battleship.message.server.GameDetails; import pp.battleship.message.server.GameDetails;
import pp.battleship.message.server.ServerInterpreter; import pp.battleship.message.server.ServerInterpreter;
import pp.battleship.message.server.StartAnimationMessage;
import pp.battleship.message.server.StartBattleMessage; import pp.battleship.message.server.StartBattleMessage;
import pp.battleship.message.server.SwitchToBattleState;
import pp.battleship.model.IntPoint; import pp.battleship.model.IntPoint;
import pp.battleship.model.ShipMap; import pp.battleship.model.ShipMap;
import pp.battleship.model.dto.ShipMapDTO; import pp.battleship.model.dto.ShipMapDTO;
import pp.battleship.notification.*; import pp.battleship.notification.ClientStateEvent;
import pp.battleship.notification.GameEvent;
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;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@@ -220,6 +225,26 @@ public void received(EffectMessage msg) {
state.receivedEffect(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. * Initializes the player's own map, opponent's map, and harbor based on the game details.
* *
@@ -252,15 +277,6 @@ public void playSound(Sound sound) {
notifyListeners(new SoundEvent(sound)); notifyListeners(new SoundEvent(sound));
} }
/**
* Emits an event to play the specified music.
*
* @param music the music to be played.
*/
public void playMusic(Music music) {
notifyListeners(new MusicEvent(music));
}
/** /**
* Loads a map from the specified file. * Loads a map from the specified file.
* *
@@ -307,7 +323,7 @@ public void saveMap(File file) throws IOException {
* *
* @param msg the message to be sent * @param msg the message to be sent
*/ */
void send(ClientMessage msg) { public void send(ClientMessage msg) {
if (clientSender == null) if (clientSender == null)
LOGGER.log(Level.ERROR, "trying to send {0} with sender==null", msg); //NON-NLS LOGGER.log(Level.ERROR, "trying to send {0} with sender==null", msg); //NON-NLS
else else
@@ -355,4 +371,13 @@ public void notifyListeners(GameEvent event) {
public void update(float delta) { public void update(float delta) {
state.update(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; 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; package pp.battleship.game.client;
import pp.battleship.message.server.EffectMessage; import pp.battleship.message.server.EffectMessage;
import pp.battleship.message.server.GameDetails; import pp.battleship.message.server.GameDetails;
import pp.battleship.message.server.StartAnimationMessage;
import pp.battleship.message.server.StartBattleMessage; import pp.battleship.message.server.StartBattleMessage;
import pp.battleship.message.server.SwitchToBattleState;
import pp.battleship.model.IntPoint; import pp.battleship.model.IntPoint;
import java.io.File; 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 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. * 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; package pp.battleship.game.client;
@@ -16,9 +11,11 @@
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.lang.System.Logger.Level; import java.lang.System.Logger.Level;
import java.util.Arrays;
import java.util.List; import java.util.List;
import static pp.battleship.Resources.lookup; 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.INVALID_PREVIEW;
import static pp.battleship.model.Battleship.Status.NORMAL; import static pp.battleship.model.Battleship.Status.NORMAL;
import static pp.battleship.model.Battleship.Status.VALID_PREVIEW; import static pp.battleship.model.Battleship.Status.VALID_PREVIEW;
@@ -57,7 +54,7 @@ public boolean showEditor() {
*/ */
@Override @Override
public void movePreview(IntPoint pos) { 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; if (preview == null || !ownMap().isValid(pos)) return;
preview.moveTo(pos); preview.moveTo(pos);
setPreviewStatus(preview); setPreviewStatus(preview);
@@ -72,7 +69,7 @@ public void movePreview(IntPoint pos) {
*/ */
@Override @Override
public void clickOwnMap(IntPoint pos) { 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 (!ownMap().isValid(pos)) return;
if (preview == null) if (preview == null)
modifyShip(pos); modifyShip(pos);
@@ -112,7 +109,8 @@ private void placeShip(IntPoint cursor) {
harbor().remove(selectedInHarbor); harbor().remove(selectedInHarbor);
preview = null; preview = null;
selectedInHarbor = null; selectedInHarbor = null;
} else { }
else {
preview.setStatus(INVALID_PREVIEW); preview.setStatus(INVALID_PREVIEW);
ownMap().add(preview); ownMap().add(preview);
} }
@@ -125,7 +123,7 @@ private void placeShip(IntPoint cursor) {
*/ */
@Override @Override
public void clickHarbor(IntPoint pos) { 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; if (!harbor().isValid(pos)) return;
final Battleship shipAtCursor = harbor().findShipAt(pos); final Battleship shipAtCursor = harbor().findShipAt(pos);
if (preview != null) { if (preview != null) {
@@ -135,7 +133,8 @@ public void clickHarbor(IntPoint pos) {
harbor().add(selectedInHarbor); harbor().add(selectedInHarbor);
preview = null; preview = null;
selectedInHarbor = null; selectedInHarbor = null;
} else if (shipAtCursor != null) { }
else if (shipAtCursor != null) {
selectedInHarbor = shipAtCursor; selectedInHarbor = shipAtCursor;
selectedInHarbor.setStatus(VALID_PREVIEW); selectedInHarbor.setStatus(VALID_PREVIEW);
harbor().remove(selectedInHarbor); harbor().remove(selectedInHarbor);
@@ -151,7 +150,7 @@ public void clickHarbor(IntPoint pos) {
*/ */
@Override @Override
public void rotateShip() { public void rotateShip() {
ClientGameLogic.LOGGER.log(Level.DEBUG, "pushed rotate"); //NON-NLS LOGGER.log(Level.DEBUG, "pushed rotate"); //NON-NLS
if (preview == null) return; if (preview == null) return;
preview.rotated(); preview.rotated();
ownMap().remove(preview); ownMap().remove(preview);
@@ -237,8 +236,9 @@ public void loadMap(File file) throws IOException {
final ShipMapDTO dto = ShipMapDTO.loadFrom(file); final ShipMapDTO dto = ShipMapDTO.loadFrom(file);
if (!dto.fits(logic.getDetails())) if (!dto.fits(logic.getDetails()))
throw new IOException(lookup("map.doesnt.fit")); throw new IOException(lookup("map.doesnt.fit"));
if (!validMap(dto)) else if (!checkMapToLoad(dto)) {
throw new IOException(lookup("map.invalid")); throw new IOException(lookup("ships.dont.fit.the.map"));
}
ownMap().clear(); ownMap().clear();
dto.getShips().forEach(ownMap()::add); dto.getShips().forEach(ownMap()::add);
harbor().clear(); harbor().clear();
@@ -246,6 +246,39 @@ public void loadMap(File file) throws IOException {
selectedInHarbor = null; 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. * Checks if the player's own map may be loaded from a file.
* *
@@ -265,70 +298,4 @@ public boolean mayLoadMap() {
public boolean maySaveMap() { public boolean maySaveMap() {
return harbor().getItems().isEmpty(); return harbor().getItems().isEmpty();
} }
/**
* Validates the given ShipMapDTO by checking if all ships are within bounds
* and do not overlap with each other.
*
* @param dto the ShipMapDTO to validate
* @return true if the map is valid, false otherwise
*/
private boolean validMap(ShipMapDTO dto) {
return inBounds(dto) && !overlaps(dto);
}
/**
* Checks if all ships in the given ShipMapDTO are within the bounds of the map.
*
* @param dto the ShipMapDTO to validate
* @return true if all ships are within bounds, false otherwise
*/
private boolean inBounds(ShipMapDTO dto) {
List<Battleship> ships = dto.getShips();
for (Battleship ship : ships) {
if (!isWithinBounds(ship, dto.getWidth(), dto.getHeight())) {
return false;
}
}
return true;
}
/**
* Checks if the given ship is within the bounds of the map.
*
* @param ship the Battleship to check
* @param width the width of the map
* @param height the height of the map
* @return true if the ship is within bounds, false otherwise
*/
private boolean isWithinBounds(Battleship ship, int width, int height) {
int minX = ship.getMinX();
int maxX = ship.getMaxX();
int minY = ship.getMinY();
int maxY = ship.getMaxY();
return minX >= 0 && minX < width &&
minY >= 0 && minY < height &&
maxX >= 0 && maxX < width &&
maxY >= 0 && maxY < height;
}
/**
* Checks if any ships in the given ShipMapDTO overlap with each other.
*
* @param dto the ShipMapDTO to validate
* @return true if any ships overlap, false otherwise
*/
private boolean overlaps(ShipMapDTO dto) {
List<Battleship> ships = dto.getShips();
for (int i = 0; i < ships.size(); i++) {
Battleship ship1 = ships.get(i);
for (int j = i + 1; j < ships.size(); j++) {
Battleship ship2 = ships.get(j);
if (ship1.collidesWith(ship2)) {
return true; // Collision detected
}
}
}
return false;
}
} }

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; package pp.battleship.game.client;
import pp.battleship.notification.Music;
/** /**
* Represents the state of the client when the game is over. * 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 * @param logic the client game logic
*/ */
GameOverState(ClientGameLogic logic) { GameOverState(ClientGameLogic logic, boolean loser) {
super(logic); 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; 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 @Override
public boolean maySaveMap() { public boolean maySaveMap() {
return false; 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; package pp.battleship.game.client;

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.game.client; package pp.battleship.game.client;
import pp.battleship.message.server.GameDetails; import pp.battleship.message.server.GameDetails;
import pp.battleship.message.server.StartBattleMessage; import pp.battleship.message.server.StartBattleMessage;
import pp.battleship.notification.Music;
import java.lang.System.Logger.Level; import java.lang.System.Logger.Level;
@@ -39,17 +33,15 @@ public void receivedStartBattle(StartBattleMessage msg) {
ClientGameLogic.LOGGER.log(Level.INFO, "start battle, {0} turn", msg.isMyTurn() ? "my" : "other's"); //NON-NLS ClientGameLogic.LOGGER.log(Level.INFO, "start battle, {0} turn", msg.isMyTurn() ? "my" : "other's"); //NON-NLS
logic.setInfoText(msg.getInfoTextKey()); logic.setInfoText(msg.getInfoTextKey());
logic.setState(new BattleState(logic, msg.isMyTurn())); logic.setState(new BattleState(logic, msg.isMyTurn()));
logic.playMusic(Music.GAME_MUSIC);
} }
/** /**
* Handles the GameDetails message received from the server. * Reverts the client back to the editor state if an invalid map is provided
* If the map is invalid, the editor state is set.
* *
* @param msg the GameDetails message received * @param details the game details including map size and ships
*/ */
@Override @Override
public void receivedGameDetails(GameDetails msg) { public void receivedGameDetails(GameDetails details) {
ClientGameLogic.LOGGER.log(Level.WARNING, "Invalid Map"); //NON-NLS ClientGameLogic.LOGGER.log(Level.WARNING, "Invalid Map"); //NON-NLS
logic.setInfoText("map.invalid"); logic.setInfoText("map.invalid");
logic.setState(new EditorState(logic)); 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; package pp.battleship.game.server;

View File

@@ -1,21 +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; package pp.battleship.game.server;
import pp.battleship.BattleshipConfig; import pp.battleship.BattleshipConfig;
import pp.battleship.message.client.AnimationMessage;
import pp.battleship.message.client.ClientInterpreter; import pp.battleship.message.client.ClientInterpreter;
import pp.battleship.message.client.EndAnimationMessage;
import pp.battleship.message.client.MapMessage; import pp.battleship.message.client.MapMessage;
import pp.battleship.message.client.ShootMessage; import pp.battleship.message.client.ShootMessage;
import pp.battleship.message.server.EffectMessage; import pp.battleship.message.server.EffectMessage;
import pp.battleship.message.server.GameDetails; import pp.battleship.message.server.GameDetails;
import pp.battleship.message.server.ServerMessage; import pp.battleship.message.server.ServerMessage;
import pp.battleship.message.server.StartAnimationMessage;
import pp.battleship.message.server.StartBattleMessage; import pp.battleship.message.server.StartBattleMessage;
import pp.battleship.message.server.SwitchToBattleState;
import pp.battleship.model.Battleship; import pp.battleship.model.Battleship;
import pp.battleship.model.IntPoint; import pp.battleship.model.IntPoint;
@@ -36,11 +31,13 @@ public class ServerGameLogic implements ClientInterpreter {
private final BattleshipConfig config; private final BattleshipConfig config;
private final List<Player> players = new ArrayList<>(2); private final List<Player> players = new ArrayList<>(2);
private final Set<Player> readyPlayers = new HashSet<>(); private final Set<Player> readyPlayers = new HashSet<>();
private final Set<Player> finishedAnimation = new HashSet<>();
private final ServerSender serverSender; private final ServerSender serverSender;
private Player activePlayer; private Player activePlayer;
private ServerState state = ServerState.WAIT; private ServerState state = ServerState.WAIT;
private boolean p1AnimationFinished = false;
private boolean p2AnimationFinished = false;
/** /**
* Constructs a ServerGameLogic with the specified sender and configuration. * Constructs a ServerGameLogic with the specified sender and configuration.
* *
@@ -144,77 +141,76 @@ public Player addPlayer(int id) {
public void received(MapMessage msg, int from) { public void received(MapMessage msg, int from) {
if (state != ServerState.SET_UP) if (state != ServerState.SET_UP)
LOGGER.log(Level.ERROR, "playerReady not allowed in {0}", state); //NON-NLS LOGGER.log(Level.ERROR, "playerReady not allowed in {0}", state); //NON-NLS
else if (validMap(msg)) 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()); playerReady(getPlayerById(from), msg.getShips());
else { }
LOGGER.log(Level.ERROR, "map does not fit game details"); //NON-NLS
send(getPlayerById(from), new GameDetails(config)); /**
* 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;
} }
} }
/** /**
* Validates the received map message by checking if all ships are within bounds * Returns true if the map contains correct ship placement and is of the correct size
* and do not overlap with each other.
* *
* @param msg the received MapMessage containing the ships * @param msg the received MapMessage of the player
* @return true if the map is valid, false otherwise * @param from the ID of the Player
* @return a boolean based on if the transmitted map ist correct
*/ */
private boolean validMap(MapMessage msg) {
List<Battleship> ships = msg.getShips();
return inBounds(ships) && !overlaps(ships);
}
/** private boolean checkMap(MapMessage msg, int from) {
* Checks if all ships in the given list are within the bounds of the map. int mapWidth = getPlayerById(from).getMap().getWidth();
* int mapHeight = getPlayerById(from).getMap().getHeight();
* @param ships the list of Battleships to validate
* @return true if all ships are within bounds, false otherwise if (mapHeight != 10 || mapWidth != 10)
*/ return false;
private boolean inBounds(List<Battleship> ships) {
for (Battleship ship : ships) { // check if ship is out of bounds
if (!isWithinBounds(ship)) { 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; return false;
} }
} }
return true;
}
/** // check if ships overlap
* Checks if the given ship is within the bounds of the map. List<Battleship> ships = msg.getShips();
* for (Battleship ship : ships) {
* @param ship the Battleship to check for (Battleship compareShip : ships) {
* @return true if the ship is within bounds, false otherwise if (!(ship == compareShip)) {
*/ if (ship.collidesWith(compareShip)) {
private boolean isWithinBounds(Battleship ship) { return false;
int minX = ship.getMinX(); }
int maxX = ship.getMaxX();
int minY = ship.getMinY();
int maxY = ship.getMaxY();
int width = config.getMapWidth();
int height = config.getMapHeight();
return minX >= 0 && minX < width &&
minY >= 0 && minY < height &&
maxX >= 0 && maxX < width &&
maxY >= 0 && maxY < height;
}
/**
* Checks if any ships in the given list overlap with each other.
*
* @param ships the list of Battleships to validate
* @return true if any ships overlap, false otherwise
*/
private boolean overlaps(List<Battleship> ships) {
for (int i = 0; i < ships.size(); i++) {
Battleship ship1 = ships.get(i);
for (int j = i + 1; j < ships.size(); j++) {
Battleship ship2 = ships.get(j);
if (ship1.collidesWith(ship2)) {
return true; // Collision detected
} }
} }
} }
return false; return true;
} }
/** /**
@@ -227,40 +223,11 @@ private boolean overlaps(List<Battleship> ships) {
public void received(ShootMessage msg, int from) { public void received(ShootMessage msg, int from) {
if (state != ServerState.BATTLE) if (state != ServerState.BATTLE)
LOGGER.log(Level.ERROR, "shoot not allowed in {0}", state); //NON-NLS LOGGER.log(Level.ERROR, "shoot not allowed in {0}", state); //NON-NLS
else {
setState(ServerState.ANIMATION);
shoot(getPlayerById(from), msg.getPosition());
}
}
/**
* Handles the reception of an {@link AnimationMessage}.
* Marks the player's animation as finished and transitions the game state if necessary.
*
* @param msg the received {@code AnimationMessage}
* @param from the ID of the sender client
*/
@Override
public void received(AnimationMessage msg, int from) {
if (state != ServerState.ANIMATION)
LOGGER.log(Level.ERROR, "animation not allowed in {0}", state); //NON-NLS
else else
finishedAnimation(getPlayerById(from)); for (Player player : players) {
} send(player, new StartAnimationMessage(msg.getPosition(), player == activePlayer));
setState(ServerState.WAIT_ANIMATION);
/** }
* Marks the player's animation as finished and transitions the game state if necessary.
*
* @param player the player whose animation is finished
*/
private void finishedAnimation(Player player) {
if (!finishedAnimation.add(player)) {
LOGGER.log(Level.ERROR, "{0}'s animation was already finished", player);
}
if (finishedAnimation.size() == 2) {
finishedAnimation.clear();
setState(ServerState.BATTLE);
}
} }
/** /**
@@ -284,36 +251,85 @@ void playerReady(Player player, List<Battleship> ships) {
} }
/** /**
* Handles the shooting action by the player. * Handles what Effect should be triggered based on the shot
* * @param player the player receiving the message
* @param p the player who shot * @param position the position the shot hit
* @param pos the position of the shot
*/ */
void shoot(Player p, IntPoint pos) { void shoot(Player player, IntPoint position) {
if (p != activePlayer) return; final Battleship selectedShip;
final Player otherPlayer = getOpponent(activePlayer); selectedShip = getSelectedShip(player, position);
final Battleship selectedShip = otherPlayer.getMap().findShipAt(pos);
if (selectedShip == null) { if (selectedShip == null) {
// shot missed shotMissed(player, position);
send(activePlayer, EffectMessage.miss(true, pos)); }
send(otherPlayer, EffectMessage.miss(false, pos)); else {
activePlayer = otherPlayer; shotHit(player, position, selectedShip);
} else { }
// shot hit a ship }
selectedShip.hit(pos);
if (otherPlayer.getMap().getRemainingShips().isEmpty()) { /**
// game is over * Returns the ship at a given position
send(activePlayer, EffectMessage.won(pos, selectedShip)); * @param player the player whose map will be checked for a ship
send(otherPlayer, EffectMessage.lost(pos, selectedShip, activePlayer.getMap().getRemainingShips())); * @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); 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)); else if (ship.isDestroyed()) {
send(otherPlayer, EffectMessage.shipDestroyed(false, pos, selectedShip)); if (player != activePlayer)
} else { send(player, EffectMessage.shipDestroyed(false, position, ship));
// ship has been hit, but it hasn't been destroyed else
send(activePlayer, EffectMessage.hit(true, pos)); send(activePlayer, EffectMessage.shipDestroyed(true, position, ship));
send(otherPlayer, EffectMessage.hit(false, pos)); }
else {
if (player != activePlayer) {
send(player, EffectMessage.hit(false, position));
}
else {
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; package pp.battleship.game.server;
import pp.battleship.message.server.ServerMessage; 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; package pp.battleship.game.server;
@@ -27,9 +22,9 @@ enum ServerState {
BATTLE, BATTLE,
/** /**
* The server is waiting for clients to finish their animations. * Waits for the Animation to finish
*/ */
ANIMATION, WAIT_ANIMATION,
/** /**
* The game has ended because all the ships of one player have been destroyed. * 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; package pp.battleship.game.singlemode;
import pp.battleship.BattleshipConfig; import pp.battleship.BattleshipConfig;

View File

@@ -1,13 +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.singlemode; package pp.battleship.game.singlemode;
import pp.battleship.message.client.*; 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; import pp.battleship.model.Battleship;
/** /**
@@ -61,16 +60,13 @@ public void received(MapMessage msg, int from) {
} }
/** /**
* Handles the reception of a {@link AnimationMessage}. * Creates a copy of the provided EndAnimation message
* Since a {@code AnimationMessage} does not need to be copied, it is directly assigned. * @param msg thr received EndAnimation message
*
* @param msg the received {@code AnimationMessage}
* @param from the identifier of the sender * @param from the identifier of the sender
*/ */
@Override @Override
public void received(AnimationMessage msg, int from) { public void received(EndAnimationMessage msg, int from) {
// copying is not necessary copiedMessage = new EndAnimationMessage(msg.getPosition());
copiedMessage = msg;
} }
/** /**

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; package pp.battleship.game.singlemode;
import pp.battleship.game.client.BattleshipClient; import pp.battleship.game.client.BattleshipClient;
import pp.battleship.game.client.ClientGameLogic; import pp.battleship.game.client.ClientGameLogic;
import pp.battleship.message.server.EffectMessage; import pp.battleship.message.server.*;
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 java.io.IOException; import java.io.IOException;
@@ -24,11 +13,14 @@
class InterpreterProxy implements ServerInterpreter { class InterpreterProxy implements ServerInterpreter {
private final BattleshipClient playerClient; private final BattleshipClient playerClient;
static final System.Logger LOGGER = System.getLogger(InterpreterProxy.class.getName());
/** /**
* Constructs an InterpreterProxy with the specified BattleshipClient. * Constructs an InterpreterProxy with the specified BattleshipClient.
* *
* @param playerClient the client to which the server messages are forwarded * @param playerClient the client to which the server messages are forwarded
*/ */
InterpreterProxy(BattleshipClient playerClient) { InterpreterProxy(BattleshipClient playerClient) {
this.playerClient = playerClient; this.playerClient = playerClient;
} }
@@ -82,6 +74,27 @@ public void received(EffectMessage msg) {
forward(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. * Forwards the specified ServerMessage to the client's game logic by enqueuing the message acceptance.
* *

View File

@@ -1,13 +1,10 @@
package pp.battleship.game.singlemode; package pp.battleship.game.singlemode;
import pp.battleship.game.client.BattleshipClient; import pp.battleship.game.client.BattleshipClient;
import pp.battleship.message.client.AnimationMessage; import pp.battleship.message.client.EndAnimationMessage;
import pp.battleship.message.client.MapMessage; import pp.battleship.message.client.MapMessage;
import pp.battleship.message.client.ShootMessage; import pp.battleship.message.client.ShootMessage;
import pp.battleship.message.server.EffectMessage; import pp.battleship.message.server.*;
import pp.battleship.message.server.GameDetails;
import pp.battleship.message.server.ServerInterpreter;
import pp.battleship.message.server.StartBattleMessage;
import pp.battleship.model.IntPoint; import pp.battleship.model.IntPoint;
import pp.battleship.model.dto.ShipMapDTO; import pp.battleship.model.dto.ShipMapDTO;
import pp.util.RandomPositionIterator; import pp.util.RandomPositionIterator;
@@ -114,16 +111,35 @@ public void received(StartBattleMessage msg) {
} }
/** /**
* Receives an effect message, logs it, and updates the turn status. * Receives an effect message, logs it.
* If it is RobotClient's turn to shoot, schedules a shot using shoot();
* *
* @param msg The effect message * @param msg The effect message
*/ */
@Override @Override
public void received(EffectMessage msg) { public void received(EffectMessage msg) {
LOGGER.log(Level.INFO, "Received EffectMessage: {0}", msg); //NON-NLS LOGGER.log(Level.INFO, "Received EffectMessage: {0}", msg); //NON-NLS
connection.sendRobotMessage(new AnimationMessage()); }
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(); 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; package pp.battleship.game.singlemode;

View File

@@ -1,27 +0,0 @@
package pp.battleship.message.client;
import com.jme3.network.serializing.Serializable;
/**
* A message indicating an animation event is finished in the game. (Client &#8594; Server)
*/
@Serializable
public class AnimationMessage extends ClientMessage {
/**
* Constructs a new AnimationMessage instance.
*/
public AnimationMessage() {
super();
}
/**
* 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);
}
}

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