Adding back lost changes and finishing splitting last controllers.

- renamed fxml and their controllers to match
- removed old controllers
- finished lobby and lobbyhost controllers

#story[1261]
This commit is contained in:
Jessica Syder
2017-09-08 18:08:58 +12:00
parent a5d3434a70
commit a5050b8ea8
32 changed files with 193 additions and 579 deletions
@@ -0,0 +1,99 @@
package visualiser.Controllers;
import javafx.application.Platform;
import javafx.beans.property.Property;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import shared.model.Bearing;
import shared.model.Wind;
/**
* Controller for the wind direction arrow on the race screen.
*/
public class ArrowController {
private @FXML StackPane arrowStackPane;
private @FXML ImageView arrowImage;
private @FXML Label speedLabel;
private final static Integer MIN_KNOTS = 2; // knots for min_height
private final static Integer MAX_KNOTS = 30; // knots for max_height
private final static Integer MIN_HEIGHT = 25; // min arrow height
private final static Integer MAX_HEIGHT = 75; // max arrow height
/**
* Sets which wind property the arrow control should bind to.
* @param wind The wind property to bind to.
*/
public void setWindProperty(Property<Wind> wind) {
wind.addListener((observable, oldValue, newValue) -> {
if (newValue != null) {
Platform.runLater(() -> updateWind(newValue));
}
});
}
/**
* Updates the control to use the new wind value.
* This updates the arrow direction (due to bearing), arrow length (due to speed), and label (due to speed).
* @param wind The wind value to use.
*/
private void updateWind(Wind wind) {
updateWindBearing(wind.getWindDirection());
updateWindSpeed(wind.getWindSpeed());
}
/**
* Updates the control to account for the new wind speed.
* This changes the length (height) of the wind arrow, and updates the speed label.
* @param speedKnots The new wind speed, in knots.
*/
private void updateWindSpeed(double speedKnots) {
updateWindArrowLength(speedKnots);
updateWindSpeedLabel(speedKnots);
}
/**
* Updates the length of the wind arrow according to the specified wind speed.
* @param speedKnots Wind speed, in knots.
*/
private void updateWindArrowLength(double speedKnots) {
double deltaKnots = MAX_KNOTS - MIN_KNOTS;
double deltaHeight = MAX_HEIGHT - MIN_HEIGHT;
//Clamp speed.
if (speedKnots > MAX_KNOTS) {
speedKnots = MAX_KNOTS;
} else if (speedKnots < MIN_KNOTS) {
speedKnots = MIN_KNOTS;
}
//How far between the knots bounds is the current speed?
double currentDeltaKnots = speedKnots - MIN_KNOTS;
double currentKnotsScalar = currentDeltaKnots / deltaKnots;
//Thus, how far between the pixel height bounds should the arrow height be?
double newHeight = MIN_HEIGHT + (currentKnotsScalar * deltaHeight);
arrowImage.setFitHeight(newHeight);
}
/**
* Updates the wind speed label according to the specified wind speed.
* @param speedKnots Wind speed, in knots.
*/
private void updateWindSpeedLabel(double speedKnots) {
speedLabel.setText(String.format("%.1fkn", speedKnots));
}
/**
* Updates the control to account for a new wind bearing.
* This rotates the arrow according to the bearing.
* @param bearing The bearing to use to rotate arrow.
*/
private void updateWindBearing(Bearing bearing) {
//Rotate the wind arrow.
arrowStackPane.setRotate(bearing.degrees());
}
}
@@ -5,43 +5,24 @@ import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;
import mock.app.Event;
import org.xml.sax.SAXException;
import shared.exceptions.InvalidBoatDataException;
import shared.exceptions.InvalidRaceDataException;
import shared.exceptions.InvalidRegattaDataException;
import shared.exceptions.XMLReaderException;
import visualiser.model.RaceConnection;
import javax.xml.bind.JAXBException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.soap.Text;
import java.io.IOException;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ResourceBundle;
//TODO it appears this view/controller was replaced by Lobby.fxml. Remove?
/**
* Controls the connection that the VIsualiser can connect to.
*/
public class ConnectionController extends Controller {
@FXML
private AnchorPane connectionWrapper;
@FXML
private TableView<RaceConnection> connectionTable;
@FXML
private TableColumn<RaceConnection, String> hostnameColumn;
@FXML
private TableColumn<RaceConnection, String> statusColumn;
@FXML
private Button connectButton;
@FXML
private TextField urlField;
@FXML
private TextField portField;
public class ConnectionController extends Controller2 {
@FXML AnchorPane connectionWrapper;
@FXML TableView<RaceConnection> connectionTable;
@FXML TableColumn<RaceConnection, String> hostnameColumn;
@FXML TableColumn<RaceConnection, String> statusColumn;
@FXML Button connectButton;
@FXML TextField urlField;
@FXML TextField portField;
/*Title Screen fxml items*/
@@ -87,7 +68,6 @@ public class ConnectionController extends Controller {
@Override
public void initialize(URL location, ResourceBundle resources) {
// TODO - replace with config file
connections = FXCollections.observableArrayList();
@@ -143,5 +123,4 @@ public class ConnectionController extends Controller {
}
}
}
@@ -1,32 +0,0 @@
package visualiser.Controllers;
import javafx.fxml.Initializable;
import java.net.URL;
import java.util.ResourceBundle;
/**
* Controller parent for app controllers.
* Created by fwy13 on 15/03/2017.
*/
public abstract class Controller implements Initializable {
protected MainController parent;
/**
* Sets the parent of the application
*
* @param parent controller
*/
public void setParent(MainController parent) {
this.parent = parent;
}
/**
* Initialisation class that is run on start up.
*
* @param location resources location
* @param resources resources bundle
*/
@Override
public abstract void initialize(URL location, ResourceBundle resources);
}
@@ -0,0 +1,91 @@
package visualiser.Controllers;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Modality;
import javafx.stage.Stage;
import visualiser.app.App;
import java.io.IOException;
/**
* Abstract controller class to give each subclass the functionality to load
* a new scene into the existing stage, or create a new popup window.
*/
public abstract class Controller2 {
Stage stage = App.getStage();
protected void loadTitleScreen() throws IOException {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/visualiser/scenes/title.fxml"));
Parent root = loader.load();
stage.setResizable(false);
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
/**
* Used to load a new scene in the currently open stage.
* @param fxmlUrl the URL of the FXML file to be loaded
* @return the controller of the new scene
* @throws IOException if there is an issue with the fxmlUrl
*/
protected Controller2 loadScene(String fxmlUrl) throws IOException {
// load the correct fxml file
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource
("/visualiser/scenes/"+fxmlUrl));
Parent root = loader.load();
// reuse previous stage and it's window size
Stage stage = App.getStage();
Double stageHeight = stage.getHeight();
Double stageWidth = stage.getWidth();
// set new scene into existing window
Scene scene = new Scene(root, stageWidth, stageHeight);
stage.setScene(scene);
stage.setResizable(true);
stage.show();
stage.setHeight(stageHeight);
stage.setWidth(stageWidth);
stage.sizeToScene();
// return controller for the loaded fxml scene
return loader.getController();
}
/**
* Used to load a scene in a new separate popup stage.
* @param fxmlUrl the URL of the FXML file to be loaded
* @param title title for the new window
* @param modality modality settings for popup window
* @return the controller of the new scene
* @throws IOException if there is an issue with the fxmlUrl
*/
protected Controller2 loadPopupScene(String fxmlUrl, String title, Modality
modality) throws IOException {
// load the correct fxml scene
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource(
"/visualiser/scenes/" + fxmlUrl));
Parent root = loader.load();
// create a new 'pop-up' window
Stage stage = new Stage();
stage.initModality(modality);
stage.setTitle(title);
stage.centerOnScreen();
stage.getIcons().add(new Image(getClass().getClassLoader().getResourceAsStream("images/SailIcon.png")));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
// return controller for the loaded fxml scene
return loader.getController();
}
}
@@ -0,0 +1,272 @@
package visualiser.Controllers;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import visualiser.gameController.Keys.ControlKey;
import visualiser.gameController.Keys.KeyFactory;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static visualiser.app.App.keyFactory;
/**
* Controller for the scene used to display and update current key bindings.
*/
public class KeyBindingsController extends Controller2 {
private @FXML Button btnSave;
private @FXML Button btnCancel;
private @FXML Button btnReset;
private @FXML ListView lstControl;
private @FXML ListView lstKey;
private @FXML ListView lstDescription;
private @FXML AnchorPane anchor;
private KeyFactory newKeyFactory;
private Boolean changed = false; // keyBindings have been modified
private Button currentButton = null; // last button clicked
public void initialize(){
// create new key factory to modify, keeping the existing one safe
newKeyFactory = copyExistingFactory();
initializeTable();
populateTable();
setKeyListener();
setClosedListener();
}
/**
* Sets up table before populating it.
* Set up includes headings, CSS styling and modifying default properties.
*/
public void initializeTable(){
// set the headings for each column
lstKey.getItems().add("Key");
lstControl.getItems().add("Command");
lstDescription.getItems().add("Description");
lstKey.getSelectionModel().select(0);
lstControl.getSelectionModel().select(0);
lstDescription.getSelectionModel().select(0);
// add CSS stylesheet once the scene has been created
lstKey.sceneProperty().addListener((obs, oldScene, newScene) -> {
if (newScene != null) {
newScene.getStylesheets().add("/css/keyBindings.css");
}
});
// stop the columns from being selectable, so only the buttons are
lstKey.getSelectionModel().selectedItemProperty()
.addListener((observable, oldvalue, newValue) ->
Platform.runLater(() ->
lstKey.getSelectionModel().select(0)));
lstDescription.getSelectionModel().selectedItemProperty()
.addListener((observable, oldvalue, newValue) ->
Platform.runLater(() ->
lstDescription.getSelectionModel().select(0)));
lstControl.getSelectionModel().selectedItemProperty()
.addListener((observable, oldvalue, newValue) ->
Platform.runLater(() ->
lstControl.getSelectionModel().select(0)));
}
/**
* Populates the table with commands and their key binding details.
*/
public void populateTable(){
// add each command to the table
for (Map.Entry<String, ControlKey> entry : newKeyFactory.getKeyState().entrySet()) {
// create button for command
Button button = new Button(entry.getKey());
button.setMinWidth(120);
button.setId(entry.getValue().toString());
button.setOnAction(e -> currentButton = button);
// display details for command in table
lstControl.getItems().add(entry.getValue());
lstKey.getItems().add(button);
lstDescription.getItems().add(entry.getValue().getProtocolCode());
}
}
/**
* Makes a copy of the {@link KeyFactory} that does not modify the original.
* @return new keyfactory to be modified
*/
public KeyFactory copyExistingFactory(){
newKeyFactory = new KeyFactory();
Map<String, ControlKey> oldKeyState = keyFactory.getKeyState();
Map<String, ControlKey> newKeyState = new HashMap<>();
// copy over commands and their keys
for (Map.Entry<String, ControlKey> entry : oldKeyState.entrySet()){
newKeyState.put(entry.getKey(), entry.getValue());
}
newKeyFactory.setKeyState(newKeyState);
return newKeyFactory;
}
/**
* Creates a listener for when a user tries to close the current window.
*/
public void setClosedListener(){
anchor.sceneProperty().addListener((obsS, oldS, newS) -> {
if (newS != null) {
newS.windowProperty().addListener((obsW, oldW, newW) -> {
if (newW != null) {
Stage stage = (Stage)newW;
// WE is processed by onExit method
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
public void handle(WindowEvent we) {
if (we.getEventType() == WindowEvent.WINDOW_CLOSE_REQUEST) {
onExit(we);
}
}
});
}
});
}
});
}
/**
* Creates a listener for the base anchorpane for key presses.
* It updates the current key bindings of the {@link KeyFactory} if
* required.
*/
public void setKeyListener(){
anchor.addEventFilter(KeyEvent.KEY_PRESSED, event -> {
// if esc, cancel current button click
if (event.getCode() == KeyCode.ESCAPE){
btnCancel.requestFocus();
currentButton = null;
}
// if a button was clicked
else if (currentButton != null) {
// check if a button is already mapped to this key
for (int i = 1; i < lstKey.getItems().size(); i++) {
Button button = (Button)lstKey.getItems().get(i);
// update buttons text and remove key binding from command
if (button.getText().equals(event.getCode().toString())) {
button.setText("");
newKeyFactory.updateKey(button.getId(), button.getId());
}
}
// update text on the button
currentButton.setText(event.getCode().toString());
// update the control key
newKeyFactory.updateKey(event.getCode().toString(),
currentButton.getId());
// remove current button selection
currentButton = null;
changed = true;
btnCancel.requestFocus();
}
event.consume();
});
}
/**
* Cancel and exits the key bindings menu. Changes are not forced to be
* saved or fixed if invalid, and instead are defaulted back to the last
* successful saved state.
*/
public void cancel(){
((Stage)btnCancel.getScene().getWindow()).close();
}
/**
* Resets all key bindings to the built-in defaults.
*/
public void reset(){
lstKey.getItems().clear();
lstControl.getItems().clear();
lstDescription.getItems().clear();
newKeyFactory = new KeyFactory();
initializeTable();
populateTable();
changed = true;
}
/**
* Replace existing {@link KeyFactory} with the modified key bindings.
*/
public void save(){
if (isFactoryValid()) {
keyFactory = newKeyFactory;
newKeyFactory = new KeyFactory();
changed = false;
keyFactory.save(); // save persistently
loadNotification("Key bindings were successfully saved.", false);
} else {
loadNotification("One or more key bindings are missing. " +
"Failed to save.", true);
}
}
/**
* Checks the {@link KeyFactory} being modified is valid and that no
* commands are missing a key binding.
* @return True if valid, false if invalid
*/
public Boolean isFactoryValid(){
for (Map.Entry<String, ControlKey> entry : newKeyFactory.getKeyState().entrySet
()) {
if (entry.getKey().toString()==entry.getValue().toString()){
return false;
}
}
return true;
}
/**
* Method used to stop a user from exiting key bindings without saving
* their changes to the {@link KeyFactory}.
* @param we {@link WindowEvent} close request to be consumed if settings
* have not been successfully saved.
*/
public void onExit(WindowEvent we){
// if modified KeyFactory hasn't been saved
if (changed){
loadNotification("Please cancel or save your changes before exiting" +
".", true);
we.consume();
}
}
/**
* Loads a popup window giving confirmation/warning of user activity.
* @param message the message to be displayed to the user
* @param warning true if the message to be displayed is due to user error
*/
public void loadNotification(String message, Boolean warning){
Parent root = null;
FXMLLoader loader = new FXMLLoader(getClass().getResource
("/visualiser/scenes/notification.fxml"));
try {
root = loader.load();
} catch (IOException e) {
e.printStackTrace();
}
NotificationController controller = loader.getController();
Stage stage = new Stage();
stage.setScene(new Scene(root));
stage.centerOnScreen();
stage.initModality(Modality.APPLICATION_MODAL);
stage.show();
// displays given message in the window
controller.setMessage(message, warning);
}
}
@@ -7,9 +7,6 @@ import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import visualiser.Controllers2.Controller2;
import visualiser.Controllers2.StartController;
import visualiser.model.RaceConnection;
import java.io.IOException;
@@ -19,34 +16,21 @@ import java.net.Socket;
* Controller for the Lobby for entering games
*/
public class LobbyController extends Controller2 {
@FXML
private AnchorPane lobbyWrapper;
@FXML
private TableView<RaceConnection> lobbyTable;
@FXML
private TableColumn<RaceConnection, String> gameNameColumn;
@FXML
private TableColumn<RaceConnection, String> hostNameColumn;
@FXML
private TableColumn<RaceConnection, String> statusColumn;
@FXML
private Button joinGameBtn;
@FXML
private TextField addressFld;
@FXML
private TextField portFld;
private @FXML TableView<RaceConnection> lobbyTable;
private @FXML TableColumn<RaceConnection, String> gameNameColumn;
private @FXML TableColumn<RaceConnection, String> hostNameColumn;
private @FXML TableColumn<RaceConnection, String> statusColumn;
private @FXML Button joinGameBtn;
private @FXML TextField addressFld;
private @FXML TextField portFld;
private ObservableList<RaceConnection> connections;
// @Override
public void initialize() {
// set up the connection table
connections = FXCollections.observableArrayList();
//connections.add(new RaceConnection("localhost", 4942, "Local Game"));
lobbyTable.setItems(connections);
gameNameColumn.setCellValueFactory(cellData -> cellData.getValue().gamenameProperty());
hostNameColumn.setCellValueFactory(cellData -> cellData.getValue().hostnameProperty());
statusColumn.setCellValueFactory(cellData -> cellData.getValue().statusProperty());
@@ -54,8 +38,7 @@ public class LobbyController extends Controller2 {
lobbyTable.getSelectionModel().selectedItemProperty().addListener((obs, prev, curr) -> {
if (curr != null && curr.statusProperty().getValue().equals("Ready")) {
joinGameBtn.setDisable(false);
}
else {
} else {
joinGameBtn.setDisable(true);
}
});
@@ -81,23 +64,15 @@ public class LobbyController extends Controller2 {
/**
* Connect to a connection.
*/
public void connectSocket() {
try{
RaceConnection connection = lobbyTable.getSelectionModel().getSelectedItem();
Socket socket = new Socket(connection.getHostname(), connection.getPort());
lobbyWrapper.setVisible(false);
// parent.enterLobby(socket, false);
StartController sc = (StartController)loadScene(
"/visualiser/scenes/start.fxml");
sc.enterLobby(socket, false);
} catch (IOException e) { /* Never reached */
e.printStackTrace();
}
public void connectSocket() throws IOException {
RaceConnection connection = lobbyTable.getSelectionModel().getSelectedItem();
Socket socket = new Socket(connection.getHostname(), connection.getPort());
RaceStartController rsc = (RaceStartController)loadScene("raceStart.fxml");
rsc.enterLobby(socket, false);
}
public void menuBtnPressed() throws IOException {
// parent.enterTitle();
loadScene("titleScreen.fxml");
loadScene("title.fxml");
}
/**
@@ -106,24 +81,14 @@ public class LobbyController extends Controller2 {
public void addConnectionPressed(){
String hostName = addressFld.getText();
String portString = portFld.getText();
try{
try {
int port = Integer.parseInt(portString);
connections.add(new RaceConnection(hostName, port, "Boat Game"));
addressFld.clear();
portFld.clear();
}catch(NumberFormatException e){
} catch (NumberFormatException e) {
System.err.println("Port number entered is not a number");
}
}
public AnchorPane startWrapper(){
return lobbyWrapper;
}
/**
* Enter the lobby page.
*/
public void enterLobby(){
lobbyWrapper.setVisible(true);
}
}
}
@@ -2,14 +2,9 @@ package visualiser.Controllers;
import com.interactivemesh.jfx.importer.stl.StlMeshImporter;
import javafx.animation.AnimationTimer;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.SplitPane;
@@ -17,12 +12,8 @@ import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.scene.shape.MeshView;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import mock.app.Event;
import mock.exceptions.EventConstructionException;
import visualiser.Controllers2.Controller2;
import visualiser.Controllers2.StartController;
import visualiser.app.App;
import visualiser.layout.Subject3D;
import visualiser.layout.View3D;
@@ -37,13 +28,12 @@ import java.util.logging.Logger;
/**
* Controller for Hosting a game.
*/
public class HostController extends Controller2 {
public class LobbyHostingController extends Controller2 {
private @FXML ImageView imageView;
private @FXML AnchorPane imagePane;
private @FXML SplitPane splitPane;
private @FXML AnchorPane specPane;
private @FXML GridPane playerContainer;
private Event game;
private View3D view3D;
public void initialize() {
@@ -54,7 +44,7 @@ public class HostController extends Controller2 {
view3D.setItems(subjects);
playerContainer.add(view3D, 0,0);
URL asset = HostController.class.getClassLoader().getResource("assets/V1.2 Complete Boat.stl");
URL asset = LobbyHostingController.class.getClassLoader().getResource("assets/V1.2 Complete Boat.stl");
StlMeshImporter importer = new StlMeshImporter();
importer.read(asset);
@@ -81,30 +71,25 @@ public class HostController extends Controller2 {
*/
public void hostGamePressed() {
try {
this.game = new Event(false);
App.game = new Event(false);
connectSocket("localhost", 4942);
} catch (EventConstructionException e) {
Logger.getGlobal().log(Level.SEVERE, "Could not create Event.", e);
throw new RuntimeException(e);
} catch (IOException e) {
e.printStackTrace();
}
}
public void endEvent() throws IOException {
game.endEvent();
}
/**
* Connect to a socket
* @param address address of the server
* @param port port that the server is run off
*/
public void connectSocket(String address, int port) {
try{
Socket socket = new Socket(address, port);
StartController sc = (StartController)loadScene
("start.fxml");
sc.enterLobby(socket, true);
} catch (IOException e) { /* Never reached */ }
public void connectSocket(String address, int port) throws IOException {
Socket socket = new Socket(address, port);
RaceStartController rsc = (RaceStartController)loadScene("raceStart.fxml");
rsc.enterLobby(socket, true);
}
/**
@@ -115,34 +100,21 @@ public class HostController extends Controller2 {
splitPane.lookupAll(".split-pane-divider").stream().forEach(div -> div.setMouseTransparent(true));
imageView.fitWidthProperty().bind(imagePane.widthProperty());
imageView.fitHeightProperty().bind(imagePane.heightProperty());
// hostWrapper.setVisible(true); tick
}
/**
* Menu button pressed. Prompt alert then return to menu
*/
public void menuBtnPressed() throws IOException {
public void menuBtnPressed() throws Exception {
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("Quitting race");
alert.setContentText("Do you wish to quit the race?");
alert.setHeaderText("You are about to quit the race");
Optional<ButtonType> result = alert.showAndWait();
if(result.get() == ButtonType.OK){
// hostWrapper.setVisible(false);
Stage stage = App.getStage();
FXMLLoader loader = new FXMLLoader(getClass().getResource("/visualiser/scenes/main.fxml"));
Parent root = loader.load();
stage.setResizable(false);
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
@Override public void handle(WindowEvent event) {
Platform.exit();
System.exit(0);
}
});
// parent.enterTitle(); tick
// getStage().close();
// App.app.loadTitleScreen();
loadTitleScreen();
}
}
@@ -1,135 +0,0 @@
package visualiser.Controllers;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.layout.AnchorPane;
import visualiser.Controllers2.FinishController;
import visualiser.Controllers2.StartController;
import visualiser.Controllers2.TitleController;
import visualiser.gameController.ControllerClient;
import visualiser.model.VisualiserBoat;
import visualiser.model.VisualiserRaceEvent;
import java.io.IOException;
import java.net.Socket;
import java.net.URL;
import java.util.ResourceBundle;
/**
* Controller that everything is overlayed onto. This makes it so that changing scenes does not resize your stage.
*/
public class MainController extends Controller {
@FXML private StartController startController;
@FXML private RaceController raceController;
@FXML private ConnectionController connectionController;
@FXML private FinishController finishController;
@FXML private TitleController titleController;
@FXML private HostController hostController;
@FXML private LobbyController lobbyController;
/**
* Ctor.
*/
public MainController() {
}
/**
* Transitions from the StartController screen (displays pre-race information) to the RaceController (displays the actual race).
* @param visualiserRace The object modelling the race.
* @param controllerClient Socket Client that manipulates the controller.
* @param isHost if the client is the host of a race or not.
*/
public void beginRace(VisualiserRaceEvent visualiserRace, ControllerClient controllerClient, Boolean isHost) {
raceController.startRace(visualiserRace, controllerClient, isHost);
}
public void endEvent() throws IOException { hostController.endEvent(); }
/**
* Transitions from the server selection screen to the pre-race lobby for a given server.
* @param socket The server to read data from.
* @param isHost is connection a host
*/
public void enterLobby(Socket socket, Boolean isHost) {
startController.enterLobby(socket, isHost);
}
/**
* Transitions from the {@link RaceController} screen to the {@link FinishController} screen.
* @param boats The boats to display on the finish screen.
*/
public void enterFinish(ObservableList<VisualiserBoat> boats) {
finishController.loadFinish(boats);
}
// /**
// * Transitions into the title screen
// */
// public void enterTitle() {
// titleController.enterTitle();
// }
/**
* Transitions into lobby screen
*/
public void enterLobby(){ lobbyController.enterLobby(); }
/**
* Transitions into host game screen
*/
public void hostGame(){ hostController.hostGame(); }
/**
* Sets up the css for the start of the program
*/
public void startCss(){titleController.setDayMode();}
/**
* Main Controller for the applications will house the menu and the displayed pane.
*
* @param location of resources
* @param resources bundle
*/
@Override
public void initialize(URL location, ResourceBundle resources) {
// startController.setParent(this);
// raceController.setParent(this);
// connectionController.setParent(this);
// finishController.setParent(this);
// titleController.setParent(this);
// hostController.setParent(this);
// lobbyController.setParent(this);
// AnchorPane.setTopAnchor(startController.startWrapper(), 0.0);
// AnchorPane.setBottomAnchor(startController.startWrapper(), 0.0);
// AnchorPane.setLeftAnchor(startController.startWrapper(), 0.0);
// AnchorPane.setRightAnchor(startController.startWrapper(), 0.0);
AnchorPane.setTopAnchor(lobbyController.startWrapper(), 0.0);
AnchorPane.setBottomAnchor(lobbyController.startWrapper(), 0.0);
AnchorPane.setLeftAnchor(lobbyController.startWrapper(), 0.0);
AnchorPane.setRightAnchor(lobbyController.startWrapper(), 0.0);
// AnchorPane.setTopAnchor(hostController.startWrapper(), 0.0);
// AnchorPane.setBottomAnchor(hostController.startWrapper(), 0.0);
// AnchorPane.setLeftAnchor(hostController.startWrapper(), 0.0);
// AnchorPane.setRightAnchor(hostController.startWrapper(), 0.0);
// AnchorPane.setTopAnchor(finishController.finishWrapper, 0.0);
// AnchorPane.setBottomAnchor(finishController.finishWrapper, 0.0);
// AnchorPane.setLeftAnchor(finishController.finishWrapper, 0.0);
// AnchorPane.setRightAnchor(finishController.finishWrapper, 0.0);
// AnchorPane.setTopAnchor(titleController.titleWrapper, 0.0);
// AnchorPane.setBottomAnchor(titleController.titleWrapper, 0.0);
// AnchorPane.setLeftAnchor(titleController.titleWrapper, 0.0);
// AnchorPane.setRightAnchor(titleController.titleWrapper, 0.0);
}
}
@@ -0,0 +1,35 @@
package visualiser.Controllers;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.stage.Stage;
/**
* Controller for a popup notification regarding user activity.
*/
public class NotificationController {
private @FXML Label lblDescription;
private @FXML Text txtMessage;
/**
* Closes the popup window once clicked.
*/
public void ok(){
((Stage)lblDescription.getScene().getWindow()).close();
}
/**
* Displays the appropriate popup notification.
* @param message message for the user
* @param warning if true warning text shown, if false success text shown
*/
public void setMessage(String message, Boolean warning){
lblDescription.setText(message);
if (!warning){
txtMessage.setText("Success!");
txtMessage.setFill(Color.GREEN);
}
}
}
@@ -0,0 +1,39 @@
package visualiser.Controllers;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import visualiser.model.VisualiserBoat;
/**
* Finish Screen for when the race finishes.
*/
public class RaceFinishController extends Controller2 {
private @FXML TableView<VisualiserBoat> boatInfoTable;
private @FXML TableColumn<VisualiserBoat, String> boatRankColumn;
private @FXML TableColumn<VisualiserBoat, String> boatNameColumn;
private @FXML Label raceWinnerLabel;
/**
* Display the table
* @param boats boats to display on the table.
*/
public void loadFinish(ObservableList<VisualiserBoat> boats) {
// set table contents
boatInfoTable.setItems(boats);
//Name.
boatNameColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
//Rank/position.
boatRankColumn.setCellValueFactory(cellData -> cellData.getValue().placingProperty());
//Winner label.
if (boats.size() > 0) {
raceWinnerLabel.setText("Winner: " +
boatNameColumn.getCellObservableValue(0).getValue());
raceWinnerLabel.setWrapText(true);
}
}
}
@@ -0,0 +1,141 @@
package visualiser.Controllers;
import javafx.animation.AnimationTimer;
import javafx.application.Platform;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import network.Messages.Enums.RaceStatusEnum;
import network.Messages.Enums.RequestToJoinEnum;
import visualiser.gameController.ControllerClient;
import visualiser.model.VisualiserBoat;
import visualiser.model.VisualiserRaceEvent;
import visualiser.model.VisualiserRaceState;
import java.io.IOException;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Controller to for waiting for the race to start.
*/
public class RaceStartController extends Controller2 {
private @FXML Label raceTitleLabel;
private @FXML Label raceStartLabel;
private @FXML Label timeZoneTime;
private @FXML Label timer;
private @FXML TableView<VisualiserBoat> boatNameTable;
private @FXML TableColumn<VisualiserBoat, String> boatNameColumn;
private @FXML TableColumn<VisualiserBoat, String> boatCodeColumn;
private @FXML Label raceStatusLabel;
private VisualiserRaceEvent visualiserRaceEvent;
private VisualiserRaceState raceState;
private ControllerClient controllerClient;
private boolean isHost;
/**
* Show starting information for a race given a socket.
* Intended to be called on loading the scene.
* @param socket network source of information
* @param isHost is user a host
*/
public void enterLobby(Socket socket, Boolean isHost) {
try {
this.isHost = isHost;
this.visualiserRaceEvent = new VisualiserRaceEvent(socket, RequestToJoinEnum.PARTICIPANT);
this.controllerClient = visualiserRaceEvent.getControllerClient();
this.raceState = visualiserRaceEvent.getVisualiserRaceState();
showRaceDetails();
} catch (IOException e) {
//TODO should probably let this propagate, so that we only enter this scene if everything works
Logger.getGlobal()
.log(Level.WARNING, "Could not connect to server.", e);
}
}
/**
* Displays details and starts the timer for the race being started
*/
private void showRaceDetails() {
raceTitleLabel.setText(this.raceState.getRegattaName());
initialiseBoatTable();
initialiseRaceClock();
countdownTimer();
}
/**
* Initialises the boat table that is to be shown on the pane.
*/
private void initialiseBoatTable() {
//Get the boats.
ObservableList<VisualiserBoat> boats =
this.raceState.getBoats();
//Populate table.
boatNameTable.setItems(boats);
boatNameColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
boatCodeColumn.setCellValueFactory(cellData -> cellData.getValue().countryProperty());
}
/**
* Initialises the race clock/timer labels for the start time, current time, and remaining time.
*/
private void initialiseRaceClock() {
raceStartLabel.setText(
this.raceState.getRaceClock().getStartingTimeString());
// init clock start time
this.raceState.getRaceClock().startingTimeProperty().addListener((observable, oldValue, newValue) -> {
Platform.runLater(() -> {
raceStartLabel.setText(newValue);
});
});
// init clock current time
this.raceState.getRaceClock().currentTimeProperty().addListener((observable, oldValue, newValue) -> {
Platform.runLater(() -> {
timeZoneTime.setText(newValue);
});
});
// init clock remaining time
this.raceState.getRaceClock().durationProperty().addListener((observable, oldValue, newValue) -> {
Platform.runLater(() -> {
timer.setText(newValue);
});
});
}
/**
* Countdown timer until race starts.
*/
private void countdownTimer() {
new AnimationTimer() {
@Override
public void handle(long arg0) {
// display current race status
RaceStatusEnum raceStatus = raceState.getRaceStatusEnum();
raceStatusLabel.setText("Race Status: " + raceStatus.name());
// if race is in PREPARATORY or STARTED status
if (raceStatus == RaceStatusEnum.PREPARATORY || raceStatus == RaceStatusEnum.STARTED) {
stop(); // stop this timer
// load up the race scene
try {
RaceViewController rvc = (RaceViewController)
loadScene("raceView.fxml");
rvc.startRace(visualiserRaceEvent, controllerClient,
isHost);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}.start();
}
}
@@ -17,9 +17,6 @@ import javafx.scene.layout.StackPane;
import javafx.util.Callback;
import network.Messages.Enums.RaceStatusEnum;
import shared.model.Leg;
import visualiser.Controllers2.ArrowController;
import visualiser.Controllers2.Controller2;
import visualiser.Controllers2.FinishController;
import visualiser.app.App;
import visualiser.gameController.ControllerClient;
import visualiser.gameController.Keys.ControlKey;
@@ -35,13 +32,12 @@ import java.util.logging.Logger;
/**
* Controller used to display a running race.
*/
public class RaceController extends Controller2 {
public class RaceViewController extends Controller2 {
private VisualiserRaceEvent visualiserRace;
private VisualiserRaceState raceState;
private ControllerClient controllerClient;
private ResizableRaceCanvas raceCanvas;
private KeyFactory keyFactory;
private KeyFactory keyFactory = new KeyFactory();
private boolean infoTableShow = true; // shown or hidden
private boolean isHost;
@@ -87,9 +83,10 @@ public class RaceController extends Controller2 {
race.addEventFilter(KeyEvent.KEY_PRESSED, event -> {
String codeString = event.getCode().toString();
// tab key
if (codeString.equals("TAB")){toggleTable();}
// valid key pressed
// any key pressed
ControlKey controlKey = keyFactory.getKey(codeString);
if(controlKey != null) {
try {
@@ -98,13 +95,12 @@ public class RaceController extends Controller2 {
event.consume();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
Logger.getGlobal().log(Level.WARNING, "RaceController was interrupted on thread: " + Thread.currentThread() + "while sending: " + controlKey, e);
Logger.getGlobal().log(Level.WARNING, "RaceViewController was interrupted on thread: " + Thread.currentThread() + "while sending: " + controlKey, e);
}
}
// escape key
if(event.getCode() == KeyCode.ESCAPE) {
try {
if (isHost) {
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
@@ -112,10 +108,8 @@ public class RaceController extends Controller2 {
alert.setContentText("Do you wish to quit the race? You are the host");
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.OK) {
HostController hc = (HostController)loadScene(
"hostgame.fxml");
hc.endEvent();
App.app.loadTitleScreen();
App.game.endEvent();
loadTitleScreen();
}
} else {
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
@@ -123,7 +117,7 @@ public class RaceController extends Controller2 {
alert.setContentText("Do you wish to quit the race?");
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.OK) {
App.app.loadTitleScreen();
loadTitleScreen();
}
}
} catch (IOException e) {
@@ -170,10 +164,8 @@ public class RaceController extends Controller2 {
showFPS.selectedProperty().addListener((ov, old_val, new_val) -> {
if (showFPS.isSelected()) {
FPS.setVisible(true);
} else {
FPS.setVisible(false);
}
});
@@ -260,8 +252,6 @@ public class RaceController extends Controller2 {
private void initialiseRaceCanvas() {
//Create canvas.
raceCanvas = new ResizableRaceCanvas(raceState);
//Set properties.
raceCanvas.setMouseTransparent(true);
raceCanvas.widthProperty().bind(canvasBase.widthProperty());
raceCanvas.heightProperty().bind(canvasBase.heightProperty());
@@ -288,8 +278,8 @@ public class RaceController extends Controller2 {
* Transition from the race view to the finish view.
*/
public void finishRace() throws IOException {
FinishController fc =
(FinishController)loadScene("/visualiser/scenes/finish.fxml");
RaceFinishController fc =
(RaceFinishController)loadScene("raceFinish.fxml");
fc.loadFinish(raceState.getBoats());
}
@@ -317,7 +307,7 @@ public class RaceController extends Controller2 {
//Return to main screen if we lose connection.
if (!visualiserRace.getServerConnection().isAlive()) {
try {
App.app.loadTitleScreen();
loadTitleScreen();
} catch (Exception e) {
e.printStackTrace();
}
@@ -0,0 +1,67 @@
package visualiser.Controllers;
import javafx.fxml.FXML;
import javafx.scene.control.RadioButton;
import javafx.stage.Modality;
import java.io.IOException;
/**
* Controller for the opening title window.
* Has two initial buttons for a user to decide how to play their game. Has a
* burger-boat and comic sans styling to allure and entice users into playing
* the game.
*/
public class TitleController extends Controller2 {
private @FXML RadioButton dayModeRD;
private @FXML RadioButton nightModeRD;
/**
* Method called when the 'host a game' button is pressed.
* Opens the next window allowing a user to host their own game.
* Currently used to run the RaceVision mock.
* @throws IOException if main has problems
*/
public void hostAGame() throws IOException {
loadScene("lobbyHosting.fxml");
}
/**
* To be implemented at a later date- will open the next scene displaying
* games a player can join. Place holder method for now!
*/
public void joinAGame() throws IOException {
loadScene("lobby.fxml");
}
/**
* Switches the css of the program to day mode theme
*/
public void setDayMode(){
dayModeRD.getScene().getStylesheets().clear();
dayModeRD.getScene().getStylesheets().add("/css/dayMode.css");
nightModeRD.setSelected(false);
}
/**
* Switches the css of the program to night mode theme
*/
public void setNightMode(){
nightModeRD.getScene().getStylesheets().clear();
nightModeRD.getScene().getStylesheets().add("/css/nightMode.css");
dayModeRD.setSelected(false);
}
/**
* Called when control button is pressed. New pop up window displaying controls
*/
public void showControls(){
try {
loadPopupScene("keyBindings.fxml",
"Game Controls", Modality.WINDOW_MODAL);
} catch (IOException e) {
e.printStackTrace();
}
}
}