我在用Java实现生命游戏时遇到问题。
在GUI中,我具有确定游戏初始状态(振荡器,滑翔机等)的按钮,然后使用动作侦听器设置并显示第一块板。
然后,我有一个功能,可以计算单元的邻居并设置单元的颜色。但是我想重复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);