14 Commits

Author SHA1 Message Date
Daniel Grigencha
5174b84a1b fixed client-hosted server don't thorw an exception
- added serialization to the client-hosted server
2024-10-14 11:15:27 +02:00
Daniel Grigencha
42b995a4e7 added animation of a shell to the game
- in BattleShipServer class added serialization of the AnimationMessage classs
- added to VoidVisitor and Visitor the Shell class
- edited the ServerGameLogic class to implement a new Animation state (see new Server-State-Chart)
- added a new client state AnimationState (see new Client-State-Chart)
2024-10-13 03:19:44 +02:00
Daniel Grigencha
2c4e2fd92d improved code to pass the code analysis 2024-10-09 23:30:28 +02:00
Daniel Grigencha
08c5eeb63d added realistic visual effects to the game
- imported the jme3-effects library
- edited SeaSynchronizer to handle different effects
- added to the ShipControl class in the controlUpdate(float tpf) method the handler that moves a destroyed ship downward
2024-10-09 23:28:02 +02:00
Daniel Grigencha
9d5f3ac396 added the feature that a client can host a server
- added a class BattleshipServer (a client host a local server) and ReceivedMessage
- edited the NetworkDialog, that a client has a checkbox to select to host a server
-
2024-10-09 18:30:49 +02:00
Daniel Grigencha
28ba183b84 fixed BackgroundMusic
before play a new music, the volume prefences should be set
2024-10-09 17:04:08 +02:00
Daniel Grigencha
a44cbf2a72 added background music to the game
- added a class BackgroundMusic: is an AbstractAppState and GameEventListener that handles the backgroundmusic
- attached the BackgroundMusic to the stateManager  in the BattleshipApp
- added to the Menu a CheckBox and Slider to manipulate the volume of the backgroundmusic
- added four different music files (for different states of the game)
- edited the WaitState and BattleState to play different music files when chaing to that state
- added to ClientGameLogic a new method playMusic(Music) to play the right music (depends on the current state)
- added a new method receivedEvent(MusicEvent) to handle the music events
- added a new enum Music, that represents different types of music
- added a new record MusicEvent(Music), that decides which music shall play
2024-10-09 17:03:12 +02:00
Daniel Grigencha
ec80dd40ce added JavaDocs to the FloatMath class 2024-10-09 02:14:15 +02:00
Daniel Grigencha
046707642f fixed bugs in the JSON validation
- the method isWithinBounds(Battleship ship) couldn't check if the ship is the bounds of the map
2024-10-05 13:20:20 +02:00
Daniel Grigencha
a3b5452fb9 added 3d models for the ships
- added different models (see README.txt of the files)
- added methods to the SeaSynchronizer class to represent different ships sizes with different models
2024-10-05 05:41:12 +02:00
Daniel Grigencha
eda4f06a75 added server-side and client-side validation for JSON files
- added the client-side validation in the EditorState class
- added the server-side validation in the WaitState and ServerGameLogic class
- added Getter in the ShipMapDTO
- added the 'map.invalid' in the properties
2024-10-05 05:32:26 +02:00
Daniel Grigencha
0d2781dbe4 fixed failing tests
- ShipMapTest: notify ItemRemovedEvent when calling the remove method.
- ClientGame1Player1 and ClientGame2Player2Test: Ensure opponent's is retrieved in game over state.
2024-10-05 04:41:24 +02:00
Daniel Grigencha
ef16a3f92b Revert main branch 2024-10-02 13:30:55 +02:00
Felix Koppe
3a2f20e45c Fix ShipMap.remove 2024-10-02 08:21:32 +02:00
87 changed files with 106447 additions and 223619 deletions

View File

@@ -15,6 +15,7 @@ implementation project(":battleship:model")
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.
@@ -23,13 +23,13 @@ map.own=maps/map1.json
# 2, 3 # 2, 3
# defines four shots, namely at the coordinates # defines four shots, namely at the coordinates
# (x=2, y=0), (x=2, y=1), (x=2, y=2), and (x=2, y=3) # (x=2, y=0), (x=2, y=1), (x=2, y=2), and (x=2, y=3)
robot.targets=2, 3,\ robot.targets=2, 0,\
2, 4,\ 2, 1,\
2, 5,\ 2, 2,\
2, 8 2, 3
# #
# Delay in milliseconds between each shot fired by the RobotClient. # Delay in milliseconds between each shot fired by the RobotClient.
robot.delay=500 robot.delay=2000
# #
# 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,242 +1,267 @@
package pp.battleship.client; package pp.battleship.client;
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 com.jme3.audio.AudioSource.Status;
import pp.battleship.notification.Music;
import pp.battleship.notification.MusicEvent;
import pp.battleship.notification.GameEventListener; import pp.battleship.notification.GameEventListener;
import pp.battleship.notification.MusicEvent;
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;
public class BackgroundMusic implements GameEventListener { import static pp.util.PreferencesUtils.getPreferences;
private static final String VOLUME_PREF = "volume";
private static final String MUSIC_ENABLED_PREF = "musicEnabled";
private static final Preferences PREFS = Preferences.userNodeForPackage(BackgroundMusic.class);
static final Logger LOGGER = System.getLogger(BackgroundMusic.class.getName()); /**
* The BackgroundMusic class represents the background music in the Battleship game application.
* 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 {
/**
* Logger for the BackgroundMusic class.
*/
private static final Logger LOGGER = System.getLogger(BackgroundMusic.class.getName());
private static final String MENU_MUSIC = "Music/MainMenu/Dark_Intro.ogg"; /**
private static final String BATTLE_MUSIC = "Music/BattleTheme/boss_battle_#2_metal_loop.wav"; * Preferences for storing music settings.
private static final String GAME_OVER_MUSIC_L = "Music/GameOver/Lose/Lose.ogg"; */
private static final String GAME_OVER_MUSIC_V = "Music/GameOver/Victory/Victory.wav"; private static final Preferences PREFERENCES = getPreferences(BackgroundMusic.class);
private final AudioNode menuMusic; /**
private final AudioNode battleMusic; * Preference key for enabling/disabling music.
private final AudioNode gameOverMusicL; */
private final AudioNode gameOverMusicV; private static final String ENABLED_PREF = "enabled"; //NON-NLS
private String lastNodePlayed;
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 final BattleshipApp app;
/** /**
* Initializes and controls the BackgroundMusic * Checks if music is enabled in the preferences.
* *
* @param app The main Application * @return {@code true} if music is enabled, {@code false} otherwise.
*/ */
public BackgroundMusic(BattleshipApp app) { public static boolean enabledInPreferences() {
this.volume = PREFS.getFloat(VOLUME_PREF, 1.0f); return PREFERENCES.getBoolean(ENABLED_PREF, true);
this.musicEnabled = PREFS.getBoolean(MUSIC_ENABLED_PREF, true);
this.app = app;
menuMusic = createAudioNode(MENU_MUSIC);
battleMusic = createAudioNode(BATTLE_MUSIC);
gameOverMusicL = createAudioNode(GAME_OVER_MUSIC_L);
gameOverMusicV = createAudioNode(GAME_OVER_MUSIC_V);
stop(battleMusic);
stop(gameOverMusicL);
stop(gameOverMusicV);
lastNodePlayed = menuMusic.getName();
if(musicEnabled) {
play(menuMusic);
}
} }
/** /**
* This method will be used to create the audio node containing the music * Sets the enabled state of this AppState.
* Overrides {@link com.jme3.app.state.AbstractAppState#setEnabled(boolean)}
* *
* @param musicFilePath the file path to the music * @param enabled {@code true} to enable the AppState, {@code false} to disable it.
* @return the created audio node
*/ */
private AudioNode createAudioNode(String musicFilePath) { @Override
AudioNode audioNode = new AudioNode(app.getAssetManager(), musicFilePath, DataType.Stream); public void setEnabled(boolean enabled) {
audioNode.setVolume(volume * app.getMainVolumeControl().getMainVolume()); if (isEnabled() == enabled) return;
audioNode.setPositional(false); super.setEnabled(enabled);
audioNode.setLooping(true); LOGGER.log(Level.INFO, "Music enabled: {0}", enabled); //NON-NLS
audioNode.setName(musicFilePath); PREFERENCES.putBoolean(ENABLED_PREF, enabled);
return audioNode; playCurrentMusic();
} }
/** /**
* sets the give audio node to play * Initializes the music for the game.
* Overrides {@link AbstractAppState#initialize(AppStateManager, Application)}
* *
* @param audioNode the audio node which should start to play * @param stateManager The state manager
* @param app The application
*/ */
public void play(AudioNode audioNode) { @Override
if (musicEnabled && (audioNode.getStatus() == Status.Stopped || audioNode.getStatus() == Status.Paused)) { public void initialize(AppStateManager stateManager, Application app) {
audioNode.play(); LOGGER.log(Level.INFO, "Initializing background music"); //NON-NLS
lastNodePlayed = audioNode.getName(); 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();
} }
/** /**
* stops the given audio node from playing * Loads a music file and initializes an AudioNode with the specified settings.
* *
* @param audioNode the audio node to be stopped * @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.
*/ */
public void stop(AudioNode audioNode) { private AudioNode loadMusic(Application app, String name) {
if (audioNode.getStatus() == Status.Playing) { try {
audioNode.stop(); 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;
} }
/** /**
* pauses the given audi node * Plays the current music if the music is enabled.
* * Stops the current music if the music is disabled.
* @param audioNode the audio node to be paused
*/ */
public void pause(AudioNode audioNode) { private void playCurrentMusic() {
if (audioNode.getStatus() == Status.Playing) { if (isEnabled()) {
audioNode.pause(); if (currentMusic != null) {
} LOGGER.log(Level.INFO, "Playing current music"); //NON-NLS
} currentMusic.play();
/**
* Toggle Method to control the music to switch it on or off
*/
public void toggleMusic() {
this.musicEnabled = !this.musicEnabled;
if (musicEnabled) {
switch (lastNodePlayed){
case MENU_MUSIC:
play(menuMusic);
break;
case BATTLE_MUSIC:
play(battleMusic);
break;
case GAME_OVER_MUSIC_L:
play(gameOverMusicL);
break;
case GAME_OVER_MUSIC_V:
play(gameOverMusicV);
break;
} }
} else { } else {
pause(menuMusic); if (currentMusic != null) {
pause(battleMusic); currentMusic.stop();
pause(gameOverMusicL); }
pause(gameOverMusicV);
} }
PREFS.putBoolean(MUSIC_ENABLED_PREF, musicEnabled);
} }
/** /**
* this method is used when the main volume changes * Plays the game music.
*/ */
public void setVolume(){ private void gameMusic() {
setVolume(PREFS.getFloat(VOLUME_PREF, 1.0f)); if (isEnabled() && gameMusic != null) {
stopAll();
LOGGER.log(Level.INFO, "Playing game music"); //NON-NLS
PREFERENCES.putFloat(VOLUME_PREF, volume);
gameMusic.play();
}
} }
/** /**
* Method to set the volume for the music * 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 volume float to transfer the new volume * @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;
float mainVolume = app.getMainVolumeControl().getMainVolume(); currentMusic.setVolume(volume);
menuMusic.setVolume(volume * mainVolume); PREFERENCES.putFloat(VOLUME_PREF, volume);
battleMusic.setVolume(volume * mainVolume);
gameOverMusicL.setVolume(volume * mainVolume);
gameOverMusicV.setVolume(volume * mainVolume);
PREFS.putFloat(VOLUME_PREF, volume);
} }
/** /**
* This method retuns the volume * Returns the volume level for the background music.
* *
* @return the current volume as a float * @return The volume level 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;
}
/**
* 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 && !lastNodePlayed.equals(MENU_MUSIC)) {
LOGGER.log(Level.INFO, "Received Music change Event {0}", music.toString());
stop(battleMusic);
stop(gameOverMusicL);
stop(gameOverMusicV);
play(menuMusic);
lastNodePlayed = menuMusic.getName();
} else if (music == Music.BATTLE_THEME && !lastNodePlayed.equals(BATTLE_MUSIC)) {
LOGGER.log(Level.INFO, "Received Music change Event {0}", music.toString());
stop(menuMusic);
stop(gameOverMusicL);
stop(gameOverMusicV);
play(battleMusic);
lastNodePlayed = battleMusic.getName();
} else if (music == Music.GAME_OVER_THEME_L && !lastNodePlayed.equals(GAME_OVER_MUSIC_L)) {
LOGGER.log(Level.INFO, "Received Music change Event {0}", music.toString());
stop(menuMusic);
stop(battleMusic);
stop(gameOverMusicV);
play(gameOverMusicL);
lastNodePlayed = gameOverMusicL.getName();
} else if (music == Music.GAME_OVER_THEME_V && !lastNodePlayed.equals(GAME_OVER_MUSIC_V)){
LOGGER.log(Level.INFO, "Received Music change Event {0}", music.toString());
stop(menuMusic);
stop(battleMusic);
stop(gameOverMusicL);
play(gameOverMusicV);
lastNodePlayed = gameOverMusicV.getName();
}
}
/**
* the method which receives the Event
*
* @param music the received Event
*/
@Override
public void receivedEvent (MusicEvent music){
LOGGER.log(Level.INFO, "Received Music change Event {0}", music.toString());
switch (music.music()){
case MENU_THEME:
changeMusic(Music.MENU_THEME);
break;
case BATTLE_THEME:
changeMusic(Music.BATTLE_THEME);
break;
case GAME_OVER_THEME_L:
changeMusic(Music.GAME_OVER_THEME_L);
break;
case GAME_OVER_THEME_V:
changeMusic(Music.GAME_OVER_THEME_V);
break;
}
}
} }

View File

@@ -122,24 +122,13 @@ 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);
/**
* The Object which handles the background music
*/
private BackgroundMusic backgroundMusic;
/**
* The object that handles the main volume
*/
private MainVolume mainVolume;
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());
} }
} }
@@ -235,10 +224,6 @@ public void simpleInitApp() {
setupStates(); setupStates();
setupGui(); setupGui();
serverConnection.connect(); serverConnection.connect();
mainVolume = new MainVolume(this);
backgroundMusic = new BackgroundMusic(this);
logic.addListener(backgroundMusic);
} }
/** /**
@@ -281,6 +266,7 @@ 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());
} }
@@ -294,6 +280,19 @@ 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.
@@ -440,22 +439,4 @@ void errorDialog(String errorMessage) {
.build() .build()
.open(); .open();
} }
/**
* this method returns the object which handles the background music
*
* @return BackgroundMusic
*/
public BackgroundMusic getBackgroundMusic(){
return backgroundMusic;
}
/**
* this method returns the object which handles the main volume
*
* @return an object of MainVolume
*/
public MainVolume getMainVolumeControl(){
return mainVolume;
}
} }

