Reputation: 582
This is my first question and I am new in programming. I hope this question will not be boring for you.
I am writing a version of the Snake game in java for a school project. I am using javafx.
Each time the head eats the apple, a text appears and fades away. This text includes the score (increment of apples eaten).
The text appears and fades away well, but the score always shows the value "0", although its value is not 0 (I can see by printing the score in the console).
I have tried to create a class IntValue to call the value of the score in another way but it did not work.
public class MainGame extends Application {
Snake snake = new Snake();
Apple apple = new Apple();
public static final int width = 200;
public static final int height = 200;
public static int score;
private Text tEat = new Text();
public void start(Stage primaryStage) {
Pane layout = new Pane();
ObservableList<Node> components = layout.getChildren(); //creates a list of nodes and adds them to pane
components.add(snake); //snake added to pane
components.add(apple); //apple added to pane
components.add(tEat); //text added to pane
tEat.setText("GG! " + score);
tEat.setFont(Font.font(STYLESHEET_MODENA, FontWeight.BOLD, 20));
tEat.setY(height/2);
tEat.setX(width/2 - 40);
tEat.setFill(Color.GREEN);
tEat.setOpacity(0);
Timeline timeline = new Timeline(new KeyFrame(Duration.millis(100), ev -> {
snake.move();
if (snake.collides(apple)) {
score++; //score is incremented but not updated in tEat
fader(tEat); //tEat text appears and fades away
snake.eat(apple);
components.remove(apple);
apple = new Apple();
components.add(apple);
}
}));
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
Upvotes: 2
Views: 4481
Reputation: 4209
You can create a binding and it will update automatically.
Create:
private LongProperty score = new SimpleLongProperty(0);
Then create a binding.
Instead of:
tEat.setText("GG! " + score);
Use this:
tEat.textProperty().bind(Bindings.createStringBinding(() -> ("GG! " + score.get(), score));
Instead of this:
score++;
Use this:
score.set(score.get() + 1);
This will bind your value so that anytime that property is updated, it will update.
Upvotes: 2