0

Im working on a game in JavaFX. It's almost done but I encountered problem with move detection and can't think of simple solution. There probably is, but I'm just not aware of that

Obviously there is more code in between but i'm highlighting the problematic part.

int finalX = x;
int finalY = y;
boolean jumpMade = false;
boolean moveMade = false;

// Mouse Controller
board[x][y].setOnMouseClicked(event -> {

    if (!moveMade) {
        move(finalX, finalY, selectedMarbleX, selectedMarbleY, selectedMarbleColor);
        // Here I would want to make moveMade = true;
        // To block further possibility of moving.
    }
}

Tried changing to atomic or into one-element array but that won't do the job because the "map" that user is playing on have more than one possible direction of moving (so it wont block all of them).

And the error that appears by just placing nonchalantly moveMade = true overthere brings up "Variable in lambda expression should be final or effectively final".

  • Make moveMade a field of your class, or a field of an actual MouseListener class, rather than a local variable? – JB Nizet Jan 05 '19 at 18:09

2 Answers2

1

Use java.util.concurrent.atomic.AtomicBoolean utility class. They hold an atomic thread-safe reference to a value.

import java.util.concurrent.atomic.AtomicBoolean;

// Outside of lambda, instantiate the atomic boolean reference
AtomicBoolean ref = new AtomicBoolean(); // Constructor parameter optional: empty (false) / true / false

// Inside lambda, use the getters and setters
ref.set(true); // or: ref.set(false);
0

If you wish to access and modify the variable in a lambda expression, define it as a class/instance variable. There is a genuinely crux reason for the error you shouldn't rule out.

Gobbledygook yet a simple example,

interface Q {
    void fun();
}
class ABC {
    public static boolean x = false;  // class variable
    public static void b(Q q) {
        q.fun();
    }

    public static void main(String[] args) {
        Q a = () -> {
            System.out.println("run simple lambda");
            x = true;
        };
        b(a);
        System.out.println(x);
    }
}