View File

@@ -5,7 +5,7 @@
// (c) Mark Minas (mark.minas@unibw.de) // (c) Mark Minas (mark.minas@unibw.de)
//////////////////////////////////////// ////////////////////////////////////////
package pp.battleship.client.server; package pp.battleship.client;
import com.jme3.network.ConnectionListener; import com.jme3.network.ConnectionListener;
import com.jme3.network.HostedConnection; import com.jme3.network.HostedConnection;
@@ -18,11 +18,14 @@
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.AnimationEndMessage; import pp.battleship.message.client.AnimationMessage;
import pp.battleship.message.client.ClientMessage; import pp.battleship.message.client.ClientMessage;
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.*; import pp.battleship.message.server.EffectMessage;
import pp.battleship.message.server.GameDetails;
import pp.battleship.message.server.ServerMessage;
import pp.battleship.message.server.StartBattleMessage;
import pp.battleship.model.Battleship; import pp.battleship.model.Battleship;
import pp.battleship.model.IntPoint; import pp.battleship.model.IntPoint;
import pp.battleship.model.Shot; import pp.battleship.model.Shot;
@@ -40,14 +43,39 @@
* 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 {
@@ -56,8 +84,7 @@ 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());
} }
} }
@@ -65,65 +92,91 @@ public class BattleshipServer implements MessageListener<HostedConnection>, Conn
/** /**
* Creates the server. * Creates the server.
*/ */
public BattleshipServer(int port) { public BattleshipServer(int PORT_NUMBER) {
config.readFromIfExists(CONFIG_FILE); config.readFromIfExists(CONFIG_FILE);
BattleshipServer.port = port; this.PORT_NUMBER = PORT_NUMBER;
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.
*/
public void run() { public void run() {
startServer(); startServer();
while (true) while (true)
processNextMessage(); processNextMessage();
} }
/**
* Starts the server and initializes necessary components.
* 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); myServer = Network.createServer(PORT_NUMBER);
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.
* 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.
* 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(AnimationEndMessage.class);
Serializer.registerClass(AnimationStartMessage.class);
Serializer.registerClass(SwitchBattleState.class);
} }
/**
* Registers listeners for incoming connections and messages.
* 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, AnimationEndMessage.class); myServer.addMessageListener(this, AnimationMessage.class);
myServer.addConnectionListener(this); myServer.addConnectionListener(this);
} }
/**
* Handles the reception of messages from clients.
*
* @param source the connection from which the message was received
* @param message the message received from the client
*/
@Override @Override
public void messageReceived(HostedConnection source, Message message) { public void messageReceived(HostedConnection source, Message message) {
LOGGER.log(Level.INFO, "message received from {0}: {1}", source.getId(), message); //NON-NLS LOGGER.log(Level.INFO, "message received from {0}: {1}", source.getId(), message); //NON-NLS
@@ -131,12 +184,24 @@ public void messageReceived(HostedConnection source, Message message) {
pendingMessages.add(new ReceivedMessage(clientMessage, source.getId())); pendingMessages.add(new ReceivedMessage(clientMessage, source.getId()));
} }
/**
* Called when a new connection is added to the server.
*
* @param server the server to which the connection was added
* @param hostedConnection the connection that was added
*/
@Override @Override
public void connectionAdded(Server server, HostedConnection hostedConnection) { public void connectionAdded(Server server, HostedConnection hostedConnection) {
LOGGER.log(Level.INFO, "new connection {0}", hostedConnection); //NON-NLS LOGGER.log(Level.INFO, "new connection {0}", hostedConnection); //NON-NLS
logic.addPlayer(hostedConnection.getId()); logic.addPlayer(hostedConnection.getId());
} }
/**
* Called when a connection is removed from the server.
*
* @param server the server from which the connection was removed
* @param hostedConnection the connection that was removed
*/
@Override @Override
public void connectionRemoved(Server server, HostedConnection hostedConnection) { public void connectionRemoved(Server server, HostedConnection hostedConnection) {
LOGGER.log(Level.INFO, "connection closed: {0}", hostedConnection); //NON-NLS LOGGER.log(Level.INFO, "connection closed: {0}", hostedConnection); //NON-NLS
@@ -149,6 +214,12 @@ public void connectionRemoved(Server server, HostedConnection hostedConnection)
} }
} }
/**
* Exits the application with the specified exit value.
* Closes all client connections and logs the close request.
*
* @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
if (myServer != null) if (myServer != null)

View File

@@ -14,7 +14,6 @@
import com.jme3.asset.AssetNotFoundException; import com.jme3.asset.AssetNotFoundException;
import com.jme3.audio.AudioData; import com.jme3.audio.AudioData;
import com.jme3.audio.AudioNode; import com.jme3.audio.AudioNode;
import com.jme3.audio.AudioSource;
import pp.battleship.notification.GameEventListener; import pp.battleship.notification.GameEventListener;
import pp.battleship.notification.SoundEvent; import pp.battleship.notification.SoundEvent;
@@ -28,19 +27,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 {
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 Preferences PREFERENCES = getPreferences(GameSound.class);
private static final String ENABLED_PREF = "enabled"; //NON-NLS private static final String ENABLED_PREF = "enabled"; //NON-NLS
private static final String SOUND_VOLUME_PREF = "volume";
private float volume;
private AudioNode splashSound; private AudioNode splashSound;
private AudioNode shipDestroyedSound; private AudioNode shipDestroyedSound;
private AudioNode explosionSound; private AudioNode explosionSound;
private AudioNode rocketSound; private AudioNode shellFiredSound;
private BattleshipApp app;
/** /**
* Checks if sound is enabled in the preferences. * Checks if sound is enabled in the preferences.
@@ -82,13 +76,10 @@ public void setEnabled(boolean enabled) {
@Override @Override
public void initialize(AppStateManager stateManager, Application app) { public void initialize(AppStateManager stateManager, Application app) {
super.initialize(stateManager, app); super.initialize(stateManager, app);
this.app = (BattleshipApp) 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
rocketSound = loadSound(app, "Sound/Effects/rocket.wav"); shellFiredSound = loadSound(app, "Sound/Effects/missle.wav"); //NON-NLS
volume = PREFERENCES.getFloat(SOUND_VOLUME_PREF, 1.0f);
} }
/** /**
@@ -104,8 +95,7 @@ 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;
@@ -136,64 +126,20 @@ public void shipDestroyed() {
} }
/** /**
* Plays sound effect when a rocket starts * Plays sound effect when a shell has been fired.
*/ */
public void rocket() { public void shellFired() {
if (isEnabled() && rocketSound != null) if (isEnabled() && shellFiredSound != null)
rocketSound.playInstance(); shellFiredSound.playInstance();
}
/**
* this method sets the sound volume of the sounds
*
* @param volume the volume to be set to
*/
public void setSoundVolume(float volume) {
float mainVolume = app.getMainVolumeControl().getMainVolume();
float calculatedVolume = volume * mainVolume;
shipDestroyedSound.setVolume(calculatedVolume);
splashSound.setVolume(calculatedVolume);
explosionSound.setVolume(calculatedVolume);
this.volume = volume;
PREFERENCES.putFloat(SOUND_VOLUME_PREF, volume);
}
/**
* this method will be used if the main volume changes
*/
public void setSoundVolume() {
float mainVolume = app.getMainVolumeControl().getMainVolume();
shipDestroyedSound.setVolume(volume * mainVolume);
splashSound.setVolume(volume * mainVolume);
explosionSound.setVolume(volume * mainVolume);
rocketSound.setVolume(volume * mainVolume);
PREFERENCES.putFloat(SOUND_VOLUME_PREF, volume);
}
/**
* this method returns the sound
*
* @return
*/
public float getVolume(){
return volume;
} }
@Override @Override
public void receivedEvent(SoundEvent event) { public void receivedEvent(SoundEvent event) {
switch (event.sound()) { switch (event.sound()) {
case EXPLOSION : case EXPLOSION -> explosion();
explosion(); case SPLASH -> splash();
break; case DESTROYED_SHIP -> shipDestroyed();
case SPLASH : case SHELL_FIRED -> shellFired();
splash();
break;
case DESTROYED_SHIP:
shipDestroyed();
break;
case ROCKET_FIRED:
rocket();
break;
} }
} }
} }

View File

@@ -1,32 +0,0 @@
package pp.battleship.client;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import java.util.prefs.Preferences;
public class MainVolume {
private static final Preferences PREFS = Preferences.userNodeForPackage(MainVolume.class);
private static final String MAIN_VOLUME_PREFS = "MainVolume";
static final Logger LOGGER = System.getLogger(MainVolume.class.getName());
private float mainVolume;
private BattleshipApp app;
public MainVolume(BattleshipApp app) {
this.mainVolume = PREFS.getFloat(MAIN_VOLUME_PREFS, 1.0f);
this.app = app;
}
public void setMainVolume(float mainVolume) {
LOGGER.log(Level.DEBUG, "setMainVolume: mainVolume = {0}", mainVolume);
app.getBackgroundMusic().setVolume();
app.getStateManager().getState(GameSound.class).setSoundVolume();
this.mainVolume = mainVolume;
PREFS.putFloat(MAIN_VOLUME_PREFS, mainVolume);
}
public float getMainVolume() {
return mainVolume;
}
}

View File

