Java 康威人生游戏

Java 康威人生游戏,java,Java,创建一个名为live的方法,该方法接受一行和一列,然后返回一个布尔值,该布尔值根据一组规则(康威的生命游戏)确定该位置的现有单元格是生存还是消亡(或者创建一个单元格)。在检查单元格周围的单元格数量时,要仔细考虑数组的边界。 我已经有了这个方法,但我不知道在这个方法里面该怎么做 import java.awt.*; import javax.swing.*; import java.awt.event.*; // Needed for ActionListener import javax.sw

创建一个名为live的方法,该方法接受一行和一列,然后返回一个布尔值,该布尔值根据一组规则(康威的生命游戏)确定该位置的现有单元格是生存还是消亡(或者创建一个单元格)。在检查单元格周围的单元格数量时,要仔细考虑数组的边界。

我已经有了这个方法,但我不知道在这个方法里面该怎么做

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 ()
    {
    }
}
import java.awt.*;
导入javax.swing.*;
导入java.awt.event.*;//ActionListener需要
导入javax.swing.event.*;//ActionListener需要
类LifeSimulationGUIDemo扩展了JFrame
{
静态菌落=新菌落(0.5);
静态定时器t;
//====================================================================================构造函数
公共生活模拟UIDemo()
{
//1…创建/初始化组件
BtnListener BtnListener=新建BtnListener();//所有按钮的侦听器
JButton simulateBtn=新JButton(“模拟”);
simulateBtn.addActionListener(BTNLListener);
//2…创建内容窗格,设置布局
JPanel content=newjpanel();//创建内容窗格
content.setLayout(新的BorderLayout());//对面板使用BorderLayout
JPanel north=新的JPanel();
north.setLayout(新的FlowLayout());//对输入区域使用FlowLayout
绘图区板=新绘图区(500500);
//3…将组件添加到输入区域。
north.add(simulateBtn);
content.add(北,“北”);//输入区域
content.add(board,“South”);//输出区域
//4…设置此窗口的属性。
setContentPane(内容);
包装();
setTitle(“生命模拟”);
设置大小(510570);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);//中心窗口。
}
类BtnListener实现ActionListener
{
已执行的公共无效操作(操作事件e)
{
if(e.getActionCommand().equals(“模拟”))
{
Movement moveColony=new Movement();//计时器的ActionListener
t=新计时器(200,moveColony);//设置每200毫秒运行一次的移动
t、 start();//开始模拟
}
repaint();//刷新殖民地的显示
}
}
类DrawArea扩展了JPanel
{
公共绘图区(内部宽度、内部高度)
{
this.setPreferredSize(新尺寸(宽度、高度));//尺寸
}
公共组件(图形g)
{
colony.show(g);//显示殖民地的当前状态
}
}
类移动实现ActionListener
{
已执行的公共无效操作(操作事件)
{
colony.advance();//前进到下一个时间步骤
重新绘制();//刷新
}
}
//=================================================================================================方法主
公共静态void main(字符串[]args)
{
LifeSimulationUIDemo窗口=新建LifeSimulationUIDemo();
window.setVisible(true);
}
}
阶级群体
{
专用布尔网格[];
公共布尔活动(int行,int列)
{
}
公共殖民地(双密度)
{
网格=新布尔值[100][100];
对于(int row=0;row
如果您不熟悉康威的生活游戏,可能需要快速介绍:

《生命的游戏》是约翰·康威在1970年发明的一种细胞自动机简而言之,生命本质上是对生命本身的简单动力学——出生、繁殖和死亡的模拟。有了给定的种子或初始输入,生命将自行发挥,并根据你寻求帮助的核心规则,决定哪些细胞生存、繁殖或死亡

查看Conway生命游戏的规则:

  • 任何少于两个活邻居的活细胞都会死亡,就好像是由于人口不足造成的一样
  • 任何有两个或三个活邻居的活细胞都会延续到下一代
  • 任何有三个以上活邻居的活细胞都会死亡,就好像是因为人口过多
  • 任何有三个活邻居的死细胞都会变成活细胞,就像通过繁殖一样
本质上,您的
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;
         }
     }
}

要遍历每个相邻单元,您需要从数学上计算每个单元相对于当前单元的位置。我会让你为此编写代码,但请记住,你是在二维空间中工作的。例如,对于当前单元格(
grid[row-1][column-1]
中上部的邻居将在行号中为减一,在列号中为减一,但在列号中为不变
grid[row-1][column]
)等。

欢迎使用StackOverflow!我们不是编码服务。Y
private int neighborCheck(int row, int column)
{ 
    // Iterate through each neighbor, count the living ones, and return it
    ...add your code here.
}