【发布时间】:2021-09-25 19:07:25
【问题描述】:
我正在尝试对战海进行编码,在我的一个菜单上,我应该向客户展示他们的地图,并给他们 30 秒的时间来决定他们是否想要一张新地图,或者地图没问题,然后他们就可以开始游戏了。如果他们点击开始游戏按钮,计时器应该停止并且场景会改变。如果他们的时间到了,就像他们点击了开始游戏按钮一样,超时后场景应该会自动改变。如果他们点击新地图按钮,我应该给他们剩余的时间 + 10 来再次决定。我做了一些编码,但我无法完成剩余的+10 部分,而且我不知道如何停止线程。这是我的场景的 FXML 控制器,计时器应该在其中。drawMap 函数在这里并不重要。
public class StandbyMapGuiController implements Initializable {
@FXML
private volatile Label timerLabel;
@FXML
private GridPane sea;
private static Stage stage;
private static int time;
private GameTimer gameTimer;
private CountDown countDown;
@Override
public void initialize(URL location, ResourceBundle resources) {
drawMap();
gameTimer = new GameTimer(time,timerLabel , this);
gameTimer.countDown();
}
public void updateTimer(int newTime){
timerLabel.setText(String.valueOf(newTime));
}
public void drawMap(){
for (int i = 0 ; i < 10 ; i++){
for (int j = 0 ; j < 10 ; j++){
MapButton btn = new MapButton(i,j);
btn.setManner(MapButton.COLOR.VIOLET);
sea.add(btn,j,i);
}
}
}
public void changeMap(ActionEvent actionEvent) {
int remaining = Integer.parseInt(timerLabel.getText())+10;
System.out.println(remaining);
setTime(remaining);
//restart the page
Toolbar.getInstance().changeScene(ConfigLoader.readProperty("standbyMapMenuAdd"), actionEvent);
}
public void startGame() {
//todo: tell server the gamer is ready
timerLabel.setText("Time's up");
try {
Parent root;
root = FXMLLoader.load(getClass().getClassLoader().getResource("FXMLs/GameBoard.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
}
}
这是我的 GameTimer 类:
public class GameTimer {
private Timer timer;
private TimerTask task;
private int time;
private volatile Label label;
public GameTimer(int time, Label label, StandbyMapGuiController controller) {
this.time = time;
this.label = label;
timer = new Timer();
task = new TimerTask() {
int counter = time;
boolean timeOut = false;
public int getCounter() {
return counter;
}
public void setCounter(int counter) {
this.counter = counter;
}
public boolean isTimeOut() {
return timeOut;
}
public void setTimeOut(boolean timeOut) {
this.timeOut = timeOut;
}
@Override
public void run() {
Platform.runLater(() -> {
if (counter > 0) {
label.setText(String.valueOf(counter));
counter--;
} else {
timeOut = true;
controller.startGame();
timer.cancel();
}
});
}
};
}
public void countDown() {
timer.scheduleAtFixedRate(task, 0, 1000);
}
}
我无法访问 timeOut 和 counter 来设置或获取它们的值。(TimerTask 线程中的 getter 和 setter 不起作用)
【问题讨论】:
标签: java multithreading javafx timer