@@ -22,6 +22,8 @@
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;
@@ -31,19 +33,13 @@
* 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;
private final Button loadButton = new Button(lookup("menu.map.load")); private final Button loadButton = new Button(lookup("menu.map.load"));
private final Button saveButton = new Button(lookup("menu.map.save")); private final Button saveButton = new Button(lookup("menu.map.save"));
private static final double SLIDER_DELTA = 0.1;
private static final double SLIDER_MIN_VALUE = 0.0;
private static final double SLIDER_MAX_VALUE = 2.0;
private final VersionedReference<Double> volumeRef; private final VersionedReference<Double> volumeRef;
private final VersionedReference<Double> soundVolumeRef;
private final VersionedReference<Double> mainVolumeRef;
/** /**
* Constructs the Menu dialog for the Battleship application. * Constructs the Menu dialog for the Battleship application.
@@ -55,24 +51,15 @@ public Menu(BattleshipApp app) {
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 Label(lookup("menu.main.volume"), new ElementId("label")));
Slider mainVolumeSlider = createSlider(app.getMainVolumeControl().getMainVolume());
addChild(mainVolumeSlider);
mainVolumeRef = mainVolumeSlider.getModel().createReference();
addChild(new Label(lookup("menu.sound.volume"), new ElementId("label")));
addChild(new Checkbox(lookup("menu.sound-enabled"), addChild(new Checkbox(lookup("menu.sound-enabled"),
new StateCheckboxModel(app, GameSound.class))); new StateCheckboxModel(app, GameSound.class)));
Slider soundSlider = createSlider(app.getStateManager().getState(GameSound.class).getVolume());
addChild(soundSlider);
soundVolumeRef = soundSlider.getModel().createReference();
addChild(new Label(lookup("menu.volume"), new ElementId("label"))); addChild(new Checkbox(lookup("menu.music-toggle"),
Checkbox musicToggle = new Checkbox(lookup("menu.music.toggle")); new StateCheckboxModel(app, BackgroundMusic.class)));
musicToggle.setChecked(app.getBackgroundMusic().isMusicEnabled());
musicToggle.addClickCommands(s -> toggleMusic()); Slider volumeSlider = new Slider();
addChild(musicToggle); volumeSlider.setModel(new DefaultRangedValueModel(0.0, 2.0, app.getStateManager().getState(BackgroundMusic.class).getVolume()));
Slider volumeSlider = createSlider(app.getBackgroundMusic().getVolume()); volumeSlider.setDelta(0.1f);
addChild(volumeSlider); addChild(volumeSlider);
volumeRef = volumeSlider.getModel().createReference(); volumeRef = volumeSlider.getModel().createReference();
@@ -87,72 +74,6 @@ public Menu(BattleshipApp app) {
update(); update();
} }
/**
* this method creates a slider to be used in the menu
*
* @param relativePosition the position of the regulator on the slider
* @return the creates slider
*/
private Slider createSlider(double relativePosition){
Slider slider = new Slider();
slider.setModel(new DefaultRangedValueModel(SLIDER_MIN_VALUE, SLIDER_MAX_VALUE, relativePosition));
slider.setDelta(SLIDER_DELTA);
return slider;
}
/**
* this method is used update the volume when there is a change in the slider
* @param tpf time per frame
*/
@Override
public void update(float tpf){
if(volumeRef.update()){
double newVolume = volumeRef.get();
adjustMusicVolume(newVolume);
}
else if (soundVolumeRef.update()) {
double newSoundVolume = soundVolumeRef.get();
adjustSoundVolume(newSoundVolume);
} else if (mainVolumeRef.update()) {
double newMainVolume = mainVolumeRef.get();
adjustMainVolume(newMainVolume);
}
}
/**
* this method adjusts the main volume
*
* @param newVolume the volume to be set as main volume
*/
private void adjustMainVolume(double newVolume) {
app.getMainVolumeControl().setMainVolume((float) newVolume);
}
/**
* this method adjust the volume for the background music
*
* @param volume is the double value of the volume
*/
private void adjustMusicVolume(double volume) {
app.getBackgroundMusic().setVolume((float) volume);
}
/**
* this method adjusts the volume for the sound
*
* @param volume is a double value of the sound volume
*/
private void adjustSoundVolume(double volume) {
app.getStateManager().getState(GameSound.class).setSoundVolume((float) volume);
}
/**
* this method 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.
*/ */
@@ -162,6 +83,28 @@ 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.
*/ */
@@ -196,8 +139,7 @@ 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());
} }
} }

View File

@@ -12,7 +12,6 @@
import com.simsilica.lemur.Label; import com.simsilica.lemur.Label;
import com.simsilica.lemur.TextField; import com.simsilica.lemur.TextField;
import com.simsilica.lemur.component.SpringGridLayout; import com.simsilica.lemur.component.SpringGridLayout;
import pp.battleship.client.server.BattleshipServer;
import pp.dialog.Dialog; import pp.dialog.Dialog;
import pp.dialog.DialogBuilder; import pp.dialog.DialogBuilder;
import pp.dialog.SimpleDialog; import pp.dialog.SimpleDialog;
@@ -32,6 +31,7 @@ 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 +53,9 @@ class NetworkDialog extends SimpleDialog {
host.setPreferredWidth(400f); host.setPreferredWidth(400f);
port.setSingleLine(true); port.setSingleLine(true);
Checkbox serverHost = new Checkbox(lookup("host.own.server")); Checkbox hostCheckbox = new Checkbox(lookup("host.own-server"));
serverHost.setChecked(false); hostCheckbox.setChecked(false);
serverHost.addClickCommands(s -> toggleServerHost()); hostCheckbox.addClickCommands(s -> hostServer = !hostServer);
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,12 +63,12 @@ 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(serverHost); input.addChild(hostCheckbox);
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 -> connect()) .setOkButton(lookup("button.connect"), d -> connectHostServer())
.setNoButton(lookup("button.cancel"), app::closeApp) .setNoButton(lookup("button.cancel"), app::closeApp)
.setOkClose(false) .setOkClose(false)
.setNoClose(false) .setNoClose(false)
@@ -79,54 +79,54 @@ class NetworkDialog extends SimpleDialog {
* Handles the action for the connect button in the connection dialog. * Handles the action for the connect button in the connection dialog.
* 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 connectServer() { private void connect() {
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"));
} }
} }
/** /**
* This method will start a server or just connect to one based on the boolean hostServer * 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 connect() { private void connectHostServer() {
if (hostServer) { if (hostServer) {
startServer(); startServer();
try { try {
Thread.sleep(1000); Thread.sleep(START_SERVER_DELAY);
} catch (InterruptedException e) { } catch (Exception e) {
LOGGER.log(Level.WARNING, e.getMessage(), e); LOGGER.log(Level.ERROR, "Server start failed", e); //NON-NLS
} }
connectServer(); connect();
} else { } else {
connectServer(); connect();
} }
} }
/** /**
* This method starts a server in a new thread * Starts the game server in a new thread.
* Logs an error if the server fails to start.
*/ */
private void startServer() { private void startServer() {
LOGGER.log(Level.INFO, "start server"); //NON-NLS
new Thread(() -> { new Thread(() -> {
try { try {
BattleshipServer battleshipServer = new BattleshipServer(Integer.parseInt(port.getText())); LOGGER.log(Level.INFO, "Starting server..."); //NON-NLS
battleshipServer.run(); BattleshipServer server = new BattleshipServer(Integer.parseInt(port.getText()));
LOGGER.log(Level.INFO, "Server started"); //NON-NLS
server.run();
} catch (Exception e) { } catch (Exception e) {
LOGGER.log(Level.ERROR, e.getMessage(), e); LOGGER.log(Level.ERROR, "Server start failed", e); //NON-NLS
} }
}).start(); }).start();
} }
private void toggleServerHost(){
hostServer = !hostServer;
}
/** /**
* Creates a dialog indicating that the connection is in progress. * Creates a dialog indicating that the connection is in progress.
*/ */
@@ -146,8 +146,7 @@ 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);
} }
} }
@@ -162,11 +161,9 @@ 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();
} }

View File

