17 Commits

Author SHA1 Message Date
Lukas Bauer
66798eb3e4 Improved code documentation 2024-10-11 15:22:20 +02:00
Lukas Bauer
edff9e1ad9 Improved code documentation and clarify comments for better readability and understanding 2024-10-11 15:06:09 +02:00
Lukas Bauer
bf16a18b71 Aufgabe 13
edited class BattleState in order to implement the 2D map feature
edited class GameSound to add the Missile launch sound
edited class MapViewSynchronizer in order to implement the 2D map feature
edited class ImpactEffectManager removed unused import
edited class SeaSynchronizer removed unused code
edited class Shell in order to implement the 2D map feature
edited class ShellControl in order to implement the 2D map feature
edited Sound added Missile launch enum
edited FloatMath to improve the animation for the 2D projectile
added missileLaunch.wav
2024-10-11 14:23:49 +02:00
Lukas Bauer
6100e95e76 Aufgabe 13
added class Shell for the feature Airstrike
added class ShellControl for the feature Airstrike
added new Model Bomb to implement the feature Airstrike
added README´S to the Models to show the free to use license
edited class ShipMap for the feature Airstrike
edited class ImpactEffectManager to improve the Fire and Water Particles
edited class MapViewSynchronizer for the feature Airstrike
edited class BattleState for the feature Airstrike
edited class BattleshipApp for the feature Airstrike
2024-10-09 21:10:31 +02:00
Lukas Bauer
1b7b842ca7 JavaDoc adjustments 2024-10-08 19:46:23 +02:00
Lukas Bauer
865b0fc33c Aufgabe 12
added class ImpactEffectManager to implement the funktionality with hit or miss particles
added map4 for particle testing purposes
edited class SeaSynchronizer in order to implement the particle feature
edited class ShipControl in order to implement the particle feature
edited settings.gradle in order to implement the particle feature
2024-10-08 19:43:07 +02:00
Lukas Bauer
5a9b0b1de0 fix Aufgabe 11
edited class NetworkDialog
to change the logic that the checkbox works now as intended
moved BattleshipServer and ReceivedMessage into own folders to separate server from client
2024-10-07 20:11:15 +02:00
Lukas Bauer
8650fa5b58 fix edited class EditorState
fix edited battleship.properties with the right Key to fix an exception
fix edited battleship_de.properties with the right Key to fix an exception
2024-10-05 13:09:05 +02:00
Lukas Bauer
113da79df6 fix edited class NetworkDialog changed Button to Checklist 2024-10-04 18:42:47 +02:00
Lukas Bauer
e41d21584a Aufgabe 11.
added class BattleshipServer, ReceivedMessage
to implement the feature that a client is able to start an server
edited NetworkDialog to implement the logic to start an server and overhauled the GUI to be appropriate for the new features
2024-10-04 18:33:13 +02:00
Lukas Bauer
5e773ca1ba Aufgabe 10.
added class BackgroundMusic
edited BattleshipApp, GameSound, Menu
implemented a Slider for the Gui in order to change the Volume
Quality of Life
implemented feature to Safe the Sound settings to keep them even after shutting down the game
implemented feature to mute Sounds/effects
implemented feature to mute Music
2024-10-03 19:11:53 +02:00
Lukas Bauer
b2b3bc23bf Aufgabe 10.
added class BackgroundMusic
edited BattleshipApp, GameSound, Menu
implemented a Slider for the Gui in order to change the Volume
Quality of Life
implemented feature to Safe the Sound settings to keep them even after shutting down the game
implemented feature to mute Sounds/effects
implemented feature to mute Music
2024-10-03 19:10:36 +02:00
Lukas Bauer
ce490fb877 Aufgabe 10.
added class BackgroundMusic
edited BattleshipApp, GameSound, Menu
implemented a Slider for the Gui in order to change the Volume
Quality of Life
implemented feature to Safe the Sound settings to keep them even after shutting down the game
implemented feature to mute Sounds/effects
implemented feature to mute Music
2024-10-03 19:07:27 +02:00
Lukas Bauer
ce5e908349 edited SeaSynchronizer , EditorState, ServerGameLogic
added JavaDocs for the new and adapted functions
added a new invalid map for testing purposes
fixed implemented the logic to check for invalid maps in the method received in ServerGameLogic
2024-10-03 13:28:41 +02:00
Lukas Bauer
07e922d01e Aufgabe 9.
edited SeaSynchronizer
added 3 Ship Models Small Ship, Medium Ship and Big Ship and tweaked the scaling of all Models
2024-10-02 20:23:05 +02:00
Lukas Bauer
42b442e937 Aufgabe 8.
edited class EditorState and ServerGameLogic
 to check for invalid maps in which ships overlap or are out of the map boundries for clientside and serverside
2024-10-02 18:24:27 +02:00
Lukas Bauer
93ade34282 Aufgabe 7.
fix: in class ShipMap
function remove
hierbei wurde nach dem entfernen eines Items dass Event ItemAddedEvent ausgelöst hierbei sollte aber logischerweiße dass Event ItemRemovedEvent ausgelöst werden.

fix: in class BattleState
function receivedEffect
hierbei wurde die eigene map für die Bedingung isGameOver verglichen wobei man für isGameOver die OpponentMap auf remainingShips untersuchen muss.
2024-10-02 00:31:40 +02:00
203 changed files with 806847 additions and 684316 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -1,18 +1,17 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="BattleshipApp (Mac)" type="Application" factoryName="Application"
singleton="false">
<option name="MAIN_CLASS_NAME" value="pp.battleship.client.BattleshipApp"/>
<module name="Projekte.battleship.client.main"/>
<option name="VM_PARAMETERS" value="-XstartOnFirstThread"/>
<option name="WORKING_DIRECTORY" value="$MODULE_WORKING_DIR$"/>
<extension name="coverage">
<pattern>
<option name="PATTERN" value="pp.battleship.client.*"/>
<option name="ENABLED" value="true"/>
</pattern>
</extension>
<method v="2">
<option name="Make" enabled="true"/>
</method>
</configuration>
<configuration default="false" name="BattleshipApp (Mac)" type="Application" factoryName="Application" singleton="false">
<option name="MAIN_CLASS_NAME" value="pp.battleship.client.BattleshipApp" />
<module name="Projekte.battleship.client.main" />
<option name="VM_PARAMETERS" value="-XstartOnFirstThread" />
<option name="WORKING_DIRECTORY" value="$MODULE_WORKING_DIR$" />
<extension name="coverage">
<pattern>
<option name="PATTERN" value="pp.battleship.client.server.*" />
<option name="ENABLED" value="true" />
</pattern>
</extension>
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
</component>

View File

@@ -1,18 +1,19 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="BattleshipApp" type="Application" factoryName="Application" singleton="false"
nameIsGenerated="true">
<option name="MAIN_CLASS_NAME" value="pp.battleship.client.BattleshipApp"/>
<module name="Projekte.battleship.client.main"/>
<option name="VM_PARAMETERS" value="-Djava.util.logging.config.file=logging.properties"/>
<option name="WORKING_DIRECTORY" value="$MODULE_WORKING_DIR$"/>
<configuration default="false" name="BattleshipApp" type="Application" factoryName="Application" singleton="false" nameIsGenerated="true">
<option name="ALTERNATIVE_JRE_PATH" value="temurin-20" />
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="true" />
<option name="MAIN_CLASS_NAME" value="pp.battleship.client.BattleshipApp" />
<module name="Gruppe-01" />
<option name="VM_PARAMETERS" value="-Djava.util.logging.config.file=logging.properties" />
<option name="WORKING_DIRECTORY" value="$MODULE_WORKING_DIR$" />
<extension name="coverage">
<pattern>
<option name="PATTERN" value="pp.battleship.client.*"/>
<option name="ENABLED" value="true"/>
<option name="PATTERN" value="pp.battleship.client.server.*" />
<option name="ENABLED" value="true" />
</pattern>
</extension>
<method v="2">
<option name="Make" enabled="true"/>
<option name="Make" enabled="true" />
</method>
</configuration>
</component>

View File

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

View File

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

View File

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

View File

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

View File

