【问题标题】:Recursive/looping calculations of new generation in The Game of Life生命游戏中新一代的递归/循环计算
【发布时间】:2024-04-23 14:40:02
【问题描述】:

每个人。

我的Game Of Life 应用程序(链接是示例应用程序)中的下一代计算正确。游戏按预期运行,但每次想要新一代时都必须按“下一步”。我在实现“开始”按钮来循环生成时遇到问题。 (“next”和“start”之间的区别请参见链接。)

很明显,我需要在 ActionListener 类中使用某种循环。当私有布尔值为真时,我尝试在 actionListener 中递归调用 nextGen() 。程序崩溃。我也尝试过设置某种等待,但这没关系。

如果我放置 10 行 nextGen(); ,它确实会进行 10 次迭代;在听众内部,所以我猜我需要在这里等待。 (内存问题。)

希望你能帮助我解决这个问题。 :)

这样计算下一代。

ActionListener 类:

public class GameOfLifeListener implements ActionListener
{

    // IMPORTANT: GameOfLifeGrid contains the GameOfLife collection!
    private GameOfLifeGrid gameOfLife;



    public GameOfLifeListener ( GameOfLifeGrid g ) 
    {
        this.gameOfLife = g;
     }

    @Override
    public void actionPerformed (ActionEvent e) 
    {
        // Get actionCommand
        String ac = e.getActionCommand();

        if ( ac.equals("next") ) 
        {
             // Method calculates next generation
             nextGen();
        }
        if ( ac.equals("start") ) 
        {
             // ADDED CODE: See class GameOfLifeGrid in bottom.
             gameOfLife.start();
        }
    }

    private void nextGen ( ) 
    {
        // Get Next generation
        gameOfLife.getCollection().nextGen();

        // Repaint
        gameOfLife.repaint();
    }
}

当按下按钮“next”时,actionListener 在 GameOfLife 对象上运行 nextGen()。 nextGen() 方法的工作原理并不重要,但这里它与 GameOfLife 类的某些部分一起使用

public class GameOfLife extends CellCollection
{
    // Temporary array for new generation . We must add next generations alive cells HERE.
    // Else the calculations of the current generation will fail.
    private Cell[][] nextGen = null;

    public void nextGen ( ) 
    {
        // Create the new Array holding next generation
        prepareNextCollection();

        // Iterate the whole grid
        for ( int row = 0; row < super.rows; row++ ) 
        {
            for ( int col = 0; col < super.cols; col++ ) 
            {
                 ruleOne(row, col);
            }
        }

        // Set the new collection to superClass. 
        // Super class holds the collection that will be drawn
        super.setCollection(nextGen);
    }


    private void ruleOne ( int row, int col ) 
    {
        // Calculations not important. It works like expected.
    }

    private void prepareNextCollection ( ) 
    {
        this.nextGen = new Cell[rows][cols];
    }

这是 GameOfLifeGrid 类的选定部分。它绘制网格和活动单元格(单元格数组)。

public class GameOfLifeGrid extends Grid
{

    private GameOfLife collection = null;

    // ADDED MEMBERS: Timer, int
    private Timer timer; 
    private int updateEachMilliSec = 100; // Used in program. Not in this code

    @Override
    public void paintComponent ( Graphics g )
    {
        super.paintComponent(g);
        drawCells(g);
    }

    private void drawCells ( Graphics g ) 
    {
        for ( int row = 0; row < rows; row++ ) 
        {
            for ( int col = 0; col < cols; col++ )
            {
                if ( ! collection.isEmptyPos(row, col) ) 
                {
                    g.fillRect(super.calcX(col), super.calcY(row), cellSize, cellSize);
                }
            }
        } 
    }

    // ADDED METHOD!
    public void start() 
    {
        // Create a timer object. The timer will send events each 100 ms.
        // The events will be caught by the ActionListener returned from
        // nextGenlistener(). VOILA!

        timer = new Timer(100, nextGenlistener());

        // Start sending events to be caught!
        timer.start();
    }

    // ADDED METHOD! The ActionListener who will catch the events sent by timer.
    private ActionListener nextGenlistener () 
    {
        return new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e) 
            {
                // Get next generation
                collection.nextGen();

                // Repaint
                repaint();
            }
        };
    }

【问题讨论】:

    标签: java recursion multidimensional-array mouseevent composition


    【解决方案1】:

    问题在于,当您尝试在 actionPerformed 方法中使用 Thread.sleep() 循环时,您会阻塞 Event Dispatch Thread。在您释放对线程的控制之前,不会重绘任何内容,因此您的重绘请求会在您的 actionPerformed 方法完成时立即启动并全部触发。

    简单的解决方案是使用 javax.swing.Timer 定期触发事件,大致如下:

    new Timer(5000, new ActionListener(){
      public void actionPerformed(ActionEvent e) {
        panel.repaint();
      }
    }).start();
    

    【讨论】:

    • 我花了很长时间才把它弄好。如果没有正确的方向,我永远不会发现。谢谢!