@@ -5,12 +5,23 @@
// (c) Mark Minas (mark.minas@unibw.de) // (c) Mark Minas (mark.minas@unibw.de)
//////////////////////////////////////// ////////////////////////////////////////
package pp.battleship.client.server; package pp.battleship.client;
import pp.battleship.message.client.ClientInterpreter; import pp.battleship.message.client.ClientInterpreter;
import pp.battleship.message.client.ClientMessage; 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) { record ReceivedMessage(ClientMessage message, int from) {
/**
* Processes the received message using the specified interpreter.
*
* @param interpreter the client interpreter
*/
void process(ClientInterpreter interpreter) { void process(ClientInterpreter interpreter) {
message.accept(interpreter, from); message.accept(interpreter, from);
} }

View File

@@ -1,179 +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;
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;
import java.util.Timer;
import java.util.TimerTask;
/**
* This class is used to handle the effects for impacts
*/
public class EffectHandler {
private final AssetManager assetManager;
static final Logger LOGGER = System.getLogger(EffectHandler.class.getName());
private Material particleMat;
/**
* the constructor is used to get the asset manager from the app
*
* @param app the main application
*/
public EffectHandler(Application app) {
assetManager = app.getAssetManager();
particleMat = new Material(assetManager, "Common/MatDefs/Misc/Particle.j3md");
}
/**
* creates a new HitEffect
*
* @param battleshipNode the node of the ship
* @param shot the shot which triggered the effect
*/
public void createHitEffect(Node battleshipNode, Shot shot) {
createFieryEffect(battleshipNode,shot, "HitEffect", 30, 0.45f, 0.1f, -0.5f, 1f , 2f, false);
}
/**
* creates a new FireEffect
*
* @param battleshipNode the node of the ship
* @param shot the shot which triggered the effect
*/
public void createFireEffect(Node battleshipNode, Shot shot) {
createFieryEffect(battleshipNode, shot, "FireEffect", 30, 0.1f, 0.05f, -0.9f, 1f , 2f, true);
}
/**
* creates a fiery type hit effect
*
* @param battleshipNode the ship to which the effect should be attached
* @param shot the shot that triggered the effect
* @param name the name of the particle emitter
* @param numOfParticle the overall numberOfParticles
* @param startSize the start size of the particles
* @param endSize the end size of the particles
* @param gravity the gravity of the particles
* @param lowLife the lowest lifetime of a particle
* @param highLife the maximum lifetime of a particle
* @param loop if the effect should be looped
*/
public void createFieryEffect(Node battleshipNode, Shot shot, String name, int numOfParticle, float startSize, float endSize, float gravity,
float lowLife, float highLife, boolean loop) {
ParticleEmitter fieryEffect = new ParticleEmitter(name, Type.Triangle, numOfParticle);
fieryEffect.setMaterial(particleMat);
fieryEffect.setImagesX(2);
fieryEffect.setImagesY(2);
fieryEffect.setStartColor(ColorRGBA.Orange);
fieryEffect.setEndColor(ColorRGBA.Red);
fieryEffect.getParticleInfluencer().setInitialVelocity(new Vector3f(0,1,0));
fieryEffect.setStartSize(startSize);
fieryEffect.setEndSize(endSize);
fieryEffect.setGravity(0, gravity, 0);
fieryEffect.setLowLife(lowLife);
fieryEffect.setHighLife(highLife);
if(!loop) {
fieryEffect.setLocalTranslation(shot.getY() + 0.5f, 0 , shot.getX() + 0.5f);
fieryEffect.setParticlesPerSec(0);
fieryEffect.emitAllParticles();
} else {
fieryEffect.setLocalTranslation(shot.getY() + 0.5f, 0 , shot.getX() + 0.5f);
fieryEffect.getLocalTranslation().subtractLocal(battleshipNode.getLocalTranslation());
fieryEffect.setParticlesPerSec(10);
}
battleshipNode.attachChild(fieryEffect);
LOGGER.log(Level.DEBUG, "Created {0} at {1}", name ,fieryEffect.getLocalTranslation().toString());
fieryEffect.addControl(new EffectControl(fieryEffect, battleshipNode));
}
/**
* This method is used to create a miss effect at a certain location
*/
public ParticleEmitter createMissEffect(Shot shot) {
ParticleEmitter missEffect = new ParticleEmitter("MissEffect", Type.Triangle, 15);
missEffect.setMaterial(particleMat);
missEffect.setImagesX(2);
missEffect.setImagesY(2);
missEffect.setStartColor(ColorRGBA.Blue); // Water color
missEffect.setEndColor(ColorRGBA.Cyan);
missEffect.getParticleInfluencer().setInitialVelocity(new Vector3f(0, 1, 0));
missEffect.setStartSize(0.3f);
missEffect.setEndSize(0.05f);
missEffect.setGravity(0, -0.1f, 0);
missEffect.setLowLife(0.5f);
missEffect.setHighLife(1.5f);
missEffect.setParticlesPerSec(0);
missEffect.setLocalTranslation(shot.getY() + 0.5f, 0 , shot.getX() + 0.5f);
missEffect.emitAllParticles();
missEffect.addControl(new EffectControl(missEffect));
return missEffect;
}
/**
* This inner class is used to control the effects
*/
private static class EffectControl extends AbstractControl {
private final ParticleEmitter emitter;
private final Node parentNode;
/**
* this constructor is used to when the effect should be attached to a specific 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;
}
/**
* This constructor is used when the effect shouldn't be attached to
* a specific node
*
* @param emitter the Particle emitter to be controlled
*/
public EffectControl(ParticleEmitter emitter){
this.emitter = emitter;
this.parentNode = null;
}
/**
* The method which 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

@@ -143,6 +143,10 @@ 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

@@ -7,16 +7,19 @@
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 java.lang.System.Logger;
import static com.jme3.material.Materials.UNSHADED;
/** /**
* Synchronizes the visual representation of the ship map with the game model. * Synchronizes the visual representation of the ship map with the game model.
@@ -29,10 +32,6 @@ 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 SHELL_DEPTH = 8f;
private static final float SHELL_SIZE = 0.75f;
private static final float SHELL_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;
@@ -44,8 +43,6 @@ 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.
@@ -67,7 +64,6 @@ public MapViewSynchronizer(MapView view) {
*/ */
@Override @Override
public Spatial visit(Shot shot) { public Spatial visit(Shot shot) {
LOGGER.log(Logger.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);
@@ -120,24 +116,22 @@ public Spatial visit(Battleship ship) {
} }
/** /**
* this method will create a representation of a shell in the map * Creates a visual representation of a shell on the map.
* The shell is represented as a black ellipse.
* *
* @param shell the Shell element to visit * @param shell the Shell object representing the shell in the model
* @return the node the representation is attached to * @return a Spatial representing the shell on the map
*/ */
@Override @Override
public Spatial visit(Shell shell) { public Spatial visit(Shell shell) {
LOGGER.log(Logger.Level.DEBUG, "Visiting {0}", shell); Geometry ellipse = new Geometry("ellipse", new Sphere(50, 50, MapView.getFieldSize() / 2 * 0.8f));
final Node shellNode = new Node("shell"); Material mat = new Material(view.getApp().getAssetManager(), UNSHADED); //NON-NLS
final Position p1 = view.modelToView(shell.getX(), shell.getY()); mat.getAdditionalRenderState().setBlendMode(RenderState.BlendMode.Alpha);
final Position p2 = view.modelToView(shell.getX() + SHELL_SIZE, shell.getY() + SHELL_SIZE); mat.getAdditionalRenderState().setFaceCullMode(RenderState.FaceCullMode.Off);
mat.setColor("Color", ColorRGBA.Black);
final Position startPosition = view.modelToView(SHELL_CENTERED_IN_MAP_GRID, SHELL_CENTERED_IN_MAP_GRID); ellipse.setMaterial(mat);
ellipse.addControl(new ShellMapControl(view, shell));
shellNode.attachChild(view.getApp().getDraw().makeRectangle(startPosition.getX(), startPosition.getY(), SHELL_DEPTH, p2.getX() - p1.getX(), p2.getY() - p1.getY(), ColorRGBA.Black)); return ellipse;
shellNode.setLocalTranslation(startPosition.getX(), startPosition.getY(), SHELL_DEPTH);
shellNode.addControl(new ShellMapControl(p1, view.getApp(), new IntPoint(shell.getX(), shell.getY())));
return shellNode;
} }
/** /**
@@ -151,7 +145,6 @@ 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

@@ -7,12 +7,18 @@
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.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.Node; import com.jme3.scene.Node;
import com.jme3.scene.Spatial; import com.jme3.scene.Spatial;
import com.jme3.scene.shape.Box;
import pp.battleship.client.BattleshipApp; import pp.battleship.client.BattleshipApp;
import pp.battleship.model.*; import pp.battleship.model.*;
@@ -28,15 +34,18 @@
*/ */
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"; private static final String KING_GEORGE_V_MODEL = "Models/KingGeorgeV/KingGeorgeV.j3o"; //NON-NLS
private static final String UBOAT = "Models/UBoat/14084_WWII_Ship_German_Type_II_U-boat_v2_L1.obj"; //NON-NLS private static final String DESTROYER_MODEL = "Models/Destroyer/Destroyer.j3o"; //NON-NLS
private static final String BATTLE_SHIP_MODERN = "Models/BattleShipModern/Destroyer.j3o"; private static final String DESTROYER_TEXTURE = "Models/Destroyer/BattleshipC.jpg"; //NON-NLS
private static final String BATTLE_SHIP_MODERN_TEXTURE = "Models/BattleShipModern/BattleshipC.jpg"; private static final String TYPE_II_UBOAT_MODEL = "Models/TypeIIUboat/TypeIIUboat.j3o"; //NON-NLS
private static final String PATROL_BOAT = "Models/PatrolBoat/12219_boat_v2_L2.obj"; private static final String TYPE_II_UBOAT_TEXTURE = "Models/TypeIIUboat/Type_II_U-boat_diff.jpg"; //NON-NLS
private static final String SHELL_ROCKET = "Models/Rocket/Rocket.obj"; private static final String ATLANTICA_MODEL = "Models/Atlantica/Atlantica.j3o"; //NON-NLS
private static final String ROCKET = "Models/Rocket/Rocket.j3o"; //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"; private static final String SHELL = "shell"; //NON-NLS
private final EffectHandler effectHandler; private static final ColorRGBA BOX_COLOR = ColorRGBA.Gray;
private final ShipMap map; private final ShipMap map;
private final BattleshipApp app; private final BattleshipApp app;
@@ -52,7 +61,6 @@ 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;
effectHandler = new EffectHandler(app);
addExisting(); addExisting();
} }
@@ -66,7 +74,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) : effectHandler.createMissEffect(shot); return shot.isHit() ? handleHit(shot) : handleMiss(shot);
} }
/** /**
@@ -81,12 +89,122 @@ 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");
effectHandler.createHitEffect(shipNode, shot); final ParticleEmitter debris = createDebrisEffect(shot);
effectHandler.createFireEffect(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.
* The shell is represented as a node with a model attached to it.
* The node is then positioned and controlled by a {@link ShellControl}.
*
* @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(SHELL);
node.attachChild(createShell());
node.setLocalTranslation(shell.getY() + 0.5f, 10f, shell.getX() + 0.5f);
node.addControl(new ShellControl());
return node;
}
/**
* Creates a graphical representation of a shell.
*
* @return the spatial representing the shell
*/
private Spatial createShell() {
final Spatial model = app.getAssetManager().loadModel(ROCKET);
model.scale(0.0025f);
model.rotate(PI, 0f, 0f);
model.setShadowMode(ShadowMode.CastAndReceive);
return model;
}
/** /**
* Visits a {@link Battleship} and creates a graphical representation of it. * Visits a {@link Battleship} and creates a graphical representation of it.
* The representation is either a 3D model or a simple box depending on the * The representation is either a 3D model or a simple box depending on the
@@ -107,42 +225,6 @@ public Spatial visit(Battleship ship) {
return node; return node;
} }
/**
* Visits a shell and creates a graphical representation
*
* @param shell the Shell element to visit
* @return the node containing the graphical representation
*/
@Override
public Spatial visit(Shell shell){
final Node node = new Node(SHELL);
node.attachChild(createRocket());
final float x = shell.getY();
final float z = shell.getX();
node.setLocalTranslation(x + 0.5f, 10f, z + 0.5f);
ShellControl shellControl = new ShellControl(shell, app);
node.addControl(shellControl);
return node;
}
/**
* creates the spatial representation of a rocket
*
* @return a spatial the rocket
*/
private Spatial createRocket() {
final Spatial model = app.getAssetManager().loadModel(SHELL_ROCKET);
model.rotate(PI, 0f, 0f);
model.scale(0.002f);
model.setShadowMode(ShadowMode.CastAndReceive);
model.move(0, 0, 0);
return model;
}
/** /**
* 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.
@@ -152,14 +234,48 @@ private Spatial createRocket() {
*/ */
private Spatial createShip(Battleship ship) { private Spatial createShip(Battleship ship) {
return switch (ship.getLength()) { return switch (ship.getLength()) {
case 1 -> createPatrolBoat(ship); case 1 -> createVessel(ship);
case 2 -> createModernBattleship(ship); case 2 -> createSubmarine(ship);
case 3 -> createUBoat(ship); case 3 -> createDestroyer(ship);
case 4 -> createBattleship(ship); case 4 -> createBattleship(ship);
default -> throw new IllegalArgumentException("Ship length must be between 1 and 4 units long"); default -> createBox(ship);
}; };
} }
/**
* Creates a simple box to represent a battleship that is not of the "King George V" type.
*
* @param ship the battleship to be represented
* @return the geometry representing the battleship as a box
*/
private Spatial createBox(Battleship ship) {
final Box box = new Box(0.5f * (ship.getMaxY() - ship.getMinY()) + 0.3f,
0.3f,
0.5f * (ship.getMaxX() - ship.getMinX()) + 0.3f);
final Geometry geometry = new Geometry(SHIP, box);
geometry.setMaterial(createColoredMaterial());
geometry.setShadowMode(ShadowMode.CastAndReceive);
return geometry;
}
/**
* Creates a new {@link Material} with the specified color.
* If the color includes transparency (i.e., alpha value less than 1),
* the material's render state is set to use alpha blending, allowing for
* semi-transparent rendering.
*
* @return a {@link Material} instance configured with the specified color and,
* if necessary, alpha blending enabled.
*/
private Material createColoredMaterial() {
final Material material = new Material(app.getAssetManager(), UNSHADED);
if (SeaSynchronizer.BOX_COLOR.getAlpha() < 1f)
material.getAdditionalRenderState().setBlendMode(BlendMode.Alpha);
material.setColor(COLOR, SeaSynchronizer.BOX_COLOR);
return material;
}
/** /**
* Creates a detailed 3D model to represent a "King George V" battleship. * Creates a detailed 3D model to represent a "King George V" battleship.
* *
@@ -177,58 +293,62 @@ private Spatial createBattleship(Battleship ship) {
} }
/** /**
* creates a detailed 3D model to represent an UBoat * Creates a detailed 3D model to represent a destroyer battleship.
* *
* @param ship the ship to be represented * @param ship the battleship to be represented
* @return the spatial representing the Uboat * @return the spatial representing the destroyer battleship
*/ */
private Spatial createUBoat(Battleship ship) { private Spatial createDestroyer(Battleship ship) {
final Spatial model = app.getAssetManager().loadModel(UBOAT); final Spatial model = app.getAssetManager().loadModel(DESTROYER_MODEL);
model.rotate(-HALF_PI, calculateRotationAngle(ship.getRot()), 0f);
model.scale(0.5f);
model.setShadowMode(ShadowMode.CastAndReceive);
model.move(0, -0.3f, 0);
return model;
}
/**
* creates a detailed 3D model to represent the modern battleship
*
* @param ship the ship to be represented
* @return the spatial representing the Modern Battleship
*/
private Spatial createModernBattleship(Battleship ship) {
final Spatial model = app.getAssetManager().loadModel(BATTLE_SHIP_MODERN);
Material mat = new Material(app.getAssetManager(), UNSHADED); Material mat = new Material(app.getAssetManager(), UNSHADED);
mat.setTexture("ColorMap", app.getAssetManager().loadTexture(BATTLE_SHIP_MODERN_TEXTURE)); mat.setTexture("ColorMap", app.getAssetManager().loadTexture(DESTROYER_TEXTURE));
mat.getAdditionalRenderState().setBlendMode(RenderState.BlendMode.Off); mat.getAdditionalRenderState().setBlendMode(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()), 0f);
model.scale(0.08f); model.scale(0.1f);
model.setLocalTranslation(0f, 0.2f, 0f); model.setLocalTranslation(0f, 0.25f, 0f);
model.setShadowMode(ShadowMode.CastAndReceive); model.setShadowMode(ShadowMode.CastAndReceive);
return model; return model;
} }
/** /**
* creates a detailed 3D model to represent the patrol boat * Creates a detailed 3D model to represent a Type II U-boat submarine.
* *
* @param ship the ship to be represented * @param ship the battleship to be represented
* @return the spatial representing the patrol boat * @return the spatial representing the Type II U-boat submarine
*/ */
private Spatial createPatrolBoat(Battleship ship) { private Spatial createSubmarine(Battleship ship) {
final Spatial model = app.getAssetManager().loadModel(PATROL_BOAT); final Spatial model = app.getAssetManager().loadModel(TYPE_II_UBOAT_MODEL);
Material mat = new Material(app.getAssetManager(), UNSHADED);
mat.setTexture("ColorMap", app.getAssetManager().loadTexture(TYPE_II_UBOAT_TEXTURE));
model.setMaterial(mat);
model.rotate(-HALF_PI, calculateRotationAngle(ship.getRot()), 0f); model.rotate(-HALF_PI, calculateRotationAngle(ship.getRot()), 0f);
model.scale(0.0005f); model.scale(0.25f);
model.getLocalTranslation().addLocal(0f, -0.15f, 0f);
model.setShadowMode(ShadowMode.CastAndReceive);
return model;
}
/**
* Creates a detailed 3D model to represent a vessel.
*
* @param ship the battleship to be represented
* @return the spatial representing the vessel
*/
private Spatial createVessel(Battleship ship) {
final Spatial model = app.getAssetManager().loadModel(ATLANTICA_MODEL);
model.rotate(-HALF_PI, calculateRotationAngle(ship.getRot()), 0f);
model.scale(0.0003f);
model.getLocalTranslation().addLocal(0f, -0.05f, 0f);
model.setShadowMode(ShadowMode.CastAndReceive); model.setShadowMode(ShadowMode.CastAndReceive);
return model; return model;

View File

@@ -1,65 +1,42 @@
package pp.battleship.client.gui; package pp.battleship.client.gui;
import com.jme3.math.Quaternion;
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.AnimationEndMessage;
import pp.battleship.model.IntPoint;
import pp.battleship.model.Shell;
import java.lang.System.Logger;
/** /**
* This class controls a 3D representation of a shell * Controls the movement and rotation of a shell in the game.
* 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 Shell shell; private final static float SHELL_SPEED = 7.5f;
private final BattleshipApp app; private final static float SHELL_ROTATION_SPEED = 0.5f;
private final static float MIN_HEIGHT = 0.7f;
private static final float MOVE_SPEED = 8.0f;
static final Logger LOGGER = System.getLogger(ShellControl.class.getName());
/** /**
* Constructor to create a new ShellControl object * Updates the shell's position and rotation.
* If the shell's Y-coordinate is less than or equal to 1.0, it is detached from its parent node.
* *
* @param shell the shell to be displayed * @param tpf time per frame, used to ensure consistent movement speed across different frame rates
* @param app the main application
*/
public ShellControl(Shell shell, BattleshipApp app) {
this.shell = shell;
this.app = app;
}
/**
* this method moves the representation towards it destination
* and deletes it if it reaches its target
*
* @param tpf time per frame (in seconds)
*/ */
@Override @Override
protected void controlUpdate(float tpf) { protected void controlUpdate(float tpf) {
spatial.move(0, -MOVE_SPEED * tpf, 0); spatial.move(0, -SHELL_SPEED * tpf, 0);
spatial.rotate(0f, 0.05f, 0f); spatial.rotate(0, SHELL_ROTATION_SPEED, 0);
//LOGGER.log(System.Logger.Level.DEBUG, "moved rocket {0}", spatial.getLocalTranslation().getY()); if (spatial.getLocalTranslation().getY() <= MIN_HEIGHT) {
if (spatial.getLocalTranslation().getY() <= 1.5){
spatial.getParent().detachChild(spatial); spatial.getParent().detachChild(spatial);
app.getGameLogic().send(new AnimationEndMessage(new IntPoint(shell.getX(), shell.getY())));
} }
} }
/** /**
* This method is called during the rendering phase, but it does not perform any * Renders the shell. This method is currently not used.
* 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 rm the RenderManager
* @param vp the ViewPort being rendered (not null) * @param vp the ViewPort
*/ */
@Override @Override
protected void controlRender(RenderManager rm, ViewPort vp) { protected void controlRender(RenderManager rm, ViewPort vp) {
// nothing to do here
} }
} }

