我在用 Java 实现生命游戏时遇到问题。
在 GUI 中,我有一些按钮决定游戏的初始状态(振荡器、滑翔机等),然后使用 Action 监听器设置第一个板并显示它。
然后我有一个函数可以计算单元格的邻居并设置单元格的颜色。 但是当我想重复游戏n次时我遇到了问题,因为我不知道如何设置时间间隔。
此时我看不到游戏的每一步,只能看到最后一步。
下面是我的 ActionListener:
private ActionListener buttonsListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source == button1)area = setButton1(getBoardWidth(), getBoardHeight());
if (source == glider) area = setGlider(getBoardWidth(), getBoardHeight());
if (source == oscilator) area = setOscilator(getBoardWidth(), getBoardHeight());
setBoard(area, board);
}
};
函数 setBoard()
接受包含 0 和 1 的整数数组,并将其转换为包含颜色的 JButton[][]
数组。
我尝试使用重写方法run()
,其中包括startTheGame()
函数,该函数检查邻域并设置整数数组。我需要多次执行此操作,但无法设置时间间隔。
@Override
public void run() {
startTheGame(area);
setBoard(area, board);
}
最佳答案
您应该使用此计时器 schedule .
所以你必须定义一个自定义TimerTask像这样:
import java.util.TimerTask;
public class UserTimerTask extends TimerTask{
@Override
public void run() {
startTheGame(area);
setBoard(area, board);
}
}
然后像这样包装你的代码:
// daemon means, background. If every task is a demon task, the VM will exit
Bolean isDaemon = false;
Timer timer = new Timer("nameOfThread",isDaemon);
TimerTask task = new UserTimerTask();
// Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay
// both parameters are in milliseconds
timer.schedule(task,0,1000);
关于java - 生命游戏循环函数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61045384/