13 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
232 changed files with 808335 additions and 2693738 deletions

View File

@@ -2,7 +2,7 @@
<configuration default="false" name="Projekte [test]" type="GradleRunConfiguration" factoryName="Gradle">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$/Projekte" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="--continue" />
<option name="taskDescriptions">

View File

@@ -15,6 +15,7 @@ implementation project(":battleship:model")
runtimeOnly libs.jme3.plugins
runtimeOnly libs.jme3.jogg
runtimeOnly libs.jme3.testdata
}
application {

View File

@@ -29,7 +29,7 @@ robot.targets=2, 0,\
2, 3
#
# 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.
# 'map.width' defines the number of columns, and 'map.height' defines the number of rows.

View File

@@ -0,0 +1,267 @@
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.AudioNode;
import pp.battleship.notification.GameEventListener;
import pp.battleship.notification.MusicEvent;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import java.util.prefs.Preferences;
import static pp.util.PreferencesUtils.getPreferences;
/**
* 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());
/**
* Preferences for storing music settings.
*/
private static final Preferences PREFERENCES = getPreferences(BackgroundMusic.class);
/**
* Preference key for enabling/disabling music.
*/
private static final String ENABLED_PREF = "enabled"; //NON-NLS
/**
* 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;
/**
* Checks if music is enabled in the preferences.
*
* @return {@code true} if music is enabled, {@code false} otherwise.
*/
public static boolean enabledInPreferences() {
return PREFERENCES.getBoolean(ENABLED_PREF, true);
}
/**
* Sets the enabled state of this AppState.
* Overrides {@link com.jme3.app.state.AbstractAppState#setEnabled(boolean)}
*
* @param enabled {@code true} to enable the AppState, {@code false} to disable it.
*/
@Override
public void setEnabled(boolean enabled) {
if (isEnabled() == enabled) return;
super.setEnabled(enabled);
LOGGER.log(Level.INFO, "Music enabled: {0}", enabled); //NON-NLS
PREFERENCES.putBoolean(ENABLED_PREF, enabled);
playCurrentMusic();
}
/**
* Initializes the music for the game.
* Overrides {@link AbstractAppState#initialize(AppStateManager, Application)}
*
* @param stateManager The state manager
* @param app The application
*/
@Override
public void initialize(AppStateManager stateManager, Application app) {
LOGGER.log(Level.INFO, "Initializing background music"); //NON-NLS
super.initialize(stateManager, app);
menuMusic = loadMusic(app, MENU_MUSIC_PATH);
gameMusic = loadMusic(app, GAME_MUSIC_PATH);
victoryMusic = loadMusic(app, VICTORY_MUSIC_PATH);
defeatMusic = loadMusic(app, DEFEAT_MUSIC_PATH);
currentMusic = menuMusic;
playCurrentMusic();
}
/**
* Loads a music file and initializes an AudioNode with the specified settings.
*
* @param app The application instance.
* @param name The name of the music file to load.
* @return The initialized AudioNode, or {@code null} if the file could not be loaded.
*/
private AudioNode loadMusic(Application app, String name) {
try {
this.volume = PREFERENCES.getFloat(VOLUME_PREF, 0.5f);
final AudioNode music = new AudioNode(app.getAssetManager(), name, DataType.Stream);
music.setLooping(true);
music.setVolume(volume);
music.setPositional(false);
music.setDirectional(false);
return music;
} catch (AssetLoadException | AssetNotFoundException ex) {
LOGGER.log(Level.ERROR, ex.getMessage(), ex);
}
return null;
}
/**
* Plays the current music if the music is enabled.
* Stops the current music if the music is disabled.
*/
private void playCurrentMusic() {
if (isEnabled()) {
if (currentMusic != null) {
LOGGER.log(Level.INFO, "Playing current music"); //NON-NLS
currentMusic.play();
}
} else {
if (currentMusic != null) {
currentMusic.stop();
}
}
}
/**
* Plays the game music.
*/
private void gameMusic() {
if (isEnabled() && gameMusic != null) {
stopAll();
LOGGER.log(Level.INFO, "Playing game music"); //NON-NLS
PREFERENCES.putFloat(VOLUME_PREF, volume);
gameMusic.play();
}
}
/**
* Plays the victory music.
*/
private void victoryMusic() {
if (isEnabled() && victoryMusic != null) {
stopAll();
LOGGER.log(Level.INFO, "Playing victory music"); //NON-NLS
PREFERENCES.putFloat(VOLUME_PREF, volume);
victoryMusic.play();
}
}
/**
* Plays the defeat music.
*/
private void defeatMusic() {
if (isEnabled() && defeatMusic != null) {
stopAll();
LOGGER.log(Level.INFO, "Playing defeat music"); //NON-NLS
PREFERENCES.putFloat(VOLUME_PREF, volume);
defeatMusic.play();
}
}
/**
* Stops all music.
*/
private void stopAll() {
if (menuMusic != null) menuMusic.stop();
if (gameMusic != null) gameMusic.stop();
if (victoryMusic != null) victoryMusic.stop();
if (defeatMusic != null) defeatMusic.stop();
}
/**
* Handles the received music event and plays the corresponding music.
*
* @param event The music event to handle.
*/
@Override
public void receivedEvent(MusicEvent event) {
switch (event.music()) {
case GAME_MUSIC -> {
gameMusic();
currentMusic = gameMusic;
}
case VICTORY_MUSIC -> {
victoryMusic();
currentMusic = victoryMusic;
}
case DEFEAT_MUSIC -> {
defeatMusic();
currentMusic = defeatMusic;
}
}
}
/**
* Sets the volume for the background music and updates the preferences.
*
* @param volume The volume level to set.
*/
public void setVolume(float volume) {
LOGGER.log(Level.INFO, "Setting volume to {0}", volume); //NON-NLS
this.volume = volume;
currentMusic.setVolume(volume);
PREFERENCES.putFloat(VOLUME_PREF, volume);
}
/**
* Returns the volume level for the background music.
*
* @return The volume level as a float.
*/
public float getVolume() {
return volume;
}
}

View File

@@ -122,19 +122,13 @@ public class BattleshipApp extends SimpleApplication implements BattleshipClient
*/
private final ActionListener escapeListener = (name, isPressed, tpf) -> escape(isPressed);
/**
* Listener for handling actions triggered by the Escape key.
*/
private GameMusic music;
static {
// Configure logging
LogManager manager = LogManager.getLogManager();
try {
manager.readConfiguration(new FileInputStream("logging.properties"));
LOGGER.log(Level.INFO, "Successfully read logging properties"); //NON-NLS
}
catch (IOException e) {
} catch (IOException e) {
LOGGER.log(Level.INFO, e.getMessage());
}
}
@@ -198,15 +192,6 @@ DialogManager getDialogManager() {
return dialogManager;
}
/**
* Returns the GameMusic responsible for playing music.
*
* @return The {@link GameMusic} instance.
*/
GameMusic getGameMusic() {
return music;
}
/**
* Returns the game logic handler for the client.
*
@@ -239,8 +224,6 @@ public void simpleInitApp() {
setupStates();
setupGui();
serverConnection.connect();
music = new GameMusic(this, "Sound/Music/battleship.ogg");
}
/**
@@ -283,6 +266,7 @@ private void setupStates() {
stateManager.detach(stateManager.getState(DebugKeysAppState.class));
attachGameSound();
attachBackgroundSound();
stateManager.attachAll(new EditorAppState(), new BattleAppState(), new SeaAppState());
}
@@ -296,6 +280,19 @@ private void attachGameSound() {
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.
* This method is called once per frame during the game loop.
@@ -421,12 +418,12 @@ public void stop(boolean waitFor) {
*/
void confirmDialog(String question, Runnable yesAction) {
DialogBuilder.simple(dialogManager)
.setTitle(lookup("dialog.question"))
.setText(question)
.setOkButton(lookup("button.yes"), yesAction)
.setNoButton(lookup("button.no"))
.build()
.open();
.setTitle(lookup("dialog.question"))
.setText(question)
.setOkButton(lookup("button.yes"), yesAction)
.setNoButton(lookup("button.no"))
.build()
.open();
}
/**
@@ -436,10 +433,10 @@ void confirmDialog(String question, Runnable yesAction) {
*/
void errorDialog(String errorMessage) {
DialogBuilder.simple(dialogManager)
.setTitle(lookup("dialog.error"))
.setText(errorMessage)
.setOkButton(lookup("button.ok"))
.build()
.open();
.setTitle(lookup("dialog.error"))
.setText(errorMessage)
.setOkButton(lookup("button.ok"))
.build()
.open();
}
}