View File

@@ -4,60 +4,79 @@
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.model.Shell;
import pp.battleship.message.client.AnimationEndMessage;
import pp.battleship.model.IntPoint;
import pp.util.Position; import pp.util.Position;
/** import java.lang.System.Logger;
* This class controls a ShellMap element import java.lang.System.Logger.Level;
*/
public class ShellMapControl extends AbstractControl {
private final Position position;
private final IntPoint pos;
private static final Vector3f VECTOR = new Vector3f();
private final BattleshipApp app;
/** /**
* constructs a new ShellMapControl object * Controls the animation of a shell in the map view.
* * This class handles the movement of a shell from its starting position to its target position
* @param position the position where the shell should move to on the map * using linear interpolation over a specified duration.
* @param app the main application
* @param pos the position the then to render shot goes to
*/ */
public ShellMapControl(Position position, BattleshipApp app, IntPoint pos) { public class ShellMapControl extends AbstractControl {
super(); private static final Logger LOGGER = System.getLogger(ShellMapControl.class.getName());
this.position = position;
this.pos = pos; /**
this.app = app; * The duration of the shell animation in seconds.
VECTOR.set(new Vector3f(position.getX(), position.getY(), 0)); */
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 shell the shell to be controlled
*/
public ShellMapControl(MapView view, Shell shell) {
Vector3f endPos = new Vector3f(shell.getX(), 0, shell.getY());
this.endPos = view.modelToView(endPos.x, endPos.z);
LOGGER.log(Level.DEBUG, "ShellMapControl created with endPos: " + this.endPos);
} }
/** /**
* this method moves the shell representation to its correct spot and removes it after * Updates the position of the shell in the view with linear interpolation.
* it arrived at its destination * This method is called during the update phase.
* *
* @param tpf time per frame (in seconds) * @param tpf the time per frame
*/ */
@Override @Override
protected void controlUpdate(float tpf) { protected void controlUpdate(float tpf) {
spatial.move(VECTOR.mult(tpf)); // adjust speed by changing the multiplier
if (spatial.getLocalTranslation().getX() >= position.getX() && spatial.getLocalTranslation().getY() >= position.getY()) { progress += tpf * ANIMATION_DURATION;
spatial.getParent().detachChild(spatial);
app.getGameLogic().send(new AnimationEndMessage(pos)); // progress is between 0 and 1
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 rendering phase, but it does not perform any * This method is called during the render phase.
* operations in this implementation as the control only influences the spatial's * Currently, it does nothing.
* transformation, not its rendering process.
* *
* @param rm the RenderManager rendering the controlled Spatial (not null) * @param rm the RenderManager
* @param vp the ViewPort being rendered (not null) * @param vp the ViewPort
*/ */
@Override @Override
protected void controlRender(RenderManager rm, ViewPort vp) { protected void controlRender(RenderManager rm, ViewPort vp) {
// nothing to do here
} }
} }

View File

@@ -14,9 +14,6 @@
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;
@@ -46,27 +43,14 @@ class ShipControl extends AbstractControl {
*/ */
private final Quaternion pitch = new Quaternion(); private final Quaternion pitch = new Quaternion();
/**
* the speed at which ships sink
*/
private static final float SINKING_SPEED = -0.05f;
/**
* the threshold when ships should be removed from the scene if they sink below the value
*/
private static final float SHIP_SINKING_REMOVE_THRESHOLD = -0.6f;
/** /**
* 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;
/** private final Battleship ship;
* The ship to be controlled
*/
private final Battleship battleship;
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.
@@ -76,8 +60,6 @@ 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) {
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;
@@ -85,14 +67,15 @@ 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 = battleship.getLength() * 2f; cycle = ship.getLength() * 2f;
amplitude = 5f * DEG_TO_RAD / ship.getLength(); amplitude = 5f * DEG_TO_RAD / ship.getLength();
this.ship = ship;
} }
/** /**
* Updates the ship's pitch oscillation each frame. The ship's pitch is adjusted * 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. * to create a continuous tilting motion, simulating the effect of waves.
* And lets the ship sink if it is destroyed and removes it from the scene when it has completely sunk
* *
* @param tpf time per frame (in seconds), used to calculate the new pitch angle * @param tpf time per frame (in seconds), used to calculate the new pitch angle
*/ */
@@ -101,12 +84,15 @@ 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;
if (battleship.isDestroyed() && spatial.getLocalTranslation().getY() <= SHIP_SINKING_REMOVE_THRESHOLD) { // Handle ship sinking by moving it downwards
LOGGER.log(Level.INFO, "Ship removed {0}", spatial.getName()); if (ship.isDestroyed()) {
if (spatial.getLocalTranslation().getY() < SINKING_HEIGHT) {
spatial.getParent().detachChild(spatial); spatial.getParent().detachChild(spatial);
} else if (battleship.isDestroyed()) {
spatial.move(0, SINKING_SPEED * tpf, 0);
} else { } else {
spatial.move(0, -tpf * 0.1f, 0);
}
}
// Update the time within the oscillation cycle // Update the time within the oscillation cycle
time = (time + tpf) % cycle; time = (time + tpf) % cycle;
@@ -120,8 +106,6 @@ protected void controlUpdate(float tpf) {
spatial.setLocalRotation(pitch); spatial.setLocalRotation(pitch);
} }
}
/** /**
* This method is called during the rendering phase, but it does not perform any * 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 * operations in this implementation as the control only influences the spatial's

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

@@ -1,3 +0,0 @@
based on
https://opengameart.org/content/boss-battle-2-symphonic-metal
License: CC0 (public domain)

View File

@@ -1,3 +0,0 @@
based on
https://opengameart.org/content/game-over-instrumental
License: CC0 (public domain)

View File

@@ -1,3 +0,0 @@
based on
https://opengameart.org/content/victory-fanfare-short
License: CC0 (public domain)

View File

@@ -1,3 +0,0 @@
based on
https://opengameart.org/content/dark-intro
License: CC0 (public domain)

View File

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

@@ -1,74 +1,98 @@
package pp.battleship.game.client; package pp.battleship.game.client;
import pp.battleship.message.client.AnimationMessage;
import pp.battleship.message.server.EffectMessage; import pp.battleship.message.server.EffectMessage;
import pp.battleship.message.server.SwitchBattleState; import pp.battleship.model.Battleship;
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;
/**
* Represents the state of the game during an animation sequence.
* 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 {
private boolean myTurn; /**
* Progress of the current animation, ranging from 0 to 1.
*/
private float animationProgress = 0;
/** /**
* creates an object of AnimationState * Duration of the animation in seconds.
*
* @param logic the client logic
* @param myTurn a boolean containing if it is the clients turn
* @param position the position a shell should be created
*/ */
public AnimationState(ClientGameLogic logic, boolean myTurn, IntPoint position) { 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 msg the effect message received from the server
* @param shell the shell involved in the animation
*/
public AnimationState(ClientGameLogic logic, EffectMessage msg, Shell shell) {
super(logic); super(logic);
logic.playMusic(Music.BATTLE_THEME); this.msg = msg;
this.myTurn = myTurn; this.shell = shell;
if(myTurn) {
logic.getOpponentMap().add(new Shell(position));
}else {
logic.getOwnMap().add(new Shell(position));
logic.playSound(Sound.ROCKET_FIRED);
}
} }
/** /**
* This method makes sure the client renders the correct view * Ends the animation state and transitions to the next state:<br>
* * - Plays the appropriate sound.<br>
* @return true * - 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`.
*/ */
@Override public void endState() {
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(System.Logger.Level.INFO, "report effect: {0}", msg); //NON-NLS
playSound(msg); playSound(msg);
myTurn = msg.isMyTurn();
logic.setInfoText(msg.getInfoTextKey());
affectedMap(msg).add(msg.getShot()); affectedMap(msg).add(msg.getShot());
if (destroyedOpponentShip(msg)) { affectedMap(msg).remove(shell);
if (destroyedOpponentShip(msg))
logic.getOpponentMap().add(msg.getDestroyedShip()); logic.getOpponentMap().add(msg.getDestroyedShip());
}
logic.send(new AnimationMessage());
if (msg.isGameOver()) { if (msg.isGameOver()) {
msg.getRemainingOpponentShips().forEach(logic.getOpponentMap()::add); for (Battleship ship : msg.getRemainingOpponentShips()) {
logic.setState(new GameOverState(logic, msg.isGameLost())); 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()));
} }
} }
/** /**
* this method is used to change the client to the battle state again * Checks if the battle state should be shown.
* *
* @param msg the message to process * @return true if the battle state should be shown, false otherwise
*/ */
@Override @Override
public void receivedSwitchBattleState(SwitchBattleState msg) { public boolean showBattle() {
logic.setState(new BattleState(logic, msg.isTurn())); return true;
} }
/** /**
@@ -87,6 +111,7 @@ 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();
} }
@@ -105,4 +130,30 @@ 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

@@ -8,9 +8,11 @@
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.AnimationStartMessage; import pp.battleship.message.server.EffectMessage;
import pp.battleship.model.IntPoint; import pp.battleship.model.IntPoint;
import pp.battleship.notification.Music; import pp.battleship.model.Shell;
import pp.battleship.model.ShipMap;
import pp.battleship.notification.Sound;
/** /**
* 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.
@@ -26,20 +28,24 @@ class BattleState extends ClientState {
*/ */
public BattleState(ClientGameLogic logic, boolean myTurn) { public BattleState(ClientGameLogic logic, boolean myTurn) {
super(logic); super(logic);
logic.playMusic(Music.BATTLE_THEME);
this.myTurn = myTurn; this.myTurn = myTurn;
} }
/** /**
* This method makes sure the client renders the correct view * Checks if the battle state should be shown.
* *
* @return true * @return true if the battle state should be shown, false otherwise
*/ */
@Override @Override
public boolean showBattle() { public boolean showBattle() {
return true; return true;
} }
/**
* Handles a click on the opponent's map.
*
* @param pos the position where the click occurred
*/
@Override @Override
public void clickOpponentMap(IntPoint pos) { public void clickOpponentMap(IntPoint pos) {
if (!myTurn) if (!myTurn)
@@ -48,8 +54,32 @@ else if (logic.getOpponentMap().isValid(pos))
logic.send(new ShootMessage(pos)); logic.send(new ShootMessage(pos));
} }
/**
* Reports the effect of a shot based on the server message.
*
* @param msg the message containing the effect of the shot
*/
@Override @Override
public void receivedAnimationStart(AnimationStartMessage msg){ public void receivedEffect(EffectMessage msg) {
logic.setState(new AnimationState(logic, msg.isMyTurn(), msg.getPosition())); ClientGameLogic.LOGGER.log(System.Logger.Level.INFO, "report effect: {0}", msg); //NON-NLS
// Update turn and info text
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

@@ -8,19 +8,14 @@
package pp.battleship.game.client; package pp.battleship.game.client;
import pp.battleship.message.client.ClientMessage; import pp.battleship.message.client.ClientMessage;
import pp.battleship.message.server.*; import pp.battleship.message.server.EffectMessage;
import pp.battleship.message.server.GameDetails;
import pp.battleship.message.server.ServerInterpreter;
import pp.battleship.message.server.StartBattleMessage;
import pp.battleship.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.ClientStateEvent; import pp.battleship.notification.*;
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;
@@ -225,26 +220,6 @@ public void received(EffectMessage msg) {
state.receivedEffect(msg); state.receivedEffect(msg);
} }
/**
* Reports that the client should start an animation
*
* @param msg the AnimationStartMessage received
*/
@Override
public void received(AnimationStartMessage msg) {
state.receivedAnimationStart(msg);
}
/**
* Reports that the client should move to the battle state
*
* @param msg the SwitchBattleState received
*/
@Override
public void received(SwitchBattleState msg) {
state.receivedSwitchBattleState(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.
* *
@@ -278,9 +253,9 @@ public void playSound(Sound sound) {
} }
/** /**
* Emits an event to play the specified music * Emits an event to play the specified music.
* *
* @param music the music to be played * @param music the music to be played.
*/ */
public void playMusic(Music music) { public void playMusic(Music music) {
notifyListeners(new MusicEvent(music)); notifyListeners(new MusicEvent(music));
@@ -332,7 +307,7 @@ public void saveMap(File file) throws IOException {
* *
* @param msg the message to be sent * @param msg the message to be sent
*/ */
public void send(ClientMessage msg) { 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

View File

@@ -7,7 +7,9 @@
package pp.battleship.game.client; package pp.battleship.game.client;
import pp.battleship.message.server.*; import pp.battleship.message.server.EffectMessage;
import pp.battleship.message.server.GameDetails;
import pp.battleship.message.server.StartBattleMessage;
import pp.battleship.model.IntPoint; import pp.battleship.model.IntPoint;
import java.io.File; import java.io.File;
@@ -163,24 +165,6 @@ 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 the client should start an animation
*
* @param msg the AnimationStartMessage received
*/
void receivedAnimationStart(AnimationStartMessage msg){
ClientGameLogic.LOGGER.log(Level.ERROR, "receivedEffect not allowed in {0}", getName());
}
/**
* Reports that the client should move to the battle state
*
* @param msg the SwitchBattleState received
*/
void receivedSwitchBattleState(SwitchBattleState msg){
ClientGameLogic.LOGGER.log(Level.ERROR, "receivedSwitchBattleState not allowed in {0}", getName());
}
/** /**
* Loads a map from the specified file. * Loads a map from the specified file.
* *

View File

@@ -16,11 +16,9 @@
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;
@@ -59,7 +57,7 @@ public boolean showEditor() {
*/ */
@Override @Override
public void movePreview(IntPoint pos) { public void movePreview(IntPoint pos) {
LOGGER.log(Level.DEBUG, "move preview to {0}", pos); //NON-NLS ClientGameLogic.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);
@@ -74,7 +72,7 @@ public void movePreview(IntPoint pos) {
*/ */
@Override @Override
public void clickOwnMap(IntPoint pos) { public void clickOwnMap(IntPoint pos) {
LOGGER.log(Level.DEBUG, "click at {0} in own map", pos); //NON-NLS ClientGameLogic.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);
@@ -114,8 +112,7 @@ 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);
} }
@@ -128,7 +125,7 @@ private void placeShip(IntPoint cursor) {
*/ */
@Override @Override
public void clickHarbor(IntPoint pos) { public void clickHarbor(IntPoint pos) {
LOGGER.log(Level.DEBUG, "click at {0} in harbor", pos); //NON-NLS ClientGameLogic.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) {
@@ -138,8 +135,7 @@ 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);
@@ -155,7 +151,7 @@ else if (shipAtCursor != null) {
*/ */
@Override @Override
public void rotateShip() { public void rotateShip() {
LOGGER.log(Level.DEBUG, "pushed rotate"); //NON-NLS ClientGameLogic.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);
@@ -241,9 +237,8 @@ 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"));
else if (!checkMapToLoad(dto)) { if (!validMap(dto))
throw new IOException(lookup("ships.dont.fit.the.map")); throw new IOException(lookup("map.invalid"));
}
ownMap().clear(); ownMap().clear();
dto.getShips().forEach(ownMap()::add); dto.getShips().forEach(ownMap()::add);
harbor().clear(); harbor().clear();
@@ -251,40 +246,6 @@ else if (!checkMapToLoad(dto)) {
selectedInHarbor = null; selectedInHarbor = null;
} }
/**
* This method is used to check if the loaded map is correct
*
* @param dto the data transfer object to check
* @return boolean if map is correct or not
*/
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.
* *
@@ -304,4 +265,70 @@ 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

@@ -7,8 +7,6 @@
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.
*/ */
@@ -18,13 +16,8 @@ class GameOverState extends ClientState {
* *
* @param logic the client game logic * @param logic the client game logic
*/ */
GameOverState(ClientGameLogic logic, boolean lost) { GameOverState(ClientGameLogic logic) {
super(logic); super(logic);
if (lost){
logic.playMusic(Music.GAME_OVER_THEME_L);
} else {
logic.playMusic(Music.GAME_OVER_THEME_V);
}
} }
/** /**

View File

@@ -9,6 +9,7 @@
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;
@@ -38,17 +39,19 @@ 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);
} }
/** /**
* This method will revert the client from wait state to editor state * Handles the GameDetails message received from the server.
* in case a wrong map was submitted * If the map is invalid, the editor state is set.
* *
* @param details the game details including map size and ships * @param msg the GameDetails message received
*/ */
@Override @Override
public void receivedGameDetails(GameDetails details){ public void receivedGameDetails(GameDetails msg) {
logic.setInfoText("invalid.map"); ClientGameLogic.LOGGER.log(Level.WARNING, "Invalid Map"); //NON-NLS
logic.setInfoText("map.invalid");
logic.setState(new EditorState(logic)); logic.setState(new EditorState(logic));
} }
} }

View File

@@ -8,21 +8,20 @@
package pp.battleship.game.server; package pp.battleship.game.server;
import pp.battleship.BattleshipConfig; import pp.battleship.BattleshipConfig;
import pp.battleship.message.client.AnimationEndMessage; import pp.battleship.message.client.AnimationMessage;
import pp.battleship.message.client.ClientInterpreter; import pp.battleship.message.client.ClientInterpreter;
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.*; import pp.battleship.message.server.EffectMessage;
import pp.battleship.message.server.GameDetails;
import pp.battleship.message.server.ServerMessage;
import pp.battleship.message.server.StartBattleMessage;
import pp.battleship.model.Battleship; import pp.battleship.model.Battleship;
import pp.battleship.model.IntPoint; import pp.battleship.model.IntPoint;
import pp.battleship.model.Rotation;
import pp.util.Position;
import java.lang.System.Logger; import java.lang.System.Logger;
import java.lang.System.Logger.Level; import java.lang.System.Logger.Level;
import java.lang.reflect.Array;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@@ -37,13 +36,11 @@ 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 player1AnimationReady = false;
private boolean player2AnimationReady = false;
/** /**
* Constructs a ServerGameLogic with the specified sender and configuration. * Constructs a ServerGameLogic with the specified sender and configuration.
* *
@@ -147,47 +144,79 @@ 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 (!checkMap(msg, from)) { else if (validMap(msg))
LOGGER.log(Level.ERROR, "player submitted not allowed Map"); playerReady(getPlayerById(from), msg.getShips());
else {
LOGGER.log(Level.ERROR, "map does not fit game details"); //NON-NLS
send(getPlayerById(from), new GameDetails(config)); send(getPlayerById(from), new GameDetails(config));
} }
else
playerReady(getPlayerById(from), msg.getShips());
} }
/** /**
* Returns true if the map contains correct ship placement and is of the correct size * Validates the received map message by checking if all ships are within bounds
* and do not overlap with each other.
* *
* @param msg the received MapMessage of the player * @param msg the received MapMessage containing the ships
* @param from the ID of the Player * @return true if the map is valid, false otherwise
* @return a boolean based on if the transmitted map ist correct
*/ */
private boolean checkMap(MapMessage msg, int from) { private boolean validMap(MapMessage msg) {
int mapWidth = getPlayerById(from).getMap().getWidth();
int mapHeight = getPlayerById(from).getMap().getHeight();
// check if ship is out of bounds
for (Battleship battleship : msg.getShips()){
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 = msg.getShips(); List<Battleship> ships = msg.getShips();
return inBounds(ships) && !overlaps(ships);
}
/**
* Checks if all ships in the given list are within the bounds of the map.
*
* @param ships the list of Battleships to validate
* @return true if all ships are within bounds, false otherwise
*/
private boolean inBounds(List<Battleship> ships) {
for (Battleship ship : ships) { for (Battleship ship : ships) {
for(Battleship compareShip:ships){ if (!isWithinBounds(ship)) {
if(!(ship==compareShip)){
if(ship.collidesWith(compareShip)){
return false; return false;
} }
} }
}
}
return true; return true;
} }
/**
* Checks if the given ship is within the bounds of the map.
*
* @param ship the Battleship to check
* @return true if the ship is within bounds, false otherwise
*/
private boolean isWithinBounds(Battleship ship) {
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;
}
/** /**
* Handles the reception of a ShootMessage. * Handles the reception of a ShootMessage.
* *
@@ -198,40 +227,39 @@ private boolean checkMap(MapMessage msg, int from) {
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 else {
for (Player player : players){ setState(ServerState.ANIMATION);
send(player, new AnimationStartMessage(msg.getPosition(), player == activePlayer)); shoot(getPlayerById(from), msg.getPosition());
setState(ServerState.ANIMATION_WAIT);
} }
} }
/** /**
* Handles a clients message that it is done with the animation * Handles the reception of an {@link AnimationMessage}.
* Marks the player's animation as finished and transitions the game state if necessary.
* *
* @param msg the AnimationEndMessage to be processed * @param msg the received {@code AnimationMessage}
* @param from the connection ID from which the message was received * @param from the ID of the sender client
*/ */
@Override @Override
public void received(AnimationEndMessage msg, int from){ public void received(AnimationMessage msg, int from) {
if(state != ServerState.ANIMATION_WAIT) { if (state != ServerState.ANIMATION)
LOGGER.log(Level.ERROR, "animation not allowed in {0}", state); LOGGER.log(Level.ERROR, "animation not allowed in {0}", state); //NON-NLS
return; else
finishedAnimation(getPlayerById(from));
} }
if(getPlayerById(from) == players.get(0)){
LOGGER.log(Level.DEBUG, "{0} set to true", getPlayerById(from)); /**
player1AnimationReady = true; * Marks the player's animation as finished and transitions the game state if necessary.
shoot(getPlayerById(from), msg.getPosition()); *
} else if (getPlayerById(from) == players.get(1)){ * @param player the player whose animation is finished
LOGGER.log(Level.DEBUG, "{0} set to true {1}", getPlayerById(from), getPlayerById(from).toString()); */
player2AnimationReady = true; private void finishedAnimation(Player player) {
shoot(getPlayerById(from), msg.getPosition()); if (!finishedAnimation.add(player)) {
LOGGER.log(Level.ERROR, "{0}'s animation was already finished", player);
} }
if(player1AnimationReady && player2AnimationReady){ if (finishedAnimation.size() == 2) {
finishedAnimation.clear();
setState(ServerState.BATTLE); setState(ServerState.BATTLE);
for (Player player : players)
send(player, new SwitchBattleState(player == activePlayer));
player1AnimationReady = false;
player2AnimationReady = false;
} }
} }
@@ -256,56 +284,36 @@ void playerReady(Player player, List<Battleship> ships) {
} }
/** /**
* This method decides what effectMessage the client should get based on the shot made * Handles the shooting action by the player.
* and switches the active player if a shot was missed
* *
* @param p the player to be sent the message * @param p the player who shot
* @param position the position where the shot would hit in the 2d map model * @param pos the position of the shot
*/ */
void shoot(Player p, IntPoint position) { void shoot(Player p, IntPoint pos) {
final Battleship selectedShip; if (p != activePlayer) return;
if(p != activePlayer){ final Player otherPlayer = getOpponent(activePlayer);
selectedShip = p.getMap().findShipAt(position); final Battleship selectedShip = otherPlayer.getMap().findShipAt(pos);
} else {
selectedShip = getOpponent(p).getMap().findShipAt(position);
}
if (selectedShip == null) { if (selectedShip == null) {
if (p != activePlayer) { // shot missed
send(p, EffectMessage.miss(false, position)); send(activePlayer, EffectMessage.miss(true, pos));
send(otherPlayer, EffectMessage.miss(false, pos));
activePlayer = otherPlayer;
} else { } else {
send(activePlayer, EffectMessage.miss(true, position)); // shot hit a ship
} selectedShip.hit(pos);
if(player1AnimationReady && player2AnimationReady){ if (otherPlayer.getMap().getRemainingShips().isEmpty()) {
LOGGER.log(Level.DEBUG, "switched active player"); // game is over
if(p != activePlayer){ send(activePlayer, EffectMessage.won(pos, selectedShip));
activePlayer = p; send(otherPlayer, EffectMessage.lost(pos, selectedShip, activePlayer.getMap().getRemainingShips()));
} else {
activePlayer = getOpponent(p);
}
}
} else {
selectedShip.hit(position);
if(getOpponent(activePlayer).getMap().getRemainingShips().isEmpty()){
if(p != activePlayer){
send(p, EffectMessage.lost(position, selectedShip, activePlayer.getMap().getRemainingShips()));
} else {
send(activePlayer, EffectMessage.won(position, selectedShip));
}
if(player1AnimationReady && player2AnimationReady){
setState(ServerState.GAME_OVER); setState(ServerState.GAME_OVER);
}
} else if (selectedShip.isDestroyed()) { } else if (selectedShip.isDestroyed()) {
if(p != activePlayer){ // ship has been destroyed, but game is not yet over
send(p, EffectMessage.shipDestroyed(false, position, selectedShip)); send(activePlayer, EffectMessage.shipDestroyed(true, pos, selectedShip));
send(otherPlayer, EffectMessage.shipDestroyed(false, pos, selectedShip));
} else { } else {
send(activePlayer, EffectMessage.shipDestroyed(true, position, selectedShip)); // ship has been hit, but it hasn't been destroyed
} send(activePlayer, EffectMessage.hit(true, pos));
} else { send(otherPlayer, EffectMessage.hit(false, pos));
if(p != activePlayer){
send(p, EffectMessage.hit(false, position));
} else {
send(activePlayer, EffectMessage.hit(true, position));
}
} }
} }
} }

View File

@@ -27,12 +27,12 @@ enum ServerState {
BATTLE, BATTLE,
/** /**
* The game has ended because all the ships of one player have been destroyed. * The server is waiting for clients to finish their animations.
*/ */
GAME_OVER, ANIMATION,
/** /**
* The server waits for all players to finish the animation * The game has ended because all the ships of one player have been destroyed.
*/ */
ANIMATION_WAIT GAME_OVER
} }

View File

@@ -61,15 +61,16 @@ public void received(MapMessage msg, int from) {
} }
/** /**
* Handles the reception of a AnimationEndMessage * Handles the reception of a {@link AnimationMessage}.
* Creates a copy of the AnimationEndMessage * Since a {@code AnimationMessage} does not need to be copied, it is directly assigned.
* *
* @param msg the AnimationEndMessage to be processed * @param msg the received {@code AnimationMessage}
* @param from the connection ID from which the message was received * @param from the identifier of the sender
*/ */
@Override @Override
public void received(AnimationEndMessage msg, int from) { public void received(AnimationMessage msg, int from) {
copiedMessage = new AnimationEndMessage(msg.getPosition()); // copying is not necessary
copiedMessage = msg;
} }
/** /**

View File

@@ -9,7 +9,11 @@
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.*; import pp.battleship.message.server.EffectMessage;
import pp.battleship.message.server.GameDetails;
import pp.battleship.message.server.ServerInterpreter;
import pp.battleship.message.server.ServerMessage;
import pp.battleship.message.server.StartBattleMessage;
import java.io.IOException; import java.io.IOException;
@@ -20,13 +24,11 @@
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;
} }
@@ -80,27 +82,6 @@ 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(AnimationStartMessage 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(SwitchBattleState 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,10 +1,13 @@
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.AnimationEndMessage; import pp.battleship.message.client.AnimationMessage;
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.*; import pp.battleship.message.server.EffectMessage;
import pp.battleship.message.server.GameDetails;
import pp.battleship.message.server.ServerInterpreter;
import pp.battleship.message.server.StartBattleMessage;
import pp.battleship.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;
@@ -111,35 +114,16 @@ public void received(StartBattleMessage msg) {
} }
/** /**
* Receives an effect message, logs it. * Receives an effect message, logs it, and updates the turn status.
* 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(AnimationStartMessage msg) {
LOGGER.log(Level.INFO, "Received AnimationStartMessage: {0}", msg);
connection.sendRobotMessage(new AnimationEndMessage(msg.getPosition()));
}
/**
* Receives a SwitchBattleState, and shots if it is the robots turn
*
* @param msg the SwitchBattleState received
*/
@Override
public void received(SwitchBattleState msg){
LOGGER.log(Level.INFO, "Received SwitchBattleStateMessage: {0}", msg);
if (msg.isTurn())
shoot(); shoot();
} }
} }

View File

@@ -1,44 +0,0 @@
package pp.battleship.message.client;
import com.jme3.network.serializing.Serializable;
import pp.battleship.model.IntPoint;
@Serializable
public class AnimationEndMessage extends ClientMessage {
private IntPoint position;
/**
* used for serialization
*/
private AnimationEndMessage(){ /* nothing */}
/**
* constructs a new AnimationEndMessage
*
* @param position the position to be effected by the server
*/
public AnimationEndMessage(IntPoint position) {
this.position = position;
}
/**
* getter for the position
*
* @return IntPoint position
*/
public IntPoint getPosition() {
return position;
}
/**
* Accepts Visitors to process 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);
}
}

View File

@@ -0,0 +1,27 @@
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);
}
}

View File

@@ -28,10 +28,10 @@ public interface ClientInterpreter {
void received(MapMessage msg, int from); void received(MapMessage msg, int from);
/** /**
* Processes a received AnimationendMessage * Processes a received AnimationMessage.
* *
* @param msg the AnimationEndMessage to be processed * @param msg the AnimationMessage to be processed
* @param from the connection ID from which the message was received * @param from the connection ID from which the message was received
*/ */
void received(AnimationEndMessage msg, int from); void received(AnimationMessage msg, int from);
} }

View File

@@ -1,64 +0,0 @@
package pp.battleship.message.server;
import com.jme3.network.serializing.Serializable;
import pp.battleship.model.IntPoint;
@Serializable
public class AnimationStartMessage extends ServerMessage {
private IntPoint position;
private boolean myTurn;
/**
* used for serialization
*/
private AnimationStartMessage(){ /* nothing */}
/**
* constructs a new AnimationStartMessage
*
* @param position the Position a shell should affect
* @param isTurn boolean containing if it is the clients turn or not
*/
public AnimationStartMessage(IntPoint position, boolean isTurn) {
this.position = position;
this.myTurn = isTurn;
}
/**
* getter for the position
*
* @return IntPoint position
*/
public IntPoint getPosition() {
return position;
}
/**
* getter for myTurn
*
* @return boolean myTurn
*/
public boolean isMyTurn() {
return myTurn;
}
/**
* Accepts visitors to process this message
*
* @param interpreter the visitor to be used for processing
*/
@Override
public void accept(ServerInterpreter interpreter) {
interpreter.received(this);
}
/**
* returns a string that gives context to the message
*
* @return String teh context
*/
@Override
public String getInfoTextKey() {
return (position + " to be animated");
}
}

View File

@@ -33,18 +33,4 @@ public interface ServerInterpreter {
* @param msg the EffectMessage received * @param msg the EffectMessage received
*/ */
void received(EffectMessage msg); void received(EffectMessage msg);
/**
* Handles an AnimationStartMessage received from the server
*
* @param msg the AnimationStartMessage received
*/
void received(AnimationStartMessage msg);
/**
* handles an SwitchBattleState received from the server
*
* @param msg the SwitchBattleState received
*/
void received(SwitchBattleState msg);
} }

View File

@@ -1,51 +0,0 @@
package pp.battleship.message.server;
import com.jme3.network.serializing.Serializable;
@Serializable
public class SwitchBattleState extends ServerMessage {
private boolean isTurn;
/**
* used for serialization
*/
private SwitchBattleState(){ /* nothing */}
/**
* constructs a new SwitchBattleState message
*
* @param isTurn boolean containing if it is the clients turn
*/
public SwitchBattleState(boolean isTurn) {
this.isTurn = isTurn;
}
/**
* getter for isTurn
*
* @return boolean isTurn
*/
public boolean isTurn() {
return isTurn;
}
/**
* accept visitors the process this message
*
* @param interpreter the visitor to be used for processing
*/
@Override
public void accept(ServerInterpreter interpreter) {
interpreter.received(this);
}
/**
* returns a string containing context for this method
*
* @return String containing context
*/
@Override
public String getInfoTextKey() {
return "";
}
}

View File

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

View File

@@ -92,9 +92,9 @@ public void add(Shot shot) {
} }
/** /**
* Registers a shell in the map and updates an item added event * Adds a shell to the map and triggers an item addition event.
* *
* @param shell the shell to be registered * @param shell the shell to be added to the map
*/ */
public void add(Shell shell) { public void add(Shell shell) {
addItem(shell); addItem(shell);

View File

@@ -30,7 +30,7 @@ public interface Visitor<T> {
T visit(Battleship ship); T visit(Battleship ship);
/** /**
* Visits a Shell element * Visits a Shell element.
* *
* @param shell the Shell element to visit * @param shell the Shell element to visit
* @return the result of visiting the Shell element * @return the result of visiting the Shell element

View File

@@ -27,7 +27,7 @@ public interface VoidVisitor {
void visit(Battleship ship); void visit(Battleship ship);
/** /**
* Visits a Shell element * Visits a Shell element.
* *
* @param shell the Shell element to visit * @param shell the Shell element to visit
*/ */

View File

@@ -82,20 +82,6 @@ public List<Battleship> getShips() {
return ships.stream().map(BattleshipDTO::toBattleship).toList(); return ships.stream().map(BattleshipDTO::toBattleship).toList();
} }
/**
* This method returns the width of the DTO.
*
* @return the width of the DTO
*/
public int getWidth() {return width;}
/**
* Returns the height of the DTO.
*
* @return the height of the DTO.
*/
public int getHeight() {return height;}
/** /**
* Saves the current ShipMapDTO to a file in JSON format. * Saves the current ShipMapDTO to a file in JSON format.
* *
@@ -128,4 +114,22 @@ public static ShipMapDTO loadFrom(File file) throws IOException {
throw new IOException(e.getLocalizedMessage()); throw new IOException(e.getLocalizedMessage());
} }
} }
/**
* Returns the width of the ship map.
*
* @return the width of the ship map
*/
public int getWidth() {
return width;
}
/**
* Returns the height of the ship map.
*
* @return the height of the ship map
*/
public int getHeight() {
return height;
}
} }

View File

@@ -39,17 +39,17 @@ default void receivedEvent(InfoTextEvent event) { /* do nothing */ }
*/ */
default void receivedEvent(SoundEvent event) { /* do nothing */ } default void receivedEvent(SoundEvent event) { /* do nothing */ }
/**
* Indicates that music shall be played.
*
* @param event the received event
*/
default void receivedEvent(MusicEvent event) { /* do nothing */ }
/** /**
* Indicates that the client's state has changed. * Indicates that the client's state has changed.
* *
* @param event the received event * @param event the received event
*/ */
default void receivedEvent(ClientStateEvent event) { /* do nothing */ } default void receivedEvent(ClientStateEvent event) { /* do nothing */ }
/**
* Indicates that the music should be changed
*
* @param event the received Event
*/
default void receivedEvent(MusicEvent event) { /* do nothing */ }
} }

View File

@@ -1,23 +1,23 @@
package pp.battleship.notification; package pp.battleship.notification;
/** /**
* Enumeration representing different types of sounds used in the game. * Enumeration representing different types of music used in the game.
*/ */
public enum Music { public enum Music {
/** /**
* Menu music * Music for the game.
*/ */
MENU_THEME, GAME_MUSIC,
/** /**
* Battle music * Music for the menu.
*/ */
BATTLE_THEME, MENU_MUSIC,
/** /**
* Game over music for a loss * Music for victory.
*/ */
GAME_OVER_THEME_L, VICTORY_MUSIC,
/** /**
* Game over music for a victory * Music for defeat.
*/ */
GAME_OVER_THEME_V, DEFEAT_MUSIC
} }

View File

@@ -1,7 +1,8 @@
package pp.battleship.notification; package pp.battleship.notification;
/** /**
* Event when the background music is to be changed * Event when music is played in the game.
* *
* @param music the music to be played * @param music the music to be played
*/ */

View File

@@ -24,7 +24,7 @@ public enum Sound {
*/ */
DESTROYED_SHIP, DESTROYED_SHIP,
/** /**
* Sound of a rocket * Sound of a shot being fired.
*/ */
ROCKET_FIRED SHELL_FIRED
} }

