java – Sea battle game, link GUI and logic

Question:

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.

Answer:

Hey!
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) {
    super(x,y);
    appearance = new Rectangle(20,20,Color.GRAY);
}

@Override
public void move(Game gamer) {
    gamer.setxPos(getxPos());
    gamer.setyPos(getyPos());
}@Override
public Node appearance() {

    return appearance;
}

@Override
public void setDetected(boolean detected){
    super.setDetected(detected);
    if(detected){
        appearance.setFill(Color.BLACK);
    }else{
        appearance.setFill(Color.GRAY);
    }
}

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

   @Override
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);

        root.setCenter(pole);
        pole.addEventHandler(MouseEvent.MOUSE_CLICKED, 
                        new Move(pole.getGraphicsContext2D()));

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


public Move(GraphicsContext t) {
    teg = t;
}

@Override
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