Conways游戏的生活

时间:2016-01-10 23:01:06

标签: java

  

创建一个名为live的方法,接受一个行和一列,然后返回一个布尔值,根据一组规则确定该位置的现有单元是否会生存或死亡(或者将创建一个单元格)(Conway的游戏)生活)。检查单元格周围的单元格数时,请注意考虑数组的边界。

我已经有了这个方法,但我不知道在该方法中该做什么。

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;  // Needed for ActionListener
import javax.swing.event.*;  // Needed for ActionListener

class LifeSimulationGUIDemo extends JFrame
{
    static Colony colony = new Colony (0.5);
    static Timer t;

    //======================================================== constructor
    public LifeSimulationGUIDemo ()
    {
        // 1... Create/initialize components
        BtnListener btnListener = new BtnListener (); // listener for all buttons

        JButton simulateBtn = new JButton ("Simulate");
        simulateBtn.addActionListener (btnListener);

        // 2... Create content pane, set layout
        JPanel content = new JPanel ();        // Create a content pane
        content.setLayout (new BorderLayout ()); // Use BorderLayout for panel
        JPanel north = new JPanel ();
        north.setLayout (new FlowLayout ()); // Use FlowLayout for input area

        DrawArea board = new DrawArea (500, 500);

        // 3... Add the components to the input area.

        north.add (simulateBtn);

        content.add (north, "North"); // Input area
        content.add (board, "South"); // Output area

        // 4... Set this window's attributes.
        setContentPane (content);
        pack ();
        setTitle ("Life Simulation");
        setSize (510, 570);
        setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo (null);           // Center window.
    }

    class BtnListener implements ActionListener 
    {
        public void actionPerformed (ActionEvent e)
        {
            if (e.getActionCommand ().equals ("Simulate"))
            {
                Movement moveColony = new Movement (); // ActionListener for timer
                t = new Timer (200, moveColony); // set up Movement to run every 200 milliseconds
                t.start (); // start simulation
            }
            repaint ();            // refresh display of colony
        }
    }

    class DrawArea extends JPanel
    {
        public DrawArea (int width, int height)
        {
            this.setPreferredSize (new Dimension (width, height)); // size
        }

        public void paintComponent (Graphics g)
        {
            colony.show (g); // display current state of colony
        }
    }

    class Movement implements ActionListener
    {
        public void actionPerformed (ActionEvent event)
        {
            colony.advance (); // advance to the next time step
            repaint (); // refresh 
        }
    }

    //======================================================== method main
    public static void main (String[] args)
    {
        LifeSimulationGUIDemo window = new LifeSimulationGUIDemo ();
        window.setVisible (true);
    }
}

class Colony
{


    private boolean grid[] [];

    public  boolean live ( int row, int column)
    {


    }



    public Colony (double density)
    {
        grid = new boolean [100] [100];
        for (int row = 0 ; row < grid.length ; row++)
            for (int col = 0 ; col < grid [0].length ; col++)
                grid [row] [col] = Math.random () < density;
    }

    public void show (Graphics g)
    {
        for (int row = 0 ; row < grid.length ; row++)
            for (int col = 0 ; col < grid [0].length ; col++)
            {
                if (grid [row] [col]) // life
                    g.setColor (Color.black);
                else
                    g.setColor (Color.white);
                g.fillRect (col * 5 + 2, row * 5 + 2, 5, 5); // draw life form
            }
    }

    public void advance ()
    {
    }
}

1 个答案:

答案 0 :(得分:3)

如果您不熟悉康威的生命游戏,可能需要快速介绍:

生命游戏是由John Conway于1970年设计的细胞自动机。生命,简而言之,实质上是对生命本身简单动态的模拟 - - 出生,繁殖和死亡。通过给定的种子或初始输入,Life将自行发挥作用,并根据您寻求帮助的核心规则,决定哪些细胞存活,繁殖或死亡。

查看Wikipedia page有关康威生命游戏的规则:

  
      
  • 任何活着的邻居少于两个的活细胞都会死亡,好像是由于人口不足造成的。
  •   
  • 任何有两三个活邻居的活细胞都会留在下一代。
  •   
  • 任何有三个以上活着的邻居的活细胞都会死亡,就像人口过多一样。
  •   
  • 任何有三个活着的邻居的死细胞都会成为活细胞,好像通过繁殖一样。
  •   

基本上,您的live()方法将实现这些核心规则,以确定给定行和列的单元格是否会存在。

我能想到提供示例的最简单方法是使用一组if / else语句:

public boolean live (int row, int column)
{
     // If the cell we're checking is currently alive
     if (grid[row][col]) // This is equal to: "if (grid[row][col] == true)"
     {
         // Check if fewer than two live neighbors exist
         if (neighborCheck(row, column) < 2)
         {
              // Cell dies due to under-population.
              return false;
         }   
         // Check if two or three live neighbors exist
         if (neighborCheck(row, column) <= 3)
         {
              // Cell lives.
              return true;
         }
         // Check if more than three live neighbors exist
         if (neighborCheck(row, column) > 3)
         {
              // Cell dies due to over-population.
              return false;
         }
     }
     // If the cell we're checking is currently dead
     else
     {
         // Check if cell has exactly three neighbors
         if (neighborCheck(row, column) == 3)
         {
              // Cell becomes alive.
              return true;
         }
     }
}

在上面的代码中,我写了live()直接基于上述规则。代码首先检查给定行和列(grid[row][column])的单元格终生。如果它是活的(如果grid[row][column] == true),则代码检查该单元格是否会继续存在或死亡。如果单元格已死(false),则代码将跳至else块。

在每次检查中,我都写了一个neighborCheck()调用。这是一种方法(尚未编写),它将检查给定单元格周围的每个 8个邻居并返回生活邻居的数量。

这张图片:( http://abyss.uoregon.edu/~js/images/life_rules.gif)很好地说明了细胞与其邻居之间的关系。以下是neighborCheck()方法的模板:

private int neighborCheck(int row, int column)
{ 
    // Iterate through each neighbor, count the living ones, and return it
    ...add your code here.
}

要遍历每个邻居,您需要以数学方式计算每个单元格相对于当前单元格的位置。我会让你为此编写代码,但请记住,你是在二维工作。例如,左上角邻居在行号中减1 ,在列号中减1 到当前单元格({{1 }, top-middle 邻居在行号中减1 但在列号(grid[row - 1][column - 1])中未更改,等等。