View File

@@ -22,25 +22,21 @@ button.no=No
button.ok=Ok button.ok=Ok
button.connect=Connect button.connect=Connect
button.cancel=Cancel button.cancel=Cancel
host.own.server=Host server
server.dialog=Server server.dialog=Server
host.name=Host host.name=Host
host.own-server=Host own server
port.number=Port port.number=Port
wait.its.not.your.turn=Wait, it's not your turn!! wait.its.not.your.turn=Wait, it's not your turn!!
menu.quit=Quit game menu.quit=Quit game
menu.return-to-game=Return to game menu.return-to-game=Return to game
menu.sound-enabled=Toggle the sound menu.sound-enabled=Sound switched on
menu.main.volume= Main volume
menu.map.load=Load map from file... menu.map.load=Load map from file...
menu.map.save=Save map in file... menu.map.save=Save map in file...
menu.music.toggle=Toggle the music menu.music-toggle=Music on/off
invalid.map=Your submitted map was invalid
menu.volume=Music volume
menu.sound.volume=Sound volume
label.file=File: label.file=File:
label.connecting=Connecting... label.connecting=Connecting...
dialog.error=Error dialog.error=Error
dialog.question=Question dialog.question=Question
port.must.be.integer=Port must be an integer number port.must.be.integer=Port must be an integer number
map.doesnt.fit=The map doesn't fit to this game map.doesnt.fit=The map doesn't fit to this game
ships.dont.fit.the.map=Ships are out of the Area map.invalid=The map is invalid

