Skip to content

Commit

Permalink
clean up VarChangeSample and move out of sandbox
Browse files Browse the repository at this point in the history
  • Loading branch information
AlmasB committed Dec 28, 2024
1 parent 3cdd7a3 commit 84c21cc
Showing 1 changed file with 32 additions and 26 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,35 +4,26 @@
* See LICENSE for details.
*/

package sandbox;
package intermediate;

import com.almasb.fxgl.app.GameApplication;
import com.almasb.fxgl.app.GameSettings;
import javafx.scene.input.KeyCode;
import javafx.util.Duration;

import java.util.Map;

import static com.almasb.fxgl.dsl.FXGL.*;

/**
* @author Almas Baimagambetov (AlmasB) ([email protected])
* Shows how to listen for changes in variables and react.
*
* @author Almas Baim (https://github.com/AlmasB)
*/
public class VarChangeSample extends GameApplication {

@Override
protected void initSettings(GameSettings settings) { }

@Override
protected void initInput() {
onKeyDown(KeyCode.F, "update", () -> {
inc("time", +1.0);

var name = gets("name");
set("name", name + "H");
});
}

@Override
protected void initGameVars(Map<String, Object> vars) {
vars.put("hp", 0);
Expand All @@ -42,29 +33,44 @@ protected void initGameVars(Map<String, Object> vars) {

@Override
protected void initGame() {
// the event builder way
eventBuilder()
.when(() -> geti("hp") == 7)
.limit(4)
.thenRun(() -> System.out.println("hello"))
.buildAndStart();

// the DSL way
// the DSL way, if you need something set up quickly
onDoubleChange("time", value -> {
System.out.println(value);
System.out.println("The var <time> is now: " + value);
});

onStringChange("name", value -> {
System.out.println(value);
System.out.println("The var <name> is now: " + value);
});

onStringChangeTo("name", "HelloHH", () -> {
System.out.println("bye");
System.out.println("The var <name> reached HelloHH");
});

onIntChangeTo("hp", 5, () -> System.out.println("Hello"));
onIntChangeTo("hp", 5, () -> {
System.out.println("The var <hp> reached 5");
});

// the event builder way, if you need more control over execution
eventBuilder()
.when(() -> geti("hp") == 7)
.limit(4)
.thenRun(() -> System.out.println("The <hp> var reached 7. You will see this message 4 times"))
.buildAndStart();

// the listener way, if you want to control lifecycle / clean-up process
getip("hp").subscribe((oldValue, newValue) -> {
if (newValue.intValue() == 4) {
System.out.println("The var <hp> reached 4");
}
});

run(() -> {
inc("hp", +1);
inc("time", +1.0);

set("name", gets("name") + "H");

run(() -> inc("hp", +1), Duration.seconds(1));
}, Duration.seconds(1));
}

public static void main(String[] args) {
Expand Down

0 comments on commit 84c21cc

Please sign in to comment.