【问题标题】:The game of life recurrent function probelm生命游戏循环函数问题
【发布时间】:2020-04-05 16:00:22
【问题描述】:

我在用 Java 实现我的 Game of Life 时遇到问题。

在 GUI 中,我有决定游戏初始状态的按钮(振荡器、滑翔机等),然后使用 Action Listener 我设置第一个板并显示它。

然后我有一个函数可以计算单元格的邻居并设置单元格的颜色。 但是当我想重复游戏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[][] 数组。

我尝试使用包含startTheGame() 函数的重写方法run(),它检查邻域并设置整数数组。我需要多次执行此操作,但我无法设置时间间隔。

 @Override
    public void run() {
            startTheGame(area);
            setBoard(area, board);
    }

【问题讨论】:

  • 你如何展示板子?

标签: java function conways-game-of-life


【解决方案1】:

你应该使用这个计时器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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-25
    • 2012-11-05
    • 1970-01-01
    • 1970-01-01
    • 2017-03-15
    • 2012-06-08
    相关资源
    最近更新 更多