View File

@@ -7,17 +7,25 @@
package pp.battleship.client;
import com.jme3.network.*;
import com.jme3.network.ConnectionListener;
import com.jme3.network.HostedConnection;
import com.jme3.network.Message;
import com.jme3.network.MessageListener;
import com.jme3.network.Network;
import com.jme3.network.Server;
import com.jme3.network.serializing.Serializer;
import pp.battleship.BattleshipConfig;
import pp.battleship.game.server.Player;
import pp.battleship.game.server.ServerGameLogic;
import pp.battleship.game.server.ServerSender;
import pp.battleship.message.client.AnimationEndMessage;
import pp.battleship.message.client.AnimationMessage;
import pp.battleship.message.client.ClientMessage;
import pp.battleship.message.client.MapMessage;
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.IntPoint;
import pp.battleship.model.Shot;
@@ -35,12 +43,39 @@
* Server implementing the visitor pattern as MessageReceiver for ClientMessages
*/
public class BattleshipServer implements MessageListener<HostedConnection>, ConnectionListener, ServerSender {
/**
* Logger for the BattleshipServer class.
*/
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");
/**
* Port number for the server.
*/
private final int PORT_NUMBER;
/**
* Configuration settings for the Battleship server.
*/
private final BattleshipConfig config = new BattleshipConfig();
/**
* The server instance.
*/
private Server myServer;
/**
* Game logic for the server.
*/
private final ServerGameLogic logic;
/**
* Queue for pending messages to be processed by the server.
*/
private final BlockingQueue<ReceivedMessage> pendingMessages = new LinkedBlockingQueue<>();
static {
@@ -49,80 +84,99 @@ public class BattleshipServer implements MessageListener<HostedConnection>, Conn
try {
manager.readConfiguration(new FileInputStream("logging.properties"));
LOGGER.log(Level.INFO, "Successfully read logging properties"); //NON-NLS
}
catch (IOException e) {
} catch (IOException e) {
LOGGER.log(Level.INFO, e.getMessage());
}
}
/**
* Starts the Battleships server.
*/
public static void main(String[] args) {
new BattleshipServer().run();
}
/**
* Creates the server.
*/
BattleshipServer() {
public BattleshipServer(int PORT_NUMBER) {
config.readFromIfExists(CONFIG_FILE);
this.PORT_NUMBER = PORT_NUMBER;
LOGGER.log(Level.INFO, "Configuration: {0}", config); //NON-NLS
logic = new ServerGameLogic(this, config);
}
/**
* Starts the server and processes incoming messages indefinitely.
*/
public void run() {
startServer();
while (true)
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() {
try {
LOGGER.log(Level.INFO, "Starting server..."); //NON-NLS
myServer = Network.createServer(config.getPort());
myServer = Network.createServer(PORT_NUMBER);
initializeSerializables();
myServer.start();
registerListeners();
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
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() {
try {
pendingMessages.take().process(logic);
}
catch (InterruptedException ex) {
} catch (InterruptedException ex) {
LOGGER.log(Level.INFO, "Interrupted while waiting for messages"); //NON-NLS
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() {
Serializer.registerClass(AnimationEndMessage.class);
Serializer.registerClass(AnimationStartMessage.class);
Serializer.registerClass(SwitchBattleState.class);
Serializer.registerClass(GameDetails.class);
Serializer.registerClass(StartBattleMessage.class);
Serializer.registerClass(MapMessage.class);
Serializer.registerClass(ShootMessage.class);
Serializer.registerClass(AnimationMessage.class);
Serializer.registerClass(EffectMessage.class);
Serializer.registerClass(Battleship.class);
Serializer.registerClass(IntPoint.class);
Serializer.registerClass(Shot.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() {
myServer.addMessageListener(this, AnimationEndMessage.class);
myServer.addMessageListener(this, MapMessage.class);
myServer.addMessageListener(this, ShootMessage.class);
myServer.addMessageListener(this, AnimationMessage.class);
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
public void messageReceived(HostedConnection source, Message message) {
LOGGER.log(Level.INFO, "message received from {0}: {1}", source.getId(), message); //NON-NLS
@@ -130,12 +184,24 @@ public void messageReceived(HostedConnection source, Message message) {
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
public void connectionAdded(Server server, HostedConnection hostedConnection) {
LOGGER.log(Level.INFO, "new connection {0}", hostedConnection); //NON-NLS
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
public void connectionRemoved(Server server, HostedConnection hostedConnection) {
LOGGER.log(Level.INFO, "connection closed: {0}", hostedConnection); //NON-NLS
@@ -148,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
LOGGER.log(Level.INFO, "close request"); //NON-NLS
if (myServer != null)

View File

@@ -1,170 +0,0 @@
////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////
package pp.battleship.client;
import com.jme3.app.Application;
import com.jme3.app.state.AbstractAppState;
import com.jme3.app.state.AppStateManager;
import com.jme3.asset.AssetLoadException;
import com.jme3.asset.AssetNotFoundException;
import com.jme3.audio.AudioData;
import com.jme3.audio.AudioNode;
import com.jme3.audio.AudioSource;
import pp.battleship.notification.GameEventListener;
import pp.battleship.notification.SoundEvent;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import java.util.prefs.Preferences;
import static pp.util.PreferencesUtils.getPreferences;
/**
* An application state that plays music.
*/
public class GameMusic extends AbstractAppState implements GameEventListener {
private static final Logger LOGGER = System.getLogger(GameMusic.class.getName());
private static final Preferences PREFERENCES = getPreferences(GameMusic.class);
private static final String ENABLED_PREF = "toggle"; //NON-NLS
private static final String SLIDER_PREF = "slider"; //NON-NLS
private AudioNode music;
private boolean enabled;
private float volume;
public GameMusic(Application app, String musicFilePath) {
this.enabled = PREFERENCES.getBoolean(ENABLED_PREF, true);
this.volume = PREFERENCES.getFloat(SLIDER_PREF, 2.0f);
music = new AudioNode(app.getAssetManager(), musicFilePath, AudioData.DataType.Stream);
music.setLooping(true);
music.setPositional(false);
music.setVolume(1.0f);
if(enabled) {
start();
}
}
/**
* Checks if music is enabled in the preferences.
*
* @return {@code true} if music is enabled, {@code false} otherwise.
*/
public static boolean enabledInPreferences() {
return PREFERENCES.getBoolean(ENABLED_PREF, true);
}
/**
* Returns the volume value that is set in the preferences.
*
* @return {@code true} if sound is enabled, {@code false} otherwise.
*/
public static float volumeInPreferences() {
return PREFERENCES.getFloat(SLIDER_PREF, 2.0f);
}
/**
* Toggles the game music on or off.
*/
public void toggleMusic() {
setEnabled(!isEnabled());
}
/**
* Sets the enabled state of this AppState.
* Overrides {@link AbstractAppState#setEnabled(boolean)}
*
* @param enabled {@code true} to enable the AppState, {@code false} to disable it.
*/
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
if(enabled) {
start();
} else {
stop();
}
LOGGER.log(Level.INFO, "Music enabled: {0}", enabled); //NON-NLS
PREFERENCES.putBoolean(ENABLED_PREF, enabled);
}
/**
* Sets the volume for the music
*
* @param volume the new volume to be set
*/
public void setVolume(float volume) {
this.volume = volume;
music.setVolume(volume);
LOGGER.log(Level.INFO, "Volume set to: {0}", volume); //NON-NLS
PREFERENCES.putFloat(SLIDER_PREF, volume);
}
/**
* Loads a music from the specified file.
*
* @param app The application
* @param name The name of the sound file.
* @return The loaded AudioNode.
*/
private AudioNode loadSound(Application app, String name) {
try {
final AudioNode sound = new AudioNode(app.getAssetManager(), name, AudioData.DataType.Buffer);
sound.setLooping(false);
sound.setPositional(false);
return sound;
}
catch (AssetLoadException | AssetNotFoundException ex) {
LOGGER.log(Level.ERROR, ex.getMessage(), ex);
}
return null;
}
/**
* Starts the music.
*/
public void start() {
if (enabled && (music.getStatus() == AudioSource.Status.Stopped || music.getStatus() == AudioSource.Status.Paused)) {
music.play();
}
}
/**
* Stops the music.
*/
public void stop() {
if (music.getStatus() == AudioSource.Status.Playing) {
music.stop();
}
}
/**
* This method returns the volume
*
* @return float the current volume
*/
public float getVolume() {
return volume;
}
/**
* Returns if music should be played or not
*
* @return boolean value if music is enabled
*/
public boolean isMusicEnabled() {
return enabled;
}
}

View File

@@ -34,7 +34,7 @@ public class GameSound extends AbstractAppState implements GameEventListener {
private AudioNode splashSound;
private AudioNode shipDestroyedSound;
private AudioNode explosionSound;
private AudioNode missleSound;
private AudioNode shellFiredSound;
/**
* Checks if sound is enabled in the preferences.
@@ -79,7 +79,7 @@ public void initialize(AppStateManager stateManager, Application app) {
shipDestroyedSound = loadSound(app, "Sound/Effects/sunken.wav"); //NON-NLS
splashSound = loadSound(app, "Sound/Effects/splash.wav"); //NON-NLS
explosionSound = loadSound(app, "Sound/Effects/explosion.wav"); //NON-NLS
missleSound = loadSound(app, "Sound/Effects/missle.wav");
shellFiredSound = loadSound(app, "Sound/Effects/missle.wav"); //NON-NLS
}
/**
@@ -95,8 +95,7 @@ private AudioNode loadSound(Application app, String name) {
sound.setLooping(false);
sound.setPositional(false);
return sound;
}
catch (AssetLoadException | AssetNotFoundException ex) {
} catch (AssetLoadException | AssetNotFoundException ex) {
LOGGER.log(Level.ERROR, ex.getMessage(), ex);
}
return null;
@@ -110,14 +109,6 @@ public void splash() {
splashSound.playInstance();
}
/**
* Plays the missle flyby sound effect.
*/
public void flyBy() {
if (isEnabled() && missleSound != null)
missleSound.playInstance();
}
/**
* Plays the explosion sound effect.
*/
@@ -134,13 +125,21 @@ public void shipDestroyed() {
shipDestroyedSound.playInstance();
}
/**
* Plays sound effect when a shell has been fired.
*/
public void shellFired() {
if (isEnabled() && shellFiredSound != null)
shellFiredSound.playInstance();
}
@Override
public void receivedEvent(SoundEvent event) {
switch (event.sound()) {
case EXPLOSION -> explosion();
case SPLASH -> splash();
case DESTROYED_SHIP -> shipDestroyed();
case MISSLE_FLYBY -> flyBy();
case SHELL_FIRED -> shellFired();
}
}
}

View File

@@ -7,7 +7,11 @@
package pp.battleship.client;
import com.simsilica.lemur.*;
import com.simsilica.lemur.Button;
import com.simsilica.lemur.Checkbox;
import com.simsilica.lemur.DefaultRangedValueModel;
import com.simsilica.lemur.Label;
import com.simsilica.lemur.Slider;
import com.simsilica.lemur.core.VersionedReference;
import com.simsilica.lemur.style.ElementId;
import pp.dialog.Dialog;
@@ -18,6 +22,8 @@
import java.io.IOException;
import java.util.prefs.Preferences;
import java.lang.System.Logger;
import static pp.battleship.Resources.lookup;
import static pp.util.PreferencesUtils.getPreferences;
@@ -27,12 +33,12 @@
* returning to the game, and quitting the application.
*/
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 String LAST_PATH = "last.file.path";
private final BattleshipApp app;
private final Button loadButton = new Button(lookup("menu.map.load"));
private final Button saveButton = new Button(lookup("menu.map.save"));
private final VersionedReference<Double> volumeRef;
/**
@@ -44,26 +50,23 @@ public Menu(BattleshipApp app) {
super(app.getDialogManager());
this.app = app;
addChild(new Label(lookup("battleship.name"), new ElementId("header"))); //NON-NLS
addChild(new Checkbox(lookup("menu.sound-enabled"),
new StateCheckboxModel(app, GameSound.class)));
new StateCheckboxModel(app, GameSound.class)));
addChild(new Checkbox(lookup("menu.music-toggle"),
new StateCheckboxModel(app, BackgroundMusic.class)));
Slider volumeSlider = new Slider();
volumeSlider.setModel(new DefaultRangedValueModel(0.0, 2.0, app.getStateManager().getState(BackgroundMusic.class).getVolume()));
volumeSlider.setDelta(0.1f);
addChild(volumeSlider);
volumeRef = volumeSlider.getModel().createReference();
addChild(loadButton)
.addClickCommands(s -> ifTopDialog(this::loadDialog));
addChild(saveButton)
.addClickCommands(s -> ifTopDialog(this::saveDialog));
Checkbox musicToggle = new Checkbox(lookup("menu.music.toggle"));
musicToggle.setChecked(app.getGameMusic().isMusicEnabled());
musicToggle.addClickCommands(s -> toggleMusic());
addChild(musicToggle);
Slider volumeSlider = new Slider(lookup("menu.music.slider"));
volumeSlider.setModel(new DefaultRangedValueModel(0.0 , 4.0, app.getGameMusic().getVolume()));
volumeSlider.setDelta(0.4);
addChild(volumeSlider);
volumeRef = volumeSlider.getModel().createReference();
addChild(new Button(lookup("menu.return-to-game")))
.addClickCommands(s -> ifTopDialog(this::close));
addChild(new Button(lookup("menu.quit")))
@@ -72,33 +75,34 @@ public Menu(BattleshipApp app) {
}
/**
* Updates the state of the load/save buttons and volume based on the game logic.
* Updates the state of the load and save buttons based on the game logic.
*/
@Override
public void update() {
loadButton.setEnabled(app.getGameLogic().mayLoadMap());
saveButton.setEnabled(app.getGameLogic().maySaveMap());
}
if(volumeRef.update()){
double newVolume = volumeRef.get();
adjustVolume(newVolume);
/**
* 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());
}
}
/**
* this method adjust the volume for the background music
* Adjusts the volume of the background music.
*
* @param volume is the double value of the volume
* @param volume the new volume level to set, as a double
*/
private void adjustVolume(double volume) {
app.getGameMusic().setVolume((float) volume);
}
/**
* this method toggles the background music on and off
*/
private void toggleMusic() {
app.getGameMusic().toggleMusic();
app.getStateManager().getState(BackgroundMusic.class).setVolume((float) volume);
}
/**
@@ -135,8 +139,7 @@ private void handle(FileAction fileAction, TextInputDialog dialog) {
PREFERENCES.put(LAST_PATH, path);
fileAction.run(new File(path));
dialog.close();
}
catch (IOException e) {
} catch (IOException e) {
app.errorDialog(e.getLocalizedMessage());
}
}
@@ -150,13 +153,13 @@ private void handle(FileAction fileAction, TextInputDialog dialog) {
private void fileDialog(FileAction fileAction, String label) {
final TextInputDialog dialog =
TextInputDialog.builder(app.getDialogManager())
.setLabel(lookup("label.file"))
.setFocus(TextInputDialog::getInput)
.setTitle(label)
.setOkButton(lookup("button.ok"), d -> handle(fileAction, d))
.setNoButton(lookup("button.cancel"))
.setOkClose(false)
.build();
.setLabel(lookup("label.file"))
.setFocus(TextInputDialog::getInput)
.setTitle(label)
.setOkButton(lookup("button.ok"), d -> handle(fileAction, d))
.setNoButton(lookup("button.cancel"))
.setOkClose(false)
.build();
final String path = PREFERENCES.get(LAST_PATH, null);
if (path != null)
dialog.getInput().setText(path.trim());

View File

@@ -31,6 +31,7 @@ class NetworkDialog extends SimpleDialog {
private static final Logger LOGGER = System.getLogger(NetworkDialog.class.getName());
private static final String LOCALHOST = "localhost"; //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 TextField host = new TextField(LOCALHOST);
private final TextField port = new TextField(DEFAULT_PORT);
@@ -52,10 +53,9 @@ class NetworkDialog extends SimpleDialog {
host.setPreferredWidth(400f);
port.setSingleLine(true);
Checkbox serverHost = new Checkbox(lookup("menu.host"));
serverHost.setChecked(false);
serverHost.addClickCommands(s -> toggleServerHost());
addChild(serverHost);
Checkbox hostCheckbox = new Checkbox(lookup("host.own-server"));
hostCheckbox.setChecked(false);
hostCheckbox.addClickCommands(s -> hostServer = !hostServer);
final BattleshipApp app = network.getApp();
final Container input = new Container(new SpringGridLayout());
@@ -63,15 +63,16 @@ class NetworkDialog extends SimpleDialog {
input.addChild(host, 1);
input.addChild(new Label(lookup("port.number") + ": "));
input.addChild(port, 1);
input.addChild(hostCheckbox);
DialogBuilder.simple(app.getDialogManager())
.setTitle(lookup("server.dialog"))
.setExtension(d -> d.addChild(input))
.setOkButton(lookup("button.connect"), d -> connectLocally())
.setNoButton(lookup("button.cancel"), app::closeApp)
.setOkClose(false)
.setNoClose(false)
.build(this);
.setTitle(lookup("server.dialog"))
.setExtension(d -> d.addChild(input))
.setOkButton(lookup("button.connect"), d -> connectHostServer())
.setNoButton(lookup("button.cancel"), app::closeApp)
.setOkClose(false)
.setNoClose(false)
.build(this);
}
/**
@@ -85,56 +86,54 @@ private void connect() {
portNumber = Integer.parseInt(port.getText());
openProgressDialog();
connectionFuture = network.getApp().getExecutor().submit(this::initNetwork);
}
catch (NumberFormatException e) {
} catch (NumberFormatException e) {
network.getApp().errorDialog(lookup("port.must.be.integer"));
}
}
/**
* Starts a server or if not host connects to one
* 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 connectLocally() {
if(hostServer){
private void connectHostServer() {
if (hostServer) {
startServer();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
LOGGER.log(Level.WARNING, e.getMessage(), e.getMessage());
Thread.sleep(START_SERVER_DELAY);
} catch (Exception e) {
LOGGER.log(Level.ERROR, "Server start failed", e); //NON-NLS
}
connect();
} else {
connect();
}
connect();
}
/**
* Starts a host 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() {
LOGGER.log(Level.INFO, "start server"); //NON-NLS
new Thread(() -> {
try{
BattleshipServer battleshipServer = new BattleshipServer();
battleshipServer.run();
try {
LOGGER.log(Level.INFO, "Starting server..."); //NON-NLS
BattleshipServer server = new BattleshipServer(Integer.parseInt(port.getText()));
LOGGER.log(Level.INFO, "Server started"); //NON-NLS
server.run();
} catch (Exception e) {
LOGGER.log(Level.ERROR,e);
LOGGER.log(Level.ERROR, "Server start failed", e); //NON-NLS
}
}).start();
}
/**
* Toggles client/host mode
*/
private void toggleServerHost(){
hostServer = !hostServer;
}
/**
* Creates a dialog indicating that the connection is in progress.
*/
private void openProgressDialog() {
progressDialog = DialogBuilder.simple(network.getApp().getDialogManager())
.setText(lookup("label.connecting"))
.build();
.setText(lookup("label.connecting"))
.build();
progressDialog.open();
}
@@ -147,8 +146,7 @@ private Object initNetwork() {
try {
network.initNetwork(hostname, portNumber);
return null;
}
catch (Exception e) {
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@@ -163,11 +161,9 @@ public void update(float delta) {
try {
connectionFuture.get();
success();
}
catch (ExecutionException e) {
} catch (ExecutionException e) {
failure(e.getCause());
}
catch (InterruptedException e) {
} catch (InterruptedException e) {
LOGGER.log(Level.WARNING, "Interrupted!", e); //NON-NLS
Thread.currentThread().interrupt();
}

View File

@@ -10,7 +10,18 @@
import pp.battleship.message.client.ClientInterpreter;
import pp.battleship.message.client.ClientMessage;
/**
* Represents a received message from a client.
*
* @param message the client message
* @param from the ID of the sender
*/
record ReceivedMessage(ClientMessage message, int from) {
/**
* Processes the received message using the specified interpreter.
*
* @param interpreter the client interpreter
*/
void process(ClientInterpreter interpreter) {
message.accept(interpreter, from);
}

View File

@@ -143,6 +143,10 @@ public float getHeight() {
return FIELD_SIZE * map.getHeight();
}
public static float getFieldSize() {
return FIELD_SIZE;
}
/**
* Converts coordinates from view coordinates to model coordinates.
*

View File

@@ -7,17 +7,20 @@
package pp.battleship.client.gui;
import com.jme3.material.Material;
import com.jme3.material.RenderState;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector3f;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import com.jme3.scene.shape.Sphere;
import pp.battleship.model.Battleship;
import pp.battleship.model.IntPoint;
import pp.battleship.model.Shell;
import pp.battleship.model.Shot;
import pp.util.Position;
import static com.jme3.material.Materials.UNSHADED;
/**
* Synchronizes the visual representation of the ship map with the game model.
* It handles the rendering of ships and shots on the map view, updating the view
@@ -29,10 +32,6 @@ class MapViewSynchronizer extends ShipMapSynchronizer {
private static final float SHOT_DEPTH = -2f;
private static final float SHIP_DEPTH = 0f;
private static final float INDENT = 4f;
private static final float 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
private static final ColorRGBA HIT_COLOR = ColorRGBA.Red;
@@ -72,9 +71,9 @@ public Spatial visit(Shot shot) {
// Create and return a rectangle representing the shot
return view.getApp().getDraw().makeRectangle(p1.getX(), p1.getY(),
SHOT_DEPTH,
p2.getX() - p1.getX(), p2.getY() - p1.getY(),
color);
SHOT_DEPTH,
p2.getX() - p1.getX(), p2.getY() - p1.getY(),
color);
}
/**
@@ -118,27 +117,23 @@ public Spatial visit(Battleship ship) {
/**
* Creates a visual representation of a shell on the map.
* The shell is represented as a black ellipse.
*
* @param shell the Shell object representing the shell in the model
* @return a Spatial representing the shell
* @return a Spatial representing the shell on the map
*/
@Override
public Spatial visit(Shell shell) {
final Node shellNode = new Node("shell");
final Position p1 = view.modelToView(shell.getX(), shell.getY());
final Position p2 = view.modelToView(shell.getX() + SHELL_SIZE, shell.getY() + SHELL_SIZE);
final Position startPosition = view.modelToView(SHELL_CENTERED_IN_MAP_GRID, SHELL_CENTERED_IN_MAP_GRID);
shellNode.attachChild(view.getApp().getDraw().makeRectangle(startPosition.getX(), startPosition.getY(), SHELL_DEPTH, p2.getX() - p1.getX(), p2.getY() - p1.getY(), ColorRGBA.Magenta));
shellNode.setLocalTranslation(startPosition.getX(), startPosition.getY(), SHELL_DEPTH);
shellNode.addControl(new ShellControlMap(p1, view.getApp(), new IntPoint(shell.getX(), shell.getY())));
return shellNode;
Geometry ellipse = new Geometry("ellipse", new Sphere(50, 50, MapView.getFieldSize() / 2 * 0.8f));
Material mat = new Material(view.getApp().getAssetManager(), UNSHADED); //NON-NLS
mat.getAdditionalRenderState().setBlendMode(RenderState.BlendMode.Alpha);
mat.getAdditionalRenderState().setFaceCullMode(RenderState.FaceCullMode.Off);
mat.setColor("Color", ColorRGBA.Black);
ellipse.setMaterial(mat);
ellipse.addControl(new ShellMapControl(view, shell));
return ellipse;
}
/**
* Creates a line geometry representing part of the ship's border.
*

View File

@@ -1,193 +0,0 @@
package pp.battleship.client.gui;
import com.jme3.effect.ParticleEmitter;
import com.jme3.effect.ParticleMesh;
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 com.jme3.scene.control.Control;
import pp.battleship.client.BattleshipApp;
import pp.battleship.model.Shot;
public class ParticleHandler {
private final BattleshipApp app;
static final System.Logger LOGGER = System.getLogger(ParticleHandler.class.getName());
private Material material;
/**
* Constructs a new ParticleHandler
*
* @param app the main battleship application
*/
public ParticleHandler(BattleshipApp app) {
this.app = app;
material = new Material(app.getAssetManager(), "Common/MatDefs/Misc/Particle.j3md");
}
/**
* this method is used to create a hit effect at the position of a node
*
* @param node the node of the battleship where the effect should be attached to
* @param shot the shot that hit a target
*/
public void createHitParticles(Node node, Shot shot) {
ParticleEmitter smokeParticles = new ParticleEmitter("Effect", ParticleMesh.Type.Triangle,1000);
smokeParticles.setMaterial(material);
smokeParticles.setImagesX(2);
smokeParticles.setImagesY(2);
smokeParticles.setStartColor(ColorRGBA.Orange);
smokeParticles.setEndColor(ColorRGBA.Black);
smokeParticles.getParticleInfluencer().setInitialVelocity(new Vector3f(0,0.8f,0));
smokeParticles.setStartSize(0.5f);
smokeParticles.setEndSize(0.04f);
smokeParticles.setGravity(0, -0.1f, 0);
smokeParticles.setLowLife(1f);
smokeParticles.setHighLife(4f);
smokeParticles.setParticlesPerSec(0);
smokeParticles.setLocalTranslation(shot.getY() + 0.5f, 0 , shot.getX() + 0.5f);
smokeParticles.emitAllParticles();
ParticleEmitter particles2 = new ParticleEmitter("Effect", ParticleMesh.Type.Triangle,300);
particles2.setMaterial(material);
particles2.setImagesX(2);
particles2.setImagesY(2);
particles2.setStartColor(ColorRGBA.Orange);
particles2.setEndColor(ColorRGBA.Yellow);
particles2.getParticleInfluencer().setInitialVelocity(new Vector3f(0,2,0));
particles2.setStartSize(0.7f);
particles2.setEndSize(0.1f);
particles2.setGravity(0, 0, 0);
particles2.setLowLife(0.5f);
particles2.setHighLife(1.5f);
particles2.setParticlesPerSec(0);
particles2.setLocalTranslation(shot.getY() + 1f, 0 , shot.getX() + 1f);
particles2.emitAllParticles();
ParticleEmitter particles3 = new ParticleEmitter("Effect", ParticleMesh.Type.Triangle,300);
particles3.setMaterial(material);
particles3.setImagesX(1);
particles3.setImagesY(1);
particles3.setStartColor(ColorRGBA.Red);
particles3.setEndColor(ColorRGBA.Gray);
particles3.getParticleInfluencer().setInitialVelocity(new Vector3f(0,0.5f,0));
particles3.setStartSize(0.8f);
particles3.setEndSize(0.1f);
particles3.setGravity(0, 0, 0);
particles3.setLowLife(0.5f);
particles3.setHighLife(0.8f);
particles3.setParticlesPerSec(0);
particles3.setLocalTranslation(shot.getY() + 1f, 0 , shot.getX() + 1f);
particles3.emitAllParticles();
ParticleEmitter flames = new ParticleEmitter("Effect", ParticleMesh.Type.Triangle,300);
flames.setMaterial(material);
flames.setImagesX(1);
flames.setImagesY(1);
flames.setStartColor(ColorRGBA.Red);
flames.setEndColor(ColorRGBA.Orange);
flames.getParticleInfluencer().setInitialVelocity(new Vector3f(0,1.0f,0));
flames.setStartSize(0.4f);
flames.setEndSize(0.1f);
flames.setGravity(0, -0.2f, 0);
flames.setLowLife(0.7f);
flames.setHighLife(1.5f);
flames.setLocalTranslation(shot.getY(), 0 , shot.getX());
flames.setLocalTranslation(flames.getLocalTranslation().subtract(node.getLocalTranslation()));
flames.setParticlesPerSec(70);
node.attachChild(smokeParticles);
smokeParticles.addControl((Control) new ParticleControl(smokeParticles, node));
node.attachChild(particles2);
particles2.addControl((Control) new ParticleControl(particles2, node));
node.attachChild(particles3);
particles3.addControl((Control) new ParticleControl(particles3, node));
//node.attachChild(flames);
//flames.addControl((Control) new ParticleControl(flames, node));
LOGGER.log(System.Logger.Level.DEBUG, "Hit-particles at {0}", smokeParticles.getLocalTranslation().toString());
}
/**
* Creates a miss effect at a certain location
* @param shot the shot that missed
* @return A ParticleEmitter
*/
public ParticleEmitter createMissParticles(Shot shot) {
ParticleEmitter particles = new ParticleEmitter("MissEffect", ParticleMesh.Type.Triangle, 200);
particles.setMaterial(material);
particles.setImagesX(2);
particles.setImagesY(2);
particles.setStartColor(ColorRGBA.Blue);
particles.setEndColor(ColorRGBA.White);
particles.getParticleInfluencer().setInitialVelocity(new Vector3f(0.01f, 3f, 0.01f));
particles.setStartSize(0.05f);
particles.setEndSize(0.4f);
particles.setGravity(0, 2f, 0);
particles.setLowLife(1.0f);
particles.setHighLife(2.2f);
particles.setParticlesPerSec(0);
particles.setLocalTranslation(shot.getY(), -0.5f , shot.getX());
particles.emitAllParticles();
LOGGER.log(System.Logger.Level.DEBUG, "Miss-particles at {0}", particles.getLocalTranslation().toString());
return particles;
}
/**
* This inner class is used to control the effects
*/
private static class ParticleControl extends AbstractControl {
private final ParticleEmitter emitter;
private final Node parentNode;
/**
* this constructor is used to when the particle should be attached to a specific node
*
* @param emitter the Particle emitter to be controlled
* @param parentNode the node to be attached
*/
public ParticleControl(ParticleEmitter emitter, Node parentNode) {
this.emitter = emitter;
this.parentNode = parentNode;
}
/**
* This constructor is used when the particle shouldn't be attached to
* a specific node
*
* @param emitter the Particle emitter to be controlled
*/
public ParticleControl(ParticleEmitter emitter) {
this.emitter = emitter;
this.parentNode = null;
}
/**
* The method which checks if the particle 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

@@ -7,18 +7,18 @@
package pp.battleship.client.gui;
import com.jme3.effect.ParticleEmitter;
import com.jme3.effect.ParticleMesh;
import com.jme3.material.Material;
import com.jme3.material.RenderState.BlendMode;
import com.jme3.math.ColorRGBA;
import com.jme3.math.FastMath;
import com.jme3.math.Quaternion;
import com.jme3.math.Vector3f;
import com.jme3.renderer.queue.RenderQueue;
import com.jme3.renderer.queue.RenderQueue.ShadowMode;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import com.jme3.scene.shape.Box;
import com.jme3.scene.shape.Cylinder;
import pp.battleship.client.BattleshipApp;
import pp.battleship.model.*;
@@ -35,17 +35,20 @@
class SeaSynchronizer extends ShipMapSynchronizer {
private static final String UNSHADED = "Common/MatDefs/Misc/Unshaded.j3md"; //NON-NLS
private static final String KING_GEORGE_V_MODEL = "Models/KingGeorgeV/KingGeorgeV.j3o"; //NON-NLS
private static final String DESTROYER_MODEL = "Models/Destroyer/Destroyer.j3o"; //NON-NLS
private static final String DESTROYER_TEXTURE = "Models/Destroyer/BattleshipC.jpg"; //NON-NLS
private static final String TYPE_II_UBOAT_MODEL = "Models/TypeIIUboat/TypeIIUboat.j3o"; //NON-NLS
private static final String TYPE_II_UBOAT_TEXTURE = "Models/TypeIIUboat/Type_II_U-boat_diff.jpg"; //NON-NLS
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 SHOT = "shot"; //NON-NLS
private static final String SHELL = "shell"; //NON-NLS
private static final ColorRGBA BOX_COLOR = ColorRGBA.Gray;
private static final ColorRGBA SPLASH_COLOR = new ColorRGBA(0f, 0f, 1f, 0.4f);
private static final ColorRGBA HIT_COLOR = new ColorRGBA(1f, 0f, 0f, 0.4f);
private static final String BOMB = "Models/Bomb/Files/Bomb GBU-43B(MOAB).obj";
private final ShipMap map;
private final BattleshipApp app;
private final ParticleHandler handler;
/**
* Constructs a {@code SeaSynchronizer} object with the specified application, root node, and ship map.
@@ -58,41 +61,9 @@ public SeaSynchronizer(BattleshipApp app, Node root, ShipMap map) {
super(app.getGameLogic().getOwnMap(), root);
this.app = app;
this.map = map;
handler = new ParticleHandler(app);
addExisting();
}
/**
* Visits a {@link Shell} and creates a graphical representation of it.
*
* @param shell the shell to be represented
* @return the graphical representation of the shell
*/
@Override
public Spatial visit(Shell shell) {
final Node node = new Node("shell");
final Spatial model = app.getAssetManager().loadModel(BOMB);
model.rotate(-PI/2, 0, 0);
model.scale(0.09f);
model.setShadowMode(ShadowMode.CastAndReceive);
model.move(0, 0, 0);
node.attachChild(model);
final float x = shell.getY();
final float z = shell.getX();
node.setLocalTranslation(x, 8f, z);
ShellControll control = new ShellControll(shell, app);
node.addControl(control);
return node;
}
/**
* Visits a {@link Shot} and creates a graphical representation of it.
* If the shot is a hit, it attaches the representation to the ship node.
@@ -103,7 +74,7 @@ public Spatial visit(Shell shell) {
*/
@Override
public Spatial visit(Shot shot) {
return shot.isHit() ? handleHit(shot) : handler.createMissParticles(shot);
return shot.isHit() ? handleHit(shot) : handleMiss(shot);
}
/**
@@ -111,38 +82,127 @@ public Spatial visit(Shot shot) {
* contains the ship model as a child so that it moves with the ship.
*
* @param shot a hit
* @return always null to prevent the representation from being sattached
* @return always null to prevent the representation from being attached
* to the items node as well
*/
private Spatial handleHit(Shot shot) {
final Battleship ship = requireNonNull(map.findShipAt(shot), "Missing ship");
final Node shipNode = requireNonNull((Node) getSpatial(ship), "Missing ship node");
handler.createHitParticles(shipNode, shot);
final ParticleEmitter debris = createDebrisEffect(shot);
shipNode.attachChild(debris);
final ParticleEmitter fire = createFireEffect(shot, shipNode);
shipNode.attachChild(fire);
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;
}
/**
* Creates a cylinder geometry representing the specified shot.
* The appearance of the cylinder depends on whether the shot is a hit or a miss.
* 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 shot the shot to be represented
* @return the geometry representing the shot
* @param shell the shell to be represented
* @return the node containing the graphical representation of the shell
*/
private Geometry createCylinder(Shot shot) {
final ColorRGBA color = shot.isHit() ? HIT_COLOR : SPLASH_COLOR;
final float height = shot.isHit() ? 1.2f : 0.1f;
@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;
}
final Cylinder cylinder = new Cylinder(2, 20, 0.45f, height, true);
final Geometry geometry = new Geometry(SHOT, cylinder);
geometry.setMaterial(createColoredMaterial(color));
geometry.rotate(HALF_PI, 0f, 0f);
// compute the center of the shot in world coordinates
geometry.setLocalTranslation(shot.getY() + 0.5f, 0f, shot.getX() + 0.5f);
return geometry;
/**
* 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;
}
/**
@@ -173,33 +233,13 @@ public Spatial visit(Battleship ship) {
* @return the spatial representing the battleship
*/
private Spatial createShip(Battleship ship) {
final int len = ship.getLength();
Quaternion q0 = new Quaternion();
Quaternion q1 = new Quaternion();
q1.fromAngleAxis(PI/2, new Vector3f(1, 0, 0));
Quaternion q2 = new Quaternion();
q2.fromAngleAxis(PI/2, new Vector3f(1, 0, 0));
switch (len) {
case 1 -> {
return createBattleship(ship, "Models/Uboat/uboat.j3o", 0.2f, new Vector3f(0.0f, -0.1f, 0.0f), q0);
}
case 2 -> {
return createBattleship(ship, "Models/KingGeorgeV/KingGeorgeV.j3o", 1.0f, new Vector3f(0.0f, 0.0f, 0.0f), q0);
}
case 3 -> {
return createBattleship(ship, "Models/EssexClass/essex.j3o", 0.8f, new Vector3f(0.0f, 0.3f, 0.0f), q2);
}
case 4 -> {
return createBattleship(ship, "Models/Container/container.j3o", 0.05f, new Vector3f(0.0f, 0.0f, 0.0f), q1);
}
default -> {
return createBox(ship);
}
}
return switch (ship.getLength()) {
case 1 -> createVessel(ship);
case 2 -> createSubmarine(ship);
case 3 -> createDestroyer(ship);
case 4 -> createBattleship(ship);
default -> createBox(ship);
};
}
/**
@@ -210,10 +250,10 @@ private Spatial createShip(Battleship ship) {
*/
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);
0.3f,
0.5f * (ship.getMaxX() - ship.getMinX()) + 0.3f);
final Geometry geometry = new Geometry(SHIP, box);
geometry.setMaterial(createColoredMaterial(BOX_COLOR));
geometry.setMaterial(createColoredMaterial());
geometry.setShadowMode(ShadowMode.CastAndReceive);
return geometry;
@@ -225,36 +265,90 @@ private Spatial createBox(Battleship ship) {
* the material's render state is set to use alpha blending, allowing for
* semi-transparent rendering.
*
* @param color the {@link ColorRGBA} to be applied to the material. If the alpha value
* of the color is less than 1, the material will support transparency.
* @return a {@link Material} instance configured with the specified color and,
* if necessary, alpha blending enabled.
*/
private Material createColoredMaterial(ColorRGBA color) {
private Material createColoredMaterial() {
final Material material = new Material(app.getAssetManager(), UNSHADED);
if (color.getAlpha() < 1f)
if (SeaSynchronizer.BOX_COLOR.getAlpha() < 1f)
material.getAdditionalRenderState().setBlendMode(BlendMode.Alpha);
material.setColor(COLOR, color);
material.setColor(COLOR, SeaSynchronizer.BOX_COLOR);
return material;
}
/**
* Creates a 3D model to represent a "battleship".
* Creates a detailed 3D model to represent a "King George V" battleship.
*
* @param ship the battleship to be represented
* @param path the battleship to be represented
* @param scale the battleship to be represented
* @param translation the battleship to be represented
* @param rotation the battleship to be represented
* @return the spatial representing the battleship
* @return the spatial representing the "King George V" battleship
*/
private Spatial createBattleship(Battleship ship, String path, float scale, Vector3f translation, Quaternion rotation) {
final Spatial model = app.getAssetManager().loadModel(path);
private Spatial createBattleship(Battleship ship) {
final Spatial model = app.getAssetManager().loadModel(KING_GEORGE_V_MODEL);
model.rotate(-HALF_PI, calculateRotationAngle(ship.getRot()), 0f);
model.rotate(rotation);
model.scale(scale);
model.setLocalTranslation(translation);
model.scale(1.48f);
model.setShadowMode(ShadowMode.CastAndReceive);
return model;
}
/**
* Creates a detailed 3D model to represent a destroyer battleship.
*
* @param ship the battleship to be represented
* @return the spatial representing the destroyer battleship
*/
private Spatial createDestroyer(Battleship ship) {
final Spatial model = app.getAssetManager().loadModel(DESTROYER_MODEL);
Material mat = new Material(app.getAssetManager(), UNSHADED);
mat.setTexture("ColorMap", app.getAssetManager().loadTexture(DESTROYER_TEXTURE));
mat.getAdditionalRenderState().setBlendMode(BlendMode.Off);
model.setMaterial(mat);
model.setQueueBucket(RenderQueue.Bucket.Opaque);
model.rotate(-HALF_PI, calculateRotationAngle(ship.getRot()), 0f);
model.scale(0.1f);
model.setLocalTranslation(0f, 0.25f, 0f);
model.setShadowMode(ShadowMode.CastAndReceive);
return model;
}
/**
* Creates a detailed 3D model to represent a Type II U-boat submarine.
*
* @param ship the battleship to be represented
* @return the spatial representing the Type II U-boat submarine
*/
private Spatial createSubmarine(Battleship ship) {
final Spatial model = app.getAssetManager().loadModel(TYPE_II_UBOAT_MODEL);
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.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);
return model;

View File

@@ -0,0 +1,42 @@
package pp.battleship.client.gui;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.control.AbstractControl;
/**
* 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 {
private final static float SHELL_SPEED = 7.5f;
private final static float SHELL_ROTATION_SPEED = 0.5f;
private final static float MIN_HEIGHT = 0.7f;
/**
* 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 tpf time per frame, used to ensure consistent movement speed across different frame rates
*/
@Override
protected void controlUpdate(float tpf) {
spatial.move(0, -SHELL_SPEED * tpf, 0);
spatial.rotate(0, SHELL_ROTATION_SPEED, 0);
if (spatial.getLocalTranslation().getY() <= MIN_HEIGHT) {
spatial.getParent().detachChild(spatial);
}
}
/**
* Renders the shell. This method is currently not used.
*
* @param rm the RenderManager
* @param vp the ViewPort
*/
@Override
protected void controlRender(RenderManager rm, ViewPort vp) {
// nothing to do here
}
}

View File

@@ -1,67 +0,0 @@
package pp.battleship.client.gui;
import com.jme3.math.Vector3f;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.control.AbstractControl;
import pp.battleship.client.BattleshipApp;
import pp.battleship.message.client.AnimationEndMessage;
import pp.battleship.model.IntPoint;
import pp.util.Position;
/**
* Controls the movement of a shell in a specified position on the battlefield.
* This control updates the shell's position and sends a message when it reaches
* its target location.
*/
public class ShellControlMap extends AbstractControl {
private final Position position; // Target position for the shell
private final IntPoint pos; // Target coordinates as an IntPoint
private static final Vector3f vector = new Vector3f(); // Movement vector
private final BattleshipApp app; // Reference to the main application
/**
* Constructs a ShellControlMap object with the specified target position,
* application instance, and target coordinates.
*
* @param position The target Position for the shell.
* @param app The BattleshipApp instance managing the game logic.
* @param pos The IntPoint representing the target coordinates of the shell.
*/
public ShellControlMap(Position position, BattleshipApp app, IntPoint pos) {
super();
this.position = position;
this.pos = pos;
this.app = app;
vector.set(new Vector3f(position.getX(), position.getY(), 0));
}
/**
* Updates the shell's position based on the time per frame.
* If the shell reaches or exceeds the target position, it detaches
* the shell from the scene and sends an animation end message.
*
* @param tpf Time per frame, used to calculate movement.
*/
@Override
protected void controlUpdate(float tpf) {
spatial.move(vector.mult(tpf));
if (spatial.getLocalTranslation().getX() >= position.getX() &&
spatial.getLocalTranslation().getY() >= position.getY()) {
spatial.getParent().detachChild(spatial);
app.getGameLogic().send(new AnimationEndMessage(pos));
}
}
/**
* Renders the shell control. This method can be overridden to implement
* custom rendering behavior, but it is currently empty.
*
* @param rm The RenderManager for rendering the control.
* @param vp The ViewPort where the control is rendered.
*/
@Override
protected void controlRender(RenderManager rm, ViewPort vp) {
// No rendering logic implemented for ShellControlMap
}
}

View File

@@ -1,62 +0,0 @@
package pp.battleship.client.gui;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.control.AbstractControl;
import pp.battleship.client.BattleshipApp;
import pp.battleship.message.client.AnimationEndMessage;
import pp.battleship.model.IntPoint;
import pp.battleship.model.Shell;
import java.util.logging.Logger;
/**
* Controls the movement and behavior of a shell in the battleship game.
* This control updates the position of the shell and sends a message
* when the shell reaches the ground.
*/
public class ShellControll extends AbstractControl {
private final Shell shell;
private final BattleshipApp app;
private static final float MOVE_SPEED = 20.0f; // Speed at which the shell moves
/**
* Constructs a ShellControll object with the specified shell and application instance.
*
* @param shell The Shell instance to control.
* @param app The BattleshipApp instance managing the game logic.
*/
public ShellControll(Shell shell, BattleshipApp app) {
this.shell = shell;
this.app = app;
}
/**
* Updates the shell's position based on the time per frame.
* If the shell's position falls below a certain threshold,
* it detaches the shell from the scene and sends an animation end message.
*
* @param tpf Time per frame, used to calculate movement.
*/
@Override
protected void controlUpdate(float tpf) {
spatial.move(0, -MOVE_SPEED * tpf, 0);
if (spatial.getLocalTranslation().getY() <= 0.1f) {
spatial.getParent().detachChild(spatial);
app.getGameLogic().send(new AnimationEndMessage(new IntPoint(shell.getX(), shell.getY())));
}
}
/**
* Renders the shell control. This method can be overridden to implement
* custom rendering behavior, but it is currently empty.
*
* @param rm The RenderManager for rendering the control.
* @param vp The ViewPort where the control is rendered.
*/
@Override
protected void controlRender(RenderManager rm, ViewPort vp) {
// No rendering logic implemented for ShellControll
}
}

View File

@@ -0,0 +1,82 @@
package pp.battleship.client.gui;
import com.jme3.math.Vector3f;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.control.AbstractControl;
import pp.battleship.model.Shell;
import pp.util.Position;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
/**
* 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
* using linear interpolation over a specified duration.
*/
public class ShellMapControl extends AbstractControl {
private static final Logger LOGGER = System.getLogger(ShellMapControl.class.getName());
/**
* The duration of the shell animation in seconds.
*/
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);
}
/**
* Updates the position of the shell in the view with linear interpolation.
* This method is called during the update phase.
*
* @param tpf the time per frame
*/
@Override
protected void controlUpdate(float tpf) {
// adjust speed by changing the multiplier
progress += tpf * ANIMATION_DURATION;
// 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 render phase.
* Currently, it does nothing.
*
* @param rm the RenderManager
* @param vp the ViewPort
*/
@Override
protected void controlRender(RenderManager rm, ViewPort vp) {
// nothing to do here
}
}

View File

@@ -23,12 +23,6 @@
* The ship oscillates to simulate a realistic movement on water, based on its orientation and length.
*/
class ShipControl extends AbstractControl {
/**
* The sinking height, after wich the ship will get removed
*/
private static final Float SINKING_HEIGHT = -0.6f;
/**
* The axis of rotation for the ship's pitch (tilting forward and backward).
*/
@@ -54,11 +48,10 @@ class ShipControl extends AbstractControl {
*/
private float time;
/**
* The ship, that the ShipControl controls
*/
private final Battleship ship;
private static final float SINKING_HEIGHT = -0.6f;
/**
* Constructs a new ShipControl instance for the specified Battleship.
* The ship's orientation determines the axis of rotation, while its length influences
@@ -67,8 +60,6 @@ class ShipControl extends AbstractControl {
* @param ship the Battleship object to control
*/
public ShipControl(Battleship ship) {
this.ship = ship;
// Determine the axis of rotation based on the ship's orientation
axis = switch (ship.getRot()) {
case LEFT, RIGHT -> Vector3f.UNIT_X;
@@ -78,6 +69,8 @@ public ShipControl(Battleship ship) {
// Set the cycle duration and amplitude based on the ship's length
cycle = ship.getLength() * 2f;
amplitude = 5f * DEG_TO_RAD / ship.getLength();
this.ship = ship;
}
/**
@@ -91,11 +84,13 @@ protected void controlUpdate(float tpf) {
// If spatial is null, do nothing
if (spatial == null) return;
if (ship.isDestroyed() && spatial.getLocalTranslation().getY() < SINKING_HEIGHT) { // removes the ship, if it is completely sunk
spatial.getParent().detachChild(spatial);
}
else if (ship.isDestroyed() && spatial.getLocalTranslation().getY() >= SINKING_HEIGHT) { // sink the ship, if it's not completely sunk
spatial.move(0, tpf * -0.03f, 0);
// Handle ship sinking by moving it downwards
if (ship.isDestroyed()) {
if (spatial.getLocalTranslation().getY() < SINKING_HEIGHT) {
spatial.getParent().detachChild(spatial);
} else {
spatial.move(0, -tpf * 0.1f, 0);
}
}
// Update the time within the oscillation cycle

View File

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

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 166 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

File diff suppressed because one or more lines are too long

View File

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

File diff suppressed because one or more lines are too long

Binary file not shown.

Before

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 332 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 629 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 122 KiB

View File

@@ -1,35 +0,0 @@
# Blender 4.2.1 LTS MTL File: 'untitled.blend'
# www.blender.org
newmtl Bridge
Ns 250.000000
Ka 1.000000 1.000000 1.000000
Ks 0.500000 0.500000 0.500000
Ni 1.500000
illum 2
map_Kd Bridge_baseColor.png
map_Ke Bridge_emissive.jpg
map_d Bridge_baseColor.png
map_Bump -bm 1.000000 Bridge_normal.jpg
newmtl Containers
Ns 250.000000
Ka 1.000000 1.000000 1.000000
Ks 0.500000 0.500000 0.500000
Ke 0.000000 0.000000 0.000000
Ni 1.500000
d 1.000000
illum 2
map_Kd Containers_baseColor.jpg
map_Bump -bm 1.000000 Containers_normal.jpg
newmtl Hull
Ns 250.000000
Ka 1.000000 1.000000 1.000000
Ks 0.500000 0.500000 0.500000
Ke 0.000000 0.000000 0.000000
Ni 1.500000
d 1.000000
illum 2
map_Kd Hull_baseColor.jpg
map_Bump -bm 1.000000 Hull_normal.jpg

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 360 KiB

View File

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

Binary file not shown.

Before

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 264 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 80 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 98 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 78 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 78 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 78 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 78 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 78 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 78 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 78 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 78 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 78 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 78 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 78 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 78 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 B

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