View File

@@ -23,24 +23,20 @@ button.ok=Ok
button.connect=Verbinde button.connect=Verbinde
button.cancel=Abbruch button.cancel=Abbruch
server.dialog=Server server.dialog=Server
host.own.server=Server starten
host.name=Host host.name=Host
port.number=Port port.number=Port
host.own-server=Server hosten
wait.its.not.your.turn=Warte, Du bist nicht dran!! wait.its.not.your.turn=Warte, Du bist nicht dran!!
menu.quit=Spiel beenden menu.quit=Spiel beenden
menu.return-to-game=Zurück zum Spiel menu.return-to-game=Zurück zum Spiel
menu.sound-enabled=An/Ausschalten des Sounds menu.sound-enabled=Sound eingeschaltet
menu.main.volume=Gesamt Lautstärke
menu.map.load=Karte von Datei laden... menu.map.load=Karte von Datei laden...
menu.map.save=Karte in Datei speichern... menu.map.save=Karte in Datei speichern...
menu.music.toggle=An/Ausschalten der Musik menu.music-toggle=Musik an/aus
invalid.map=Die angegebene Karte war ungültig
menu.volume=Lautstärke der Musik
menu.sound.volume=Lautstärke des Sounds
label.file=Datei: label.file=Datei:
label.connecting=Verbindung wird aufgebaut... label.connecting=Verbindung wird aufgebaut...
dialog.error=Fehler dialog.error=Fehler
dialog.question=Frage dialog.question=Frage
port.must.be.integer=Der Port muss eine ganze Zahl sein port.must.be.integer=Der Port muss eine ganze Zahl sein
map.doesnt.fit=Diese Karte passt nicht zu diesem Spiel map.doesnt.fit=Diese Karte passt nicht zu diesem Spiel
ships.dont.fit.the.map=Ein Schiff ist außerhalb des Spielfelds plaziert map.invalid=Die Karte ist ungültig

View File

@@ -222,7 +222,6 @@ public void testClient() {
assertEquals(p(1, 5), shootMsg.getPosition()); assertEquals(p(1, 5), shootMsg.getPosition());
clientLogic.received(EffectMessage.shipDestroyed(true, p(1, 5), new Battleship(2, 1, 5, DOWN))); clientLogic.received(EffectMessage.shipDestroyed(true, p(1, 5), new Battleship(2, 1, 5, DOWN)));
assertEquals("its.your.turn", infoTexts.poll()); assertEquals("its.your.turn", infoTexts.poll());
ships = clientLogic.getOpponentMap().getShips().toList(); ships = clientLogic.getOpponentMap().getShips().toList();
assertEquals(1, ships.size()); assertEquals(1, ships.size());
checkShip(ships.get(0), 2, 1, 5, DOWN, NORMAL); checkShip(ships.get(0), 2, 1, 5, DOWN, NORMAL);
@@ -235,7 +234,6 @@ public void testClient() {
assertEquals("you.lost.the.game", infoTexts.poll()); assertEquals("you.lost.the.game", infoTexts.poll());
ships = clientLogic.getOpponentMap().getShips().toList(); ships = clientLogic.getOpponentMap().getShips().toList();
assertEquals(2, ships.size()); assertEquals(2, ships.size());
checkShip(ships.get(0), 2, 1, 5, DOWN, NORMAL); checkShip(ships.get(0), 2, 1, 5, DOWN, NORMAL);
checkShip(ships.get(1), 1, 1, 2, RIGHT, NORMAL); checkShip(ships.get(1), 1, 1, 2, RIGHT, NORMAL);

View File

@@ -18,14 +18,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.AnimationEndMessage; import pp.battleship.message.client.AnimationMessage;
import pp.battleship.message.client.ClientMessage; import pp.battleship.message.client.ClientMessage;
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.*; import pp.battleship.message.server.EffectMessage;
import pp.battleship.message.server.GameDetails;
import pp.battleship.message.server.ServerMessage;
import pp.battleship.message.server.StartBattleMessage;
import pp.battleship.model.Battleship; import pp.battleship.model.Battleship;
import pp.battleship.model.IntPoint; import pp.battleship.model.IntPoint;
import pp.battleship.model.Shell;
import pp.battleship.model.Shot; import pp.battleship.model.Shot;
import java.io.File; import java.io.File;
@@ -55,8 +57,7 @@ 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());
} }
} }
@@ -91,8 +92,7 @@ private void startServer() {
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);
} }
@@ -101,8 +101,7 @@ private void startServer() {
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();
} }
@@ -113,19 +112,17 @@ private void initializeSerializables() {
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(AnimationEndMessage.class);
Serializer.registerClass(AnimationStartMessage.class);
Serializer.registerClass(SwitchBattleState.class);
} }
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, AnimationEndMessage.class); myServer.addMessageListener(this, AnimationMessage.class);
myServer.addConnectionListener(this); myServer.addConnectionListener(this);
} }

View File

@@ -163,18 +163,45 @@ public static float atan2(float fY, float fX) {
return (float) Math.atan2(fY, fX); return (float) Math.atan2(fY, fX);
} }
/**
* A direct call to Math.sinh.
*
* @param x The value for which to compute the hyperbolic sine
* @return Math.sinh(x)
* @see Math#sinh(double)
*/
public static float sinh(float x) { public static float sinh(float x) {
return (float) Math.sinh(x); return (float) Math.sinh(x);
} }
/**
* A direct call to Math.cosh.
*
* @param x The value for which to compute the hyperbolic cosine
* @return Math.cosh(x)
* @see Math#cosh(double)
*/
public static float cosh(float x) { public static float cosh(float x) {
return (float) Math.cosh(x); return (float) Math.cosh(x);
} }
/**
* A direct call to Math.tanh.
*
* @param x The value for which to compute the hyperbolic tangent
* @return Math.tanh(x)
* @see Math#tanh(double)
*/
public static float tanh(float x) { public static float tanh(float x) {
return (float) Math.tanh(x); return (float) Math.tanh(x);
} }
/**
* Returns the hyperbolic cotangent of a value.
* @param x The value for which to compute the hyperbolic cotangent.
* @return The hyperbolic cotangent of x.
* @see Math#tanh(double)
*/
public static float coth(float x) { public static float coth(float x) {
return (float) (1d / Math.tanh(x)); return (float) (1d / Math.tanh(x));
} }
@@ -239,6 +266,14 @@ public static float exp(float fValue) {
return (float) Math.exp(fValue); return (float) Math.exp(fValue);
} }
/**
* Returns e^fValue - 1.
* This is equivalent to calling Math.expm1.
*
* @param fValue The exponent to raise e to, minus 1.
* @return The result of e^fValue - 1.
* @see Math#expm1(double)
*/
public static float expm1(float fValue) { public static float expm1(float fValue) {
return (float) Math.expm1(fValue); return (float) Math.expm1(fValue);
} }

View File

@@ -36,7 +36,6 @@
selector("label", "pp") { selector("label", "pp") {
insets = new Insets3f(2, 2, 2, 2) insets = new Insets3f(2, 2, 2, 2)
color = buttonEnabledColor color = buttonEnabledColor
textHAlignment = HAlignment.Center
} }
selector("header", "pp") { selector("header", "pp") {