@@ -4,235 +4,92 @@
import com.jme3.audio.AudioData.DataType;
import com.jme3.audio.AudioNode;
import com.jme3.audio.AudioSource.Status;
import pp.battleship.notification.Music;
import pp.battleship.notification.MusicEvent;
import pp.battleship.notification.GameEventListener;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import java.util.prefs.Preferences;
/**
* Class to play Background music in game
*/
public class BackgroundMusic implements GameEventListener {
public class BackgroundMusic {
private static final String VOLUME_PREF = "volume";
private static final String MUSIC_ENABLED_PREF = "musicEnabled";
private final Preferences pref = Preferences.userNodeForPackage(BackgroundMusic.class);
static final Logger LOGGER = System.getLogger(BackgroundMusic.class.getName());
private Preferences prefs = Preferences.userNodeForPackage(BackgroundMusic.class);
private static final String MENU_MUSIC = "Sound/Music/menu/cinematictrailerelite.ogg";
private static final String GAME_MUSIC = "Sound/Music/game/Aluminum.ogg";
private static final String VICTORY_MUSIC = "Sound/Music/victory/victorymarchofvalor.ogg";
private static final String LOSE_MUSIC = "Sound/Music/lose/TouchofDream.ogg";
private final AudioNode menuMusic;
private final AudioNode gameMusic;
private final AudioNode victoryMusic;
private final AudioNode loseMusic;
private String lastPlayedMusic;
private final AudioNode backgroundMusic;
private boolean musicEnabled;
private float volume;
private Application app;
/**
* Constructor for BackgroundMusic class
*
* @param app The main Application
* Constuctor for the BackgroundMusic
* @param app for synchronising and saving data with the application
* @param musicFilePath the filepath for the BackgroundMusic
*/
public BackgroundMusic(Application app) {
this.volume = pref.getFloat(VOLUME_PREF, 1.0f);
this.musicEnabled = pref.getBoolean(MUSIC_ENABLED_PREF, true);
this.app = app;
public BackgroundMusic(Application app, String musicFilePath) {
this.volume = prefs.getFloat(VOLUME_PREF, 1.0f);
this.musicEnabled = prefs.getBoolean(MUSIC_ENABLED_PREF, true);
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();
backgroundMusic = new AudioNode(app.getAssetManager(), musicFilePath, DataType.Stream);
backgroundMusic.setLooping(true);
backgroundMusic.setPositional(false);
backgroundMusic.setVolume(1.0f);
if (musicEnabled) {
play(menuMusic);
play();
}
}
/**
* Creates an audio node for the music
*
* @param musicFilePath the file path to the music
* @return the created audio node
* Checks if the condition is met to play BackgroundMusic
*/
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();
public void play() {
if (musicEnabled && (backgroundMusic.getStatus() == Status.Stopped || backgroundMusic.getStatus() == Status.Paused)) {
backgroundMusic.play();
}
}
/**
* Pauses the music
*
* @param audioNode the audio node to be paused
* function to stop the BackgroundMusic
*/
public void pause(AudioNode audioNode) {
if (audioNode.getStatus() == Status.Playing) {
audioNode.pause();
public void stop() {
if (backgroundMusic.getStatus() == Status.Playing) {
backgroundMusic.stop();
}
}
/**
* Stops the music
*
* @param audioNode the audio node to be stopped
* function to toggle the Backgroundmusic also sets the volume to the previous session
*/
public void stop(AudioNode audioNode) {
if (audioNode.getStatus() == Status.Playing) {
audioNode.stop();
}
}
/**
* Controls which music should be played
*/
public void toggleMusic() {
public void toogleMusic() {
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;
}
play();
} else {
stop();
}
else {
pause(menuMusic);
pause(gameMusic);
pause(victoryMusic);
pause(loseMusic);
}
pref.putBoolean(MUSIC_ENABLED_PREF, musicEnabled);
prefs.putFloat(VOLUME_PREF, volume);
}
/**
* Changes the music to the specified music if it isn't already playing
*
* @param music the music to play
*/
public void changeMusic(Music music) {
if (music == Music.MENU_THEME && !lastPlayedMusic.equals(MENU_MUSIC)) {
LOGGER.log(Level.DEBUG, "Received Music change Event {0}", music.toString());
stop(gameMusic);
stop(victoryMusic);
stop(loseMusic);
play(menuMusic);
lastPlayedMusic = menuMusic.getName();
}
else if (music == Music.GAME_THEME && !lastPlayedMusic.equals(GAME_MUSIC)) {
LOGGER.log(Level.DEBUG, "Received Music change Event {0}", music.toString());
stop(menuMusic);
stop(loseMusic);
stop(victoryMusic);
play(gameMusic);
lastPlayedMusic = gameMusic.getName();
}
else if (music == Music.VICTORY_THEME && !lastPlayedMusic.equals(VICTORY_MUSIC)) {
LOGGER.log(Level.DEBUG, "Received Music change Event {0}", music.toString());
stop(menuMusic);
stop(gameMusic);
stop(loseMusic);
play(victoryMusic);
lastPlayedMusic = victoryMusic.getName();
}
else if (music == Music.LOSE_THEME && !lastPlayedMusic.equals(LOSE_MUSIC)) {
LOGGER.log(Level.DEBUG, "Received Music change Event {0}", music.toString());
stop(menuMusic);
stop(gameMusic);
stop(victoryMusic);
play(loseMusic);
lastPlayedMusic = loseMusic.getName();
}
}
/**
* Receives the different MusicEvents
*
* @param music the received Event
*/
@Override
public void receivedEvent(MusicEvent music) {
LOGGER.log(Level.DEBUG, "Received Music change Event {0}", music.toString());
switch (music.music()) {
case MENU_THEME:
changeMusic(Music.MENU_THEME);
break;
case GAME_THEME:
changeMusic(Music.GAME_THEME);
break;
case VICTORY_THEME:
changeMusic(Music.VICTORY_THEME);
break;
case LOSE_THEME:
changeMusic(Music.LOSE_THEME);
break;
}
}
/**
* Set the volume for the music
*
* @param volume float to transfer the new volume
* Setter for the Volume also safes the volume from the previous session
* @param volume variable for the volume of the BackgroundMusic
*/
public void setVolume(float volume) {
this.volume = volume;
menuMusic.setVolume(volume);
gameMusic.setVolume(volume);
victoryMusic.setVolume(volume);
loseMusic.setVolume(volume);
pref.putFloat(VOLUME_PREF, volume);
backgroundMusic.setVolume(volume);
prefs.putFloat(VOLUME_PREF, volume);
}
/**
* Returns the volume
*
* @return the current volume as a float
* Getter for Volume
* @return a float value of the volume
*/
public float getVolume() {
return volume;
}
/**
* Returns if music should be played or not
*
* @return boolean value in music should be played
* Getter for musicEnabled
* @return if the music is enabled return true, false otherwise
*/
public boolean isMusicEnabled() {
return musicEnabled;
}
}
}

View File

@@ -1,3 +1,10 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.client;
import com.jme3.app.DebugKeysAppState;
@@ -114,9 +121,8 @@ public class BattleshipApp extends SimpleApplication implements BattleshipClient
* Listener for handling actions triggered by the Escape key.
*/
private final ActionListener escapeListener = (name, isPressed, tpf) -> escape(isPressed);
/**
* Object handling the background music
*
*/
private BackgroundMusic backgroundMusic;
@@ -139,6 +145,7 @@ public class BattleshipApp extends SimpleApplication implements BattleshipClient
*/
public static void main(String[] args) {
new BattleshipApp().start();
}
/**
@@ -223,8 +230,7 @@ public void simpleInitApp() {
setupStates();
setupGui();
serverConnection.connect();
backgroundMusic = new BackgroundMusic(this);
logic.addListener(backgroundMusic);
backgroundMusic = new BackgroundMusic(this, "Sound/Effects/BackgroundMusic/boss_battle_#2_metal_opening.wav");
}
/**
@@ -315,10 +321,6 @@ public Draw getDraw() {
return draw;
}
public BackgroundMusic getBackgroundMusic() {
return backgroundMusic;
}
/**
* Handles a request to close the application.
* If the request is initiated by pressing ESC, this parameter is true.
@@ -430,4 +432,12 @@ void errorDialog(String errorMessage) {
.build()
.open();
}
/**
* Getter for the BackgroundMusic
* @return the BackgroundMusic
*/
public BackgroundMusic getBackgroundMusic(){
return backgroundMusic;
}
}

View File

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

View File

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

View File

@@ -1,3 +1,10 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.client;
import com.jme3.app.Application;
@@ -8,7 +15,6 @@
import com.jme3.audio.AudioData;
import com.jme3.audio.AudioNode;
import pp.battleship.notification.GameEventListener;
import pp.battleship.notification.Sound;
import pp.battleship.notification.SoundEvent;
import java.lang.System.Logger;
@@ -21,7 +27,7 @@
* An application state that plays sounds.
*/
public class GameSound extends AbstractAppState implements GameEventListener {
static final Logger LOGGER = System.getLogger(GameSound.class.getName());
private static final Logger LOGGER = System.getLogger(GameSound.class.getName());
private static final Preferences PREFERENCES = getPreferences(GameSound.class);
private static final String ENABLED_PREF = "enabled"; //NON-NLS
@@ -39,13 +45,6 @@ public static boolean enabledInPreferences() {
return PREFERENCES.getBoolean(ENABLED_PREF, true);
}
/**
* Toggles the game sound on or off.
*/
public void toggleSound() {
setEnabled(!isEnabled());
}
/**
* Sets the enabled state of this AppState.
* Overrides {@link com.jme3.app.state.AbstractAppState#setEnabled(boolean)}
@@ -73,7 +72,7 @@ public void initialize(AppStateManager stateManager, Application app) {
shipDestroyedSound = loadSound(app, "Sound/Effects/sunken.wav"); //NON-NLS
splashSound = loadSound(app, "Sound/Effects/splash.wav"); //NON-NLS
explosionSound = loadSound(app, "Sound/Effects/explosion.wav"); //NON-NLS
missileLaunch = loadSound(app, "Sound/Effects/missilefiring.wav"); //NON-NLS
missileLaunch = loadSound(app, "Sound/Effects/missileLaunch.wav");
}
/**
@@ -89,19 +88,17 @@ private AudioNode loadSound(Application app, String name) {
sound.setLooping(false);
sound.setPositional(false);
return sound;
}
catch (AssetLoadException | AssetNotFoundException ex) {
} catch (AssetLoadException | AssetNotFoundException ex) {
LOGGER.log(Level.ERROR, ex.getMessage(), ex);
}
return null;
}
/**
* Plays the splash sound effect.
* Plays the missile launch sound effect.
*/
public void missileLaunch() {
if (isEnabled() && missileLaunch != null)
missileLaunch.playInstance();
missileLaunch.playInstance();
}
/**
@@ -129,9 +126,8 @@ public void shipDestroyed() {
}
/**
* Plays sound according to the received SoundEvent
*
* @param event the received SoundEvent
* Checks the according case for the soundeffect
* @param event the received event
*/
@Override
public void receivedEvent(SoundEvent event) {

View File

@@ -1,15 +1,23 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.client;
import com.simsilica.lemur.Button;
import com.simsilica.lemur.Checkbox;
import com.simsilica.lemur.DefaultRangedValueModel;
import com.simsilica.lemur.Label;
import com.simsilica.lemur.Slider;
import com.simsilica.lemur.core.VersionedReference;
import com.simsilica.lemur.style.ElementId;
import pp.dialog.Dialog;
import pp.dialog.StateCheckboxModel;
import pp.dialog.TextInputDialog;
import com.simsilica.lemur.DefaultRangedValueModel;
import com.simsilica.lemur.Slider;
import com.simsilica.lemur.core.VersionedReference;
import java.io.File;
import java.io.IOException;
@@ -42,15 +50,16 @@ public Menu(BattleshipApp app) {
addChild(new Label(lookup("battleship.name"), new ElementId("header"))); //NON-NLS
addChild(new Checkbox(lookup("menu.sound-enabled"),
new StateCheckboxModel(app, GameSound.class)));
Checkbox musicToggle = new Checkbox(lookup("menu.music.toggle"));
musicToggle.setChecked(app.getBackgroundMusic().isMusicEnabled());
musicToggle.addClickCommands(s -> toggleMusic());
addChild(musicToggle);
addChild(new Label(lookup("menu.music.volume"), new ElementId("slider_label")));
Slider volumeSlider = new Slider();
volumeSlider.setModel(new DefaultRangedValueModel(0.00, 1.00, app.getBackgroundMusic().getVolume()));
volumeSlider.setDelta(0.05);
volumeSlider.setModel(new DefaultRangedValueModel(0.0 , 2.0, app.getBackgroundMusic().getVolume()));
volumeSlider.setDelta(0.1);
addChild(volumeSlider);
volumeRef = volumeSlider.getModel().createReference();
@@ -63,37 +72,34 @@ public Menu(BattleshipApp app) {
.addClickCommands(s -> ifTopDialog(this::close));
addChild(new Button(lookup("menu.quit")))
.addClickCommands(s -> ifTopDialog(app::closeApp));
update();
}
/**
* Updates the volume when the slider is moved
*
* @param tpf time per frame
* Updates the volume if there is a change and adjusts it accordingly.
* @param tmp unused time parameter
*/
@Override
public void update(float tpf) {
if (volumeRef.update()) {
public void update(float tmp){
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
* Adjusts the background music volume to the specified value.
* @param newVolume the new volume level
*/
private void adjustVolume(double volume) {
app.getBackgroundMusic().setVolume((float) volume);
private void adjustVolume(double newVolume) {
app.getBackgroundMusic().setVolume((float) newVolume);
}
/**
* Toggles the background music on and off
* Toggles the background music on or off.
*/
private void toggleMusic() {
app.getBackgroundMusic().toggleMusic();
private void toggleMusic(){
app.getBackgroundMusic().toogleMusic();
}
/**

View File

@@ -1,14 +1,18 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.client;
import com.simsilica.lemur.Checkbox;
import com.simsilica.lemur.Container;
import com.simsilica.lemur.Label;
import com.simsilica.lemur.TextField;
import com.simsilica.lemur.*;
import com.simsilica.lemur.component.SpringGridLayout;
import pp.battleship.client.server.BattleshipServer;
import pp.dialog.Dialog;
import pp.dialog.DialogBuilder;
import pp.dialog.SimpleDialog;
import server.BattleshipServer;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
@@ -32,7 +36,10 @@ class NetworkDialog extends SimpleDialog {
private int portNumber;
private Future<Object> connectionFuture;
private Dialog progressDialog;
private boolean hostServer = false;
private BattleshipServer battleshipServer;
private boolean GUI = true;
private Container menu;
private boolean serverToggle = false;
/**
* Constructs a new NetworkDialog.
@@ -46,52 +53,127 @@ class NetworkDialog extends SimpleDialog {
host.setPreferredWidth(400f);
port.setSingleLine(true);
Checkbox hostServer = new Checkbox(lookup("start.own.server"));
hostServer.setChecked(false);
hostServer.addClickCommands(s -> toggleOwnServer());
final BattleshipApp app = network.getApp();
final Container input = new Container(new SpringGridLayout());
input.addChild(new Label(lookup("host.name") + ": "));
input.addChild(host, 1);
input.addChild(new Label(lookup("port.number") + ": "));
input.addChild(port, 1);
input.addChild(hostServer);
DialogBuilder.simple(app.getDialogManager())
.setTitle(lookup("server.dialog"))
.setExtension(d -> d.addChild(input))
.setOkButton(lookup("button.connect"), d -> connect())
.setNoButton(lookup("button.cancel"), app::closeApp)
.setOkClose(false)
.setNoClose(false)
.build(this);
this.menu = new Container();
menu();
addChild(menu);
}
/**
* Handles the action for establishing the connection to a server.
* Main Menu creation
*/
private void menu() {
Button connectGame = new Button("Multiplayer");
connectGame.addClickCommands(source -> serverConnectGUI());
Checkbox serverHost = new Checkbox("Host own Game");
serverHost.addClickCommands(source -> toggleServer());
menu.addChild(serverHost);
menu.addChild(connectGame);
}
/**
* Logic for the ServerGUI
*/
private void serverConnectGUI() {
LOGGER.log(Level.INFO, "Hosting Server...");
if (GUI) {
host.setSingleLine(true);
host.setPreferredWidth(400f);
port.setSingleLine(true);
final BattleshipApp app = network.getApp();
final Container input = new Container(new SpringGridLayout());
input.addChild(new Label(lookup("host.name") + ": "));
input.addChild(host, 1);
input.addChild(new Label(lookup("port.number") + ": "));
input.addChild(port, 1);
DialogBuilder.simple(app.getDialogManager())
.setTitle(lookup("server.dialog"))
.setExtension(d -> d.addChild(input))
.setOkButton(lookup("button.connect"), d -> connect())
.setOkClose(false)
.build(this);
GUI = false;
}
}
/**
* Connect to server if serverToggle is false hosts otherwise
*/
private void connect(){
if (serverToggle) {
hostServer();
} else {
connectServer();
}
}
/**
* Handles the action for the connect button in the connection dialog.
* Tries to parse the port number and initiate connection to the server.
*/
private void connectToServer() {
private void connectServer() {
LOGGER.log(Level.INFO, "connect to host={0}, port={1}", host, port); //NON-NLS
try {
hostname = host.getText().trim().isEmpty() ? LOCALHOST : host.getText();
portNumber = Integer.parseInt(port.getText());
openProgressDialog();
connectionFuture = network.getApp().getExecutor().submit(this::initNetwork);
}
catch (NumberFormatException e) {
} catch (NumberFormatException e) {
network.getApp().errorDialog(lookup("port.must.be.integer"));
}
}
/**
* Checks if the Server is running or starts the Server and handles Exceptions *
*/
private void hostServer() {
if (battleshipServer == null) {
startServer(); // Starts the server in a new thread
try {
Thread.sleep(1000); // Wait for the server to start
} catch (InterruptedException e) {
LOGGER.log(Level.WARNING, e.getMessage(), e);
}
}
// Proceed with connecting to the server
connectServer();
}
/**
* Toggle Method for Boolean
*/
private void toggleServer(){
serverToggle = !serverToggle;
}
/**
* Allows Client to Start a Server in a new Thread
*/
private void startServer() {
new Thread(() -> {
try {
// Initialize and run the server
battleshipServer = new BattleshipServer();
battleshipServer.run(Integer.parseInt(port.getText()));
} catch (Exception e) {
LOGGER.log(Level.ERROR, e);
}
}).start();
}
/**
* Creates a dialog indicating that the connection is in progress.
*/
private void openProgressDialog() {
progressDialog = DialogBuilder.simple(network.getApp().getDialogManager())
.setText(lookup("label.connecting"))
.build();
.setText(lookup("label.connecting"))
.build();
progressDialog.open();
}
@@ -104,8 +186,7 @@ private Object initNetwork() {
try {
network.initNetwork(hostname, portNumber);
return null;
}
catch (Exception e) {
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@@ -120,11 +201,9 @@ public void update(float delta) {
try {
connectionFuture.get();
success();
}
catch (ExecutionException e) {
} catch (ExecutionException e) {
failure(e.getCause());
}
catch (InterruptedException e) {
} catch (InterruptedException e) {
LOGGER.log(Level.WARNING, "Interrupted!", e); //NON-NLS
Thread.currentThread().interrupt();
}
@@ -151,46 +230,4 @@ private void failure(Throwable e) {
network.getApp().errorDialog(lookup("server.connection.failed"));
network.getApp().setInfoText(e.getLocalizedMessage());
}
/**
* Handles the action for the connect-button.
* If hostServer-Checkbox is active, starts a new Server on the clients machine, else tries to connect to existing server
*/
private void connect() {
if (hostServer) {
startServer();
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
LOGGER.log(Level.WARNING, e.getMessage(), e);
}
connectToServer();
}
else {
connectToServer();
}
}
/**
* Starts a server on the clients machine
*/
private void startServer() {
new Thread(() -> {
try {
BattleshipServer battleshipServer = new BattleshipServer(Integer.parseInt(port.getText()));
battleshipServer.run();
}
catch (Exception e) {
LOGGER.log(Level.ERROR, e);
}
}).start();
}
/**
* Handles the action for the hostServer-Checkbox
*/
private void toggleOwnServer() {
hostServer = !hostServer;
}
}

View File

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

View File

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

View File

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

View File

@@ -1,181 +0,0 @@
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

@@ -0,0 +1,155 @@
package pp.battleship.client.gui;
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.client.BattleshipApp;
import pp.battleship.model.Shot;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
/**
* Manages the visual effects for impact events such as hits and misses.
*/
public class ImpactEffectManager {
private final AssetManager assetManager;
private static final Logger LOGGER = System.getLogger(ImpactEffectManager.class.getName());
private Material particleMaterial;
private BattleshipApp app;
/**
* Constructor to initialize the asset manager via the main application.
*
* @param app The main application instance.
*/
public ImpactEffectManager(BattleshipApp app) {
this.app = app;
this.assetManager = app.getAssetManager();
this.particleMaterial = new Material(assetManager, "Common/MatDefs/Misc/Particle.j3md");
}
/**
* Generates a visual effect for a hit at the specified position.
*
* @param battleshipNode The node where the effect should be attached.
* @param shot The details of the shot where the hit occurred.
*/
public void triggerHitEffect(Node battleshipNode, Shot shot) {
ParticleEmitter hitEffect = createParticleEmitter("HitEffect", 50, ColorRGBA.Orange, ColorRGBA.Red, 0.45f, 0.1f, 1f, 2f);
hitEffect.setLocalTranslation(shot.getY() + 0.5f, 0, shot.getX() + 0.5f);
LOGGER.log(Level.DEBUG, "Hit effect created at position: {0}", hitEffect.getLocalTranslation().toString());
// hitEffect.emitAllParticles();
hitEffect.addControl(new EffectCleanupControl(hitEffect));
app.getRootNode().attachChild(hitEffect);
}
/**
* Creates a visual effect for a missed shot at the specified location.
*
* @param shot The details of the missed shot.
* @return The particle emitter representing the miss effect.
*/
public ParticleEmitter triggerMissEffect(Shot shot) {
ParticleEmitter missEffect = createParticleEmitter("MissEffect", 50, ColorRGBA.Blue, ColorRGBA.Cyan, 0.3f, 0.05f, 0.5f, 1.5f);
missEffect.setLocalTranslation(shot.getY() + 0.5f, 0, shot.getX() + 0.5f);
missEffect.addControl(new EffectCleanupControl(missEffect));
return missEffect;
}
/**
* Helper method to create a particle emitter with predefined parameters.
*
* @param name The name of the particle emitter.
* @param count The number of particles to emit.
* @param startColor The initial color of the particles.
* @param endColor The final color of the particles.
* @param startSize The initial size of the particles.
* @param endSize The final size of the particles.
* @param lowLife The minimum lifetime of the particles.
* @param highLife The maximum lifetime of the particles.
* @return The configured ParticleEmitter instance.
*/
private ParticleEmitter createParticleEmitter(String name, int count, ColorRGBA startColor, ColorRGBA endColor, float startSize, float endSize, float lowLife, float highLife) {
ParticleEmitter emitter = new ParticleEmitter(name, Type.Triangle, count);
emitter.setNumParticles(0);
emitter.setMaterial(particleMaterial);
emitter.setImagesX(2);
emitter.setImagesY(2);
emitter.setStartColor(startColor);
emitter.setEndColor(endColor);
emitter.getParticleInfluencer().setInitialVelocity(new Vector3f(0, 1, 0));
emitter.setStartSize(startSize);
emitter.setEndSize(endSize);
emitter.setGravity(0, -0.5f, 0);
emitter.setLowLife(lowLife);
emitter.setHighLife(highLife);
return emitter;
}
/**
* Custom control class to handle the cleanup of particle effects once they are no longer visible.
*/
private static class EffectCleanupControl extends AbstractControl {
private final ParticleEmitter emitter;
private float currentTime = 0;
private final float duration = 3.5f;
/**
* Constructor for managing cleanup of a standalone particle emitter.
*
* @param emitter The particle emitter to manage.
*/
public EffectCleanupControl(ParticleEmitter emitter) {
this.emitter = emitter;
}
/**
* Removes the emitter when all particles are no longer visible.
*
* @param tpf Time per frame.
*/
@Override
protected void controlUpdate(float tpf) {
currentTime += tpf;
if (currentTime <= duration) {
}
if (currentTime >= 1f && currentTime <= 1.1) {
//Start
emitter.setNumParticles(50);
emitter.setParticlesPerSec(50);
}
if (currentTime >= duration){
emitter.setParticlesPerSec(0);
}
if (currentTime >= duration+1f) {
//Ende
spatial.removeFromParent();
emitter.emitAllParticles();
}
}
/**
* No custom rendering needed; particle behavior is handled in controlUpdate.
* @param rm handles rendering, and ViewPort
* @param vp defines the view where the scene is displayed.
*/
@Override
protected void controlRender(com.jme3.renderer.RenderManager rm, com.jme3.renderer.ViewPort vp) {
// No rendering-specific behavior needed for this control.
}
}
}

View File

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

View File

@@ -1,4 +1,9 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.client.gui;
@@ -7,13 +12,10 @@
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import pp.battleship.model.Battleship;
import pp.battleship.model.IntPoint;
import pp.battleship.model.Shell;
import pp.battleship.model.Shot;
import pp.util.Position;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
/**
* Synchronizes the visual representation of the ship map with the game model.
@@ -26,9 +28,8 @@ class MapViewSynchronizer extends ShipMapSynchronizer {
private static final float SHOT_DEPTH = -2f;
private static final float SHIP_DEPTH = 0f;
private static final float INDENT = 4f;
private static final float MISSILE_DEPTH = 6f;
private static final float MISSILE_SIZE = 0.8f;
private static final float MISSILE_CENTERED_IN_MAP_GRID = 0.0625f;
private static final float SHELL_DEPTH = 8f;
// Colors used for different visual elements
private static final ColorRGBA HIT_COLOR = ColorRGBA.Red;
@@ -40,8 +41,6 @@ class MapViewSynchronizer extends ShipMapSynchronizer {
// The MapView associated with this synchronizer
private final MapView view;
static final Logger LOGGER = System.getLogger(MapViewSynchronizer.class.getName());
/**
* Constructs a new MapViewSynchronizer for the given MapView.
* Initializes the synchronizer and adds existing elements from the model to the view.
@@ -63,14 +62,16 @@ public MapViewSynchronizer(MapView view) {
*/
@Override
public Spatial visit(Shot shot) {
LOGGER.log(Level.DEBUG, "visiting" + shot);
// Convert the shot's model coordinates to view coordinates
final Position p1 = view.modelToView(shot.getX(), shot.getY());
final Position p2 = view.modelToView(shot.getX() + 1, shot.getY() + 1);
final ColorRGBA color = shot.isHit() ? HIT_COLOR : MISS_COLOR;
// Create and return a rectangle representing the shot
return view.getApp().getDraw().makeRectangle(p1.getX(), p1.getY(), SHOT_DEPTH, p2.getX() - p1.getX(), p2.getY() - p1.getY(), color);
return view.getApp().getDraw().makeRectangle(p1.getX(), p1.getY(),
SHOT_DEPTH,
p2.getX() - p1.getX(), p2.getY() - p1.getY(),
color);
}
/**
@@ -113,29 +114,21 @@ public Spatial visit(Battleship ship) {
}
/**
* Creates a visual representation on the map
*
* @param shell the Shell element to visit
* @return the node the visual representation gets attached to.
* Creates a visual representation (Spatial) for the given shell, attaching a control for its behavior.
* @param shell the shell to visit and visualize
* @return the constructed shell node (Spatial)
*/
@Override
public Spatial visit(Shell shell) {
LOGGER.log(Logger.Level.DEBUG, "Visiting {0}", shell);
final Node missileNode = new Node("missile");
final Position p1 = view.modelToView(shell.getX(), shell.getY());
final Position p2 = view.modelToView(shell.getX() + MISSILE_SIZE, shell.getY() + MISSILE_SIZE);
final Node shellNode = new Node("shell");
final Position startPosition = view.modelToView(shell.getCurrentPosition().x,shell.getCurrentPosition().z);
final float x1 = p1.getX() + INDENT;
final float y1 = p1.getY() + INDENT;
final float x2 = p2.getX() - INDENT;
final float y2 = p2.getY() - INDENT;
shellNode.attachChild(view.getApp().getDraw().makeRectangle(startPosition.getX(),startPosition.getY(), SHELL_DEPTH, 30, 30, ColorRGBA.Black));
final Position startPosition = view.modelToView(MISSILE_CENTERED_IN_MAP_GRID, MISSILE_CENTERED_IN_MAP_GRID);
shellNode.addControl(new ShellControl(shell, this.view, shell.getLogic()));
return shellNode;
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;
}
/**
@@ -149,7 +142,6 @@ public Spatial visit(Shell shell) {
* @return a Geometry representing the line
*/
private Geometry shipLine(float x1, float y1, float x2, float y2, ColorRGBA color) {
LOGGER.log(Logger.Level.DEBUG, "created Ship line");
return view.getApp().getDraw().makeFatLine(x1, y1, x2, y2, SHIP_DEPTH, color, SHIP_LINE_WIDTH);
}
}

View File

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

View File

@@ -1,12 +1,15 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.client.gui;
import com.jme3.material.Material;
import com.jme3.material.RenderState;
import com.jme3.material.RenderState.BlendMode;
import com.jme3.math.ColorRGBA;
import com.jme3.renderer.queue.RenderQueue;
import com.jme3.renderer.queue.RenderQueue.ShadowMode;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
@@ -14,11 +17,7 @@
import com.jme3.scene.shape.Box;
import com.jme3.scene.shape.Cylinder;
import pp.battleship.client.BattleshipApp;
import pp.battleship.model.Battleship;
import pp.battleship.model.Shell;
import pp.battleship.model.Rotation;
import pp.battleship.model.ShipMap;
import pp.battleship.model.Shot;
import pp.battleship.model.*;
import static java.util.Objects.requireNonNull;
import static pp.util.FloatMath.HALF_PI;
@@ -32,24 +31,21 @@
*/
class SeaSynchronizer extends ShipMapSynchronizer {
private static final String UNSHADED = "Common/MatDefs/Misc/Unshaded.j3md"; //NON-NLS
private static final String KING_GEORGE_V_MODEL = "Models/KingGeorgeV/KingGeorgeV.j3o";
private static final String UBOAT_MODEL = "Models/UBOAT/14084_WWII_Ship_German_Type_II_U-boat_v2_L1.obj";
private static final String PATROL_BOAT_MODEL = "Models/PATROL_BOAT/12219_boat_v2_L2.obj";
private static final String MODERN_BATTLESHIP_MODEL = "Models/BATTLESHIP/10619_Battleship.obj";
private static final String MODERN_BATTLESHIP_TEXTURES = "Models/BATTLESHIP/BattleshipC.jpg";
private static final String MISSILE_MODEL = "Models/Missile/AIM120D.obj";
private static final String MISSILE_TEXTURE = "Models/Missile/texture.png";
private static final String KING_GEORGE_V_MODEL = "Models/KingGeorgeV/KingGeorgeV.j3o";//NON-NLS
private static final String DESTROYER = "Models/Destroyer/Destroyer.j3o";
private static final String FERRY = "Models/Ferry/13922_Staten_Island_Ferry_V1_l1.obj";
private static final String SMALL = "Models/Small/10634_SpeedBoat_v01_LOD3.obj";
private static final String BOMB = "Models/Bomb/BombGBU.j3o";
private static final String COLOR = "Color"; //NON-NLS
private static final String SHIP = "ship"; //NON-NLS
private static final String SHOT = "shot"; //NON-NLS
private static final String MISSILE = "missile"; //NON-NLS
private static final ColorRGBA BOX_COLOR = ColorRGBA.Gray;
private static final ColorRGBA SPLASH_COLOR = new ColorRGBA(0f, 0f, 1f, 0.4f);
private static final ColorRGBA HIT_COLOR = new ColorRGBA(1f, 0f, 0f, 0.4f);
private final HitEffectHandler hitEffectHandler;
private final ShipMap map;
private final BattleshipApp app;
private ImpactEffectManager effectHandler;
/**
* Constructs a {@code SeaSynchronizer} object with the specified application, root node, and ship map.
@@ -62,7 +58,7 @@ public SeaSynchronizer(BattleshipApp app, Node root, ShipMap map) {
super(app.getGameLogic().getOwnMap(), root);
this.app = app;
this.map = map;
hitEffectHandler = new HitEffectHandler(app);
effectHandler = new ImpactEffectManager(app);
addExisting();
}
@@ -76,7 +72,7 @@ public SeaSynchronizer(BattleshipApp app, Node root, ShipMap map) {
*/
@Override
public Spatial visit(Shot shot) {
return shot.isHit() ? handleHit(shot) : hitEffectHandler.missEffect(shot);
return shot.isHit() ? handleHit(shot) : effectHandler.triggerMissEffect(shot);
}
/**
@@ -91,7 +87,8 @@ private Spatial handleHit(Shot shot) {
final Battleship ship = requireNonNull(map.findShipAt(shot), "Missing ship");
final Node shipNode = requireNonNull((Node) getSpatial(ship), "Missing ship node");
hitEffectHandler.hitEffect(shipNode, shot);
System.out.println(shot.getX() + " " + shot.getY());
effectHandler.triggerHitEffect(shipNode, shot);
return null;
}
@@ -112,7 +109,7 @@ private Geometry createCylinder(Shot shot) {
geometry.setMaterial(createColoredMaterial(color));
geometry.rotate(HALF_PI, 0f, 0f);
// compute the center of the shot in world coordinates
geometry.setLocalTranslation(shot.getY() + 0.5f, 0f, shot.getX() + 0.5f);
return geometry;
@@ -138,39 +135,42 @@ public Spatial visit(Battleship ship) {
return node;
}
/**
* Visits a Shell and creates a graphical representation of it.
*
* @param shell the Shell to be represented
* @return the node containing the graphical representation of the Shell
*/
@Override
public Spatial visit(Shell shell) {
final Node node = new Node(MISSILE);
node.attachChild(createMissile());
final Spatial bombModel = app.getAssetManager().loadModel(BOMB);
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;
// Apply transformations to the bomb model (scale, rotate, etc. if needed)
bombModel.scale(0.05f);
bombModel.rotate(-HALF_PI, 0f, 0f);
// Set the position of the bomb at the shell's current position
bombModel.setLocalTranslation(shell.getCurrentPosition());
// Add a control to animate the bomb's movement (similar to the previous cylinder animation)
bombModel.addControl(new ShellControl(shell,shell.getLogic()));
return bombModel;
}
/**
* 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 a detailed model based on the length of the ship.
*
* @param ship the battleship to be represented
* @return the spatial representing the battleship
*/
private Spatial createShip(Battleship ship) {
return switch (ship.getLength()) {
case 1 -> createPatrolBoat(ship);
case 2 -> createModernBattleship(ship);
case 3 -> createUboat(ship);
case 4 -> createBattleship(ship);
default -> createBox(ship);
};
// return ship.getLength() == 4 ? createBattleship(ship) : createBox(ship);
if (ship.getLength() == 4) {
return createBattleship(ship);
} else if (ship.getLength() == 3) {
return createBigShip(ship);
} else if (ship.getLength() == 2) {
return createMediumShip(ship);
} else if (ship.getLength() == 1) {
return createSmallShip(ship);
}
return createBattleship(ship);
}
/**
@@ -226,80 +226,47 @@ private Spatial createBattleship(Battleship ship) {
}
/**
* Creates a detailed 3D model to represent a modern battleship.
*
* @param ship the battleship to be represented
* @return the spatial representing the battleship
* Creates a detailed 3D model to represent a "Big Ship"
* @param ship The Battleship object with position and rotation info.
* @return the spatial representing the "Big Ship" battleship
*/
private Spatial createBigShip(Battleship ship) {
final Spatial model = app.getAssetManager().loadModel(DESTROYER);
private Spatial createModernBattleship(Battleship ship) {
final Spatial model = app.getAssetManager().loadModel(MODERN_BATTLESHIP_MODEL);
Material mat = new Material(app.getAssetManager(), UNSHADED);
mat.setTexture("ColorMap", app.getAssetManager().loadTexture(MODERN_BATTLESHIP_TEXTURES));
mat.getAdditionalRenderState().setBlendMode(RenderState.BlendMode.Off);
model.setMaterial(mat);
model.move(0,0.4f,0);
model.rotate(-HALF_PI, calculateRotationAngle(ship.getRot()) + HALF_PI, 0f);
model.scale(0.0001f);
model.setShadowMode(ShadowMode.CastAndReceive);
model.setQueueBucket(RenderQueue.Bucket.Opaque);
return model;
}
/**
* Creates a detailed 3D model to represent a "Medium Ship"
* @param ship The Battleship object with position and rotation info.
* @return the spatial representing the "Medium Ship" battleship
*/
private Spatial createMediumShip(Battleship ship) {
final Spatial model = app.getAssetManager().loadModel(FERRY);
model.move(0,0.25f,0);
model.rotate(-HALF_PI, calculateRotationAngle(ship.getRot()), 0f);
model.scale(0.00025f);
model.setShadowMode(ShadowMode.CastAndReceive);
return model;
}
/**
* Creates a detailed 3D model to represent a "Small Ship"
* @param ship The Battleship object with position and rotation info.
* @return the spatial representing the "Small Ship" battleship
*/
private Spatial createSmallShip(Battleship ship) {
final Spatial model = app.getAssetManager().loadModel(SMALL);
model.rotate(-HALF_PI, calculateRotationAngle(ship.getRot()) + HALF_PI, 0f);
model.scale(0.000075f);
model.setShadowMode(ShadowMode.CastAndReceive);
model.move(0, 0.2f, 0);
return model;
}
/**
* Creates a detailed 3D model to represent a missile.
*
* @return the spatial representing the missile
*/
private Spatial createMissile() {
final Spatial model = app.getAssetManager().loadModel(MISSILE_MODEL);
Material mat = new Material(app.getAssetManager(), UNSHADED);
mat.setTexture("ColorMap", app.getAssetManager().loadTexture(MISSILE_TEXTURE));
mat.getAdditionalRenderState().setBlendMode(RenderState.BlendMode.Off);
model.setMaterial(mat);
model.setQueueBucket(RenderQueue.Bucket.Opaque);
model.rotate(-HALF_PI, 0, 0);
model.scale(0.009f);
model.setShadowMode(ShadowMode.CastAndReceive);
model.move(0, 0f, 0);
return model;
}
/**
* Creates a detailed 3D model to represent a Uboat.
*
* @param ship the battleship to be represented
* @return the spatial representing the Uboat
*/
private Spatial createUboat(Battleship ship) {
final Spatial model = app.getAssetManager().loadModel(UBOAT_MODEL);
model.rotate(-HALF_PI, calculateRotationAngle(ship.getRot()), 0f);
model.scale(0.45f);
model.setShadowMode(ShadowMode.CastAndReceive);
model.move(0, -0.25f, 0);
return model;
}
/**
* Creates a detailed 3D model to represent a Patrol boat.
*
* @param ship the battleship to be represented
* @return the spatial representing the Patrol boat
*/
private Spatial createPatrolBoat(Battleship ship) {
final Spatial model = app.getAssetManager().loadModel(PATROL_BOAT_MODEL);
model.rotate(-HALF_PI, calculateRotationAngle(ship.getRot()), 0f);
model.scale(0.00045f);
model.scale(0.0009f);
model.setShadowMode(ShadowMode.CastAndReceive);
return model;

View File

@@ -1,62 +1,96 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.client.gui;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.control.AbstractControl;
import pp.battleship.client.BattleshipApp;
import pp.battleship.message.client.EndAnimationMessage;
import pp.battleship.model.IntPoint;
import pp.battleship.game.client.ClientGameLogic;
import pp.battleship.message.server.EffectMessage;
import pp.battleship.model.Shell;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import pp.battleship.notification.Sound;
import pp.util.Position;
/**
* Class to control the 3D representation of a shell
* Controls the oscillating pitch motion of a battleship model in the game.
* The ship oscillates to simulate a realistic movement on water, based on its orientation and length.
*/
public class ShellControl extends AbstractControl {
class ShellControl extends AbstractControl {
private final Shell shell;
private final BattleshipApp app;
private static final float TRAVEL_SPEED = 8.5f;
static final Logger LOGGER = System.getLogger(BattleshipApp.class.getName());
private MapView view;
private final ClientGameLogic logic;
private final EffectMessage msg;
private boolean hasPlayedSound = false;
/**
* Constructor for ShellControl class
* Constructs a new ShipControl instance for the specified Battleship.
* The ship's orientation determines the axis of rotation, while its length influences
* the cycle duration and amplitude of the oscillation.
*
* @param shell The Shell to be displayed
* @param app the main application
* @param shell the Battleship object to control
*/
public ShellControl(Shell shell, BattleshipApp app) {
public ShellControl(Shell shell, ClientGameLogic clientGameLogic) {
this.shell = shell;
this.app = app;
this.logic = clientGameLogic;
this.msg = shell.getMsg();
}
/**
* Method to control movement of the Shell and remove it when target is reached
* Initializes ShellControl with a shell, map view, and game logic.
* @param shell the shell to be controlled
* @param view the map view to display the shell
* @param clientGameLogic the game logic instance
*/
public ShellControl(Shell shell, MapView view, ClientGameLogic clientGameLogic) {
this.shell = shell;
this.view = view;
this.logic = clientGameLogic;
this.msg = shell.getMsg();
}
/**
* Updates the ship's pitch oscillation each frame. The ship's pitch is adjusted
* to create a continuous tilting motion, simulating the effect of waves.
*
* @param tpf time per frame (in seconds)
* @param tpf time per frame (in seconds), used to calculate the new pitch angle
*/
@Override
public void controlUpdate(float tpf) {
//LOGGER.log(Level.DEBUG, "missile at x=" + shell.getX() + ", y=" + shell.getY());
spatial.move(0, -TRAVEL_SPEED * tpf, 0);
if (spatial.getLocalTranslation().getY() <= 0.2) {
spatial.getParent().detachChild(spatial);
app.getGameLogic().send(new EndAnimationMessage(new IntPoint(shell.getX(), shell.getY())));
protected void controlUpdate(float tpf) {
if (spatial == null)
return;
if (shell.isFinished() && !hasPlayedSound) {
if (!msg.getShot().isHit())
logic.playSound(Sound.SPLASH);
else if (msg.getDestroyedShip() == null)
logic.playSound(Sound.EXPLOSION);
else
logic.playSound(Sound.DESTROYED_SHIP);
hasPlayedSound = true;
}
if (view == null) {
shell.updatePosition(tpf);
spatial.setLocalTranslation(shell.getCurrentPosition());
} else {
shell.updatePosition(tpf);
Position pos2d = view.modelToView(shell.getCurrentPosition().x - 0.3f, shell.getCurrentPosition().z - 0.3f);
spatial.setLocalTranslation(pos2d.getY(), pos2d.getX(), 0);
}
}
/**
* This method is called during the rendering phase, but it does not perform any
* operations in this implementation as the control only influences the spatial's
* transformation, not its rendering process.
*
* @param rm the RenderManager rendering the controlled Spatial (not null)
* @param vp the ViewPort being rendered (not null)
* Called during rendering, but no operations are needed as this control only affects spatial transformation.
* @param rm the RenderManager rendering the spatial
* @param vp the ViewPort being rendered
*/
@Override
protected void controlRender(RenderManager rm, ViewPort vp) {
// No rendering logic is needed for this control
}
}

View File

@@ -1,62 +0,0 @@
package pp.battleship.client.gui;
import com.jme3.math.Vector3f;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.control.AbstractControl;
import pp.battleship.client.BattleshipApp;
import pp.battleship.message.client.EndAnimationMessage;
import pp.battleship.model.IntPoint;
import pp.util.Position;
/**
* Class to control the 2D representation of a shell
*/
public class ShellMapControl extends AbstractControl {
private final Position position;
private final IntPoint pos;
private static final Vector3f VECTOR_3_F = new Vector3f();
private final BattleshipApp app;
/**
* Constructor for ShellMapControl
*
* @param position the target position of the shell
* @param app the main application
* @param pos the position the then to render shot goes to
*/
public ShellMapControl(Position position, BattleshipApp app, IntPoint pos) {
super();
this.position = position;
this.pos = pos;
this.app = app;
VECTOR_3_F.set(new Vector3f(position.getX(), position.getY(), 0));
}
/**
* Method to control movement of the Shell on the map and remove it when target is reached
*
* @param tpf time per frame (in seconds)
*/
@Override
protected void controlUpdate(float tpf) {
spatial.move(VECTOR_3_F.mult(tpf));
if (spatial.getLocalTranslation().getX() >= position.getX() && spatial.getLocalTranslation().getY() >= position.getY()) {
spatial.getParent().detachChild(spatial);
app.getGameLogic().send(new EndAnimationMessage(pos));
}
}
/**
* This method is called during the rendering phase, but it does not perform any
* operations in this implementation as the control only influences the spatial's
* transformation, not its rendering process.
*
* @param rm the RenderManager rendering the controlled Spatial (not null)
* @param vp the ViewPort being rendered (not null)
*/
@Override
protected void controlRender(RenderManager rm, ViewPort vp) {
}
}

View File

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

View File

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

View File

@@ -1,28 +1,25 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.client.server;
package server;
import com.jme3.network.ConnectionListener;
import com.jme3.network.HostedConnection;
import com.jme3.network.Message;
import com.jme3.network.MessageListener;
import com.jme3.network.Network;
import com.jme3.network.Server;
import com.jme3.network.*;
import com.jme3.network.serializing.Serializer;
import pp.battleship.BattleshipConfig;
import pp.battleship.game.server.Player;
import pp.battleship.game.server.ServerGameLogic;
import pp.battleship.game.server.ServerSender;
import pp.battleship.message.client.ClientMessage;
import pp.battleship.message.client.EndAnimationMessage;
import pp.battleship.message.client.MapMessage;
import pp.battleship.message.client.ShootMessage;
import pp.battleship.message.server.EffectMessage;
import pp.battleship.message.server.GameDetails;
import pp.battleship.message.server.ServerMessage;
import pp.battleship.message.server.StartAnimationMessage;
import pp.battleship.message.server.StartBattleMessage;
import pp.battleship.message.server.SwitchToBattleState;
import pp.battleship.model.Battleship;
import pp.battleship.model.IntPoint;
import pp.battleship.model.Shot;
@@ -43,9 +40,6 @@ public class BattleshipServer implements MessageListener<HostedConnection>, Conn
private static final Logger LOGGER = System.getLogger(BattleshipServer.class.getName());
private static final File CONFIG_FILE = new File("server.properties");
private static int port;
private final BattleshipConfig config = new BattleshipConfig();
private Server myServer;
private final ServerGameLogic logic;
private final BlockingQueue<ReceivedMessage> pendingMessages = new LinkedBlockingQueue<>();
@@ -62,29 +56,32 @@ public class BattleshipServer implements MessageListener<HostedConnection>, Conn
}
}
/**
* Creates the server.
*/
public BattleshipServer(int port) {
public BattleshipServer() {
BattleshipConfig config = new BattleshipConfig();
config.readFromIfExists(CONFIG_FILE);
BattleshipServer.port = port;
LOGGER.log(Level.INFO, "Configuration: {0}", config); //NON-NLS
logic = new ServerGameLogic(this, config);
}
/**
* Runs a server
* Starts the server on the given port and continuously processes incoming messages.
* @param port the port to start the server on
*/
public void run() {
startServer();
public void run(int port) {
startServer(port);
while (true)
processNextMessage();
}
/**
* Starts a server
* Initializes and starts the server on the specified port, handling exceptions if the server fails to start.
* @param port the port to start the server on
*/
private void startServer() {
private void startServer(int port) {
try {
LOGGER.log(Level.INFO, "Starting server..."); //NON-NLS
myServer = Network.createServer(port);
@@ -100,7 +97,7 @@ private void startServer() {
}
/**
* Processes next received message
* Retrieves and processes the next message from the queue, handling interruptions during the wait.
*/
private void processNextMessage() {
try {
@@ -113,7 +110,7 @@ private void processNextMessage() {
}
/**
* Registers all serializable classes
* Processes the next message from the queue, handling interruptions during message retrieval.
*/
private void initializeSerializables() {
Serializer.registerClass(GameDetails.class);
@@ -124,24 +121,20 @@ private void initializeSerializables() {
Serializer.registerClass(Battleship.class);
Serializer.registerClass(IntPoint.class);
Serializer.registerClass(Shot.class);
Serializer.registerClass(StartAnimationMessage.class);
Serializer.registerClass(EndAnimationMessage.class);
Serializer.registerClass(SwitchToBattleState.class);
}
/**
* Registers all listeners
* Registers message and connection listeners for the server.
*/
private void registerListeners() {
myServer.addMessageListener(this, MapMessage.class);
myServer.addMessageListener(this, ShootMessage.class);
myServer.addMessageListener(this, EndAnimationMessage.class);
myServer.addConnectionListener(this);
}
/**
* Handles a received message
* @param source the connection the message comes from
* Handles received messages, logging the source and adding client messages to the pending queue.
* @param source the connection the message was received from
* @param message the received message
*/
@Override
@@ -152,9 +145,9 @@ public void messageReceived(HostedConnection source, Message message) {
}
/**
* Adds a new connection to a server
* @param server the server to add the connection to
* @param hostedConnection the connection to be added
* Handles a new connection by logging it and adding a new player to the game logic.
* @param server the server receiving the connection
* @param hostedConnection the newly added connection
*/
@Override
public void connectionAdded(Server server, HostedConnection hostedConnection) {
@@ -163,9 +156,9 @@ public void connectionAdded(Server server, HostedConnection hostedConnection) {
}
/**
* Removes a standing connection from a server
* @param server the server to add the connection to
* @param hostedConnection the connection to be added
* Handles the removal of a connection by logging it, checking if it belongs to an active player, and exiting if necessary.
* @param server the server losing the connection
* @param hostedConnection the removed connection
*/
@Override
public void connectionRemoved(Server server, HostedConnection hostedConnection) {
@@ -180,8 +173,8 @@ public void connectionRemoved(Server server, HostedConnection hostedConnection)
}
/**
* Shuts down the server and terminates the application with the given exit code
* @param exitValue the exit status code
* Closes all client connections and terminates the server with the given exit value.
* @param exitValue the exit code to terminate the application with
*/
private void exit(int exitValue) { //NON-NLS
LOGGER.log(Level.INFO, "close request"); //NON-NLS

View File

@@ -1,15 +1,15 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package server;
package pp.battleship.client.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);

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,11 @@
# Blender MTL File: 'untitletttd.blend'
# Material Count: 1
newmtl None
Ns 0
Ka 0.000000 0.000000 0.000000
Kd 0.8 0.8 0.8
Ks 0.8 0.8 0.8
d 1
illum 2
map_Kd C:\Users\Convidado.Cliente-JMF-PC\Desktop\ghftht.png

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

View File

@@ -0,0 +1,64 @@
# 3ds Max Wavefront OBJ Exporter v0.97b - (c)2007 guruware
# File Created: 13.03.2012 15:35:28
newmtl metall
Ns 31.0000
Ni 1.5000
d 1.0000
Tr 0.0000
Tf 1.0000 1.0000 1.0000
illum 2
Ka 0.2431 0.2431 0.2431
Kd 0.2431 0.2431 0.2431
Ks 0.5850 0.5850 0.5850
Ke 0.0000 0.0000 0.0000
newmtl 13922_StatenIslandFerry
Ns 50.0000
Ni 1.5000
d 1.0000
Tr 0.0000
Tf 1.0000 1.0000 1.0000
illum 2
Ka 1.0000 1.0000 1.0000
Kd 1.0000 1.0000 1.0000
Ks 0.5850 0.5850 0.5850
Ke 0.0000 0.0000 0.0000
map_Ka 13922_StatenIslandFerry_diffuse.jpg
map_Kd 13922_StatenIslandFerry_diffuse.jpg
newmtl metall2
Ns 50.0000
Ni 1.5000
d 1.0000
Tr 0.0000
Tf 1.0000 1.0000 1.0000
illum 2
Ka 0.2118 0.2824 0.3451
Kd 0.2118 0.2824 0.3451
Ks 0.5850 0.5850 0.5850
Ke 0.0000 0.0000 0.0000
newmtl boat
Ns 34.0000
Ni 1.5000
d 1.0000
Tr 0.0000
Tf 1.0000 1.0000 1.0000
illum 2
Ka 0.6588 0.3059 0.1294
Kd 0.6588 0.3059 0.1294
Ks 0.3600 0.3600 0.3600
Ke 0.0000 0.0000 0.0000
newmtl white
Ns 10.0000
Ni 1.5000
d 1.0000
Tr 0.0000
Tf 1.0000 1.0000 1.0000
illum 2
Ka 0.9686 0.9686 0.9686
Kd 0.9686 0.9686 0.9686
Ks 0.0000 0.0000 0.0000
Ke 0.0000 0.0000 0.0000

View File

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

View File

@@ -1,12 +0,0 @@
# 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

View File

@@ -1,2 +0,0 @@
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.

Before

Width:  |  Height:  |  Size: 6.8 MiB

View File

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

Binary file not shown.

Before

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 166 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 717 KiB

View File

@@ -0,0 +1,28 @@
# 3ds Max Wavefront OBJ Exporter v0.97b - (c)2007 guruware
# File Created: 08.06.2011 15:26:00
newmtl _10634_SpeedBoat_v01_LOD310634_SpeedBoat_v01
Ns 53.0000
Ni 1.5000
d 1.0000
Tr 0.0000
Tf 1.0000 1.0000 1.0000
illum 2
Ka 0.5882 0.5882 0.5882
Kd 0.5882 0.5882 0.5882
Ks 0.2000 0.2000 0.2000
Ke 0.0000 0.0000 0.0000
map_Ka 10634_SpeedBoat_v01.jpg
map_Kd 10634_SpeedBoat_v01.jpg
newmtl glass
Ns 80.0000
Ni 1.5000
d 0.2000
Tr 0.8000
Tf 0.2000 0.2000 0.2000
illum 2
Ka 0.5882 0.5882 0.5882
Kd 0.5882 0.5882 0.5882
Ks 0.5000 0.5000 0.5000
Ke 0.0000 0.0000 0.0000

View File

@@ -0,0 +1,3 @@
based on:
https://free3d.com/3d-model/speedboat-v01--840133.html
License: Free Personal Use Only

View File

@@ -1,16 +0,0 @@
# 3ds Max Wavefront OBJ Exporter v0.97b - (c)2007 guruware
# File Created: 29.03.2012 14:25:39
newmtl default
Ns 35.0000
Ni 1.5000
d 1.0000
Tr 0.0000
Tf 1.0000 1.0000 1.0000
illum 2
Ka 1.0000 1.0000 1.0000
Kd 1.0000 1.0000 1.0000
Ks 0.5400 0.5400 0.5400
Ke 0.0000 0.0000 0.0000
map_Ka 14084_WWII_ship_German_Type_II_U-boat_diff.jpg
map_Kd 14084_WWII_ship_German_Type_II_U-boat_diff.jpg

View File

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

View File

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

View File

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

View File

@@ -1,4 +0,0 @@
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

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

View File

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

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.8 MiB

View File

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

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 MiB

Binary file not shown.

View File

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

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,11 @@
# Blender MTL File: 'untitletttd.blend'
# Material Count: 1
newmtl None
Ns 0
Ka 0.000000 0.000000 0.000000
Kd 0.8 0.8 0.8
Ks 0.8 0.8 0.8
d 1
illum 2
map_Kd C:\Users\Convidado.Cliente-JMF-PC\Desktop\ghftht.png

File diff suppressed because one or more lines are too long

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 360 KiB

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

View File

@@ -0,0 +1,64 @@
# 3ds Max Wavefront OBJ Exporter v0.97b - (c)2007 guruware
# File Created: 13.03.2012 15:35:28
newmtl metall
Ns 31.0000
Ni 1.5000
d 1.0000
Tr 0.0000
Tf 1.0000 1.0000 1.0000
illum 2
Ka 0.2431 0.2431 0.2431
Kd 0.2431 0.2431 0.2431
Ks 0.5850 0.5850 0.5850
Ke 0.0000 0.0000 0.0000
newmtl 13922_StatenIslandFerry
Ns 50.0000
Ni 1.5000
d 1.0000
Tr 0.0000
Tf 1.0000 1.0000 1.0000
illum 2
Ka 1.0000 1.0000 1.0000
Kd 1.0000 1.0000 1.0000
Ks 0.5850 0.5850 0.5850
Ke 0.0000 0.0000 0.0000
map_Ka 13922_StatenIslandFerry_diffuse.jpg
map_Kd 13922_StatenIslandFerry_diffuse.jpg
newmtl metall2
Ns 50.0000
Ni 1.5000
d 1.0000
Tr 0.0000
Tf 1.0000 1.0000 1.0000
illum 2
Ka 0.2118 0.2824 0.3451
Kd 0.2118 0.2824 0.3451
Ks 0.5850 0.5850 0.5850
Ke 0.0000 0.0000 0.0000
newmtl boat
Ns 34.0000
Ni 1.5000
d 1.0000
Tr 0.0000
Tf 1.0000 1.0000 1.0000
illum 2
Ka 0.6588 0.3059 0.1294
Kd 0.6588 0.3059 0.1294
Ks 0.3600 0.3600 0.3600
Ke 0.0000 0.0000 0.0000
newmtl white
Ns 10.0000
Ni 1.5000
d 1.0000
Tr 0.0000
Tf 1.0000 1.0000 1.0000
illum 2
Ka 0.9686 0.9686 0.9686
Kd 0.9686 0.9686 0.9686
Ks 0.0000 0.0000 0.0000
Ke 0.0000 0.0000 0.0000

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,13 +1,18 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.game.client;
import com.jme3.math.Vector3f;
import pp.battleship.message.client.ShootMessage;
import pp.battleship.message.server.EffectMessage;
import pp.battleship.message.server.StartAnimationMessage;
import pp.battleship.model.IntPoint;
import pp.battleship.model.Shell;
import pp.battleship.model.ShipMap;
import pp.battleship.notification.Music;
import pp.battleship.notification.Sound;
import java.lang.System.Logger.Level;
@@ -26,14 +31,12 @@ class BattleState extends ClientState {
*/
public BattleState(ClientGameLogic logic, boolean myTurn) {
super(logic);
logic.playMusic(Music.GAME_THEME);
this.myTurn = myTurn;
}
/**
* Makes sure the client renders the correct view
*
* @return true
* displays the battle scene.
* @return true to show the battle
*/
@Override
public boolean showBattle() {
@@ -41,9 +44,8 @@ public boolean showBattle() {
}
/**
* Triggers a shoot event if it's client's turn
*
* @param pos the position where the click occurred
* Handles clicking on the opponent's map. If it's the player's turn and the position is valid, a ShootMessage is sent.
* @param pos the clicked position on the opponent's map
*/
@Override
public void clickOpponentMap(IntPoint pos) {
@@ -54,13 +56,43 @@ else if (logic.getOpponentMap().isValid(pos))
}
/**
* Triggers an animation if StartAnimationMessage is received
* Reports the effect of a shot based on the server message.
*
* @param msg the received Startanimation message
* @param msg the message containing the effect of the shot
*/
@Override
public void receivedStartAnimation(StartAnimationMessage msg) {
logic.setState(new AnimationState(logic, msg.isMyTurn(), msg.getPosition()));
public void receivedEffect(EffectMessage msg) {
ClientGameLogic.LOGGER.log(Level.INFO, "report effect: {0}", msg); //NON-NLS
myTurn = msg.isMyTurn();
logic.playSound(Sound.MISSILE_LAUNCH);
logic.setInfoText(msg.getInfoTextKey());
affectedMap(msg).add(msg.getShot());
affectedMap(msg).add(new Shell(new Vector3f(0, 50, 0), new Vector3f(msg.getShot().getY() + 0.5f, -0.4f, msg.getShot().getX() + 0.5f), 1f,msg,logic));
if (destroyedOpponentShip(msg))
logic.getOpponentMap().add(msg.getDestroyedShip());
if (msg.isGameOver()) {
msg.getRemainingOpponentShips().forEach(logic.getOpponentMap()::add);
logic.setState(new GameOverState(logic));
}
}
/**
* Determines which map (own or opponent's) should be affected by the shot based on the message.
*
* @param msg the effect message received from the server
* @return the map (either the opponent's or player's own map) that is affected by the shot
*/
private ShipMap affectedMap(EffectMessage msg) {
return msg.isOwnShot() ? logic.getOpponentMap() : logic.getOwnMap();
}
/**
* Checks if the opponent's ship was destroyed by the player's shot.
*
* @param msg the effect message received from the server
* @return true if the shot destroyed an opponent's ship, false otherwise
*/
private boolean destroyedOpponentShip(EffectMessage msg) {
return msg.getDestroyedShip() != null && msg.isOwnShot();
}
}

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