java – Sea battle game, link GUI and logic


Hi people. I am writing a sea battle, with graphics in JavaFX. There is a main game loop in which the player and the computer shoot, and in fact all the logic happens. While everything was in the console form, there were no problems and the loop simply did not go further until the user entered coordinates into the console. But now it's time to attach the GUI, and then a problem arose. The field is drawn on the canvas and when clicked, the coordinates are read. But now the main question is: how to make the loop wait until the user clicks on the canvas (field)? If it is important, then the graphics are written in FXML, and the application is based on the MVC principle. Heard something about events and falling asleep / waking up threads, but nothing specific.


I will describe step by step how I see the whole solution, I don’t see the cycle)
1. Create an abstract class. Fields: x, y position and detection (boolean). An abstract method for the appearance: public abstract Node appearance();
2. Create 2 subclasses (ship and miss) (extends). Example:

    public class Ship extends АбстрактныйКласс{
private Rectangle appearance;
public Ship (int x, int y) {
    appearance = new Rectangle(20,20,Color.GRAY);

public void move(Game gamer) {
public Node appearance() {

    return appearance;

public void setDetected(boolean detected){

3. The class of the game itself with get and set positions.
4. Well, and accordingly main class extends Application

public void start(Stage primaryStage) {
    try {
        GridPane root = new GridPane();...

with the method of processing the array that sets the position of the boats.
When drawing the battlefield, setDetected to false, so that everything, like in my example, would be gray.
5. A class for pressing the left mouse button on certain coordinates, which changes the appearance of the detected field.

Well, something like this. I missed some points, outlined the concept

if all the same Canvas

    Canvas pole = new Canvas(400, 400);

                        new Move(pole.getGraphicsContext2D()));

     public class Move implements EventHandler<MouseEvent> {
GraphicsContext teg;        
double X;           
double Y;           

public Move(GraphicsContext t) {
    teg = t;

public void handle(MouseEvent hendelsen) {

    double x = hendelsen.getX();
    double y = hendelsen.getY();

we get the coordinates, look at the array and describe what to do, i.e. change the appearance, or draw something.

Scroll to Top