Ginkgo
True love prevails.
“What the Fuck have I Done Lately 🙈?”
细胞自动机规则
在一个棋盘上有若干细胞,用黑色代表细胞存活,白色代表细胞死亡。它们在棋盘上根据一定的规则重生或者死亡:
| 状态 |
条件 |
结果 |
| 死亡 |
活邻居数量 < 2 或 > 3 |
细胞死亡 |
| 重生 |
活邻居数量 = 3 |
细胞重生 |
| 保持 |
其他情况 |
保持现状 |
这就是著名的 康威生命游戏(Conway’s Game of Life) 的核心规则。
程序逻辑分析
数据与表现分离
- 程序业务逻辑与表现无关
- 表现可以是 图形 的,也可以是 文本 的
- 表现可以是 当地 的,也可以是 远程 的
View 类与 Field 类的关系
两者的关系本质上是 表现与数据 的关系:
- View:只负责根据 Field 的内容画出相应的图形
- Field:负责数据的存放
为不断更新细胞的存活情况,每一次数据更新后,都需要调用 repaint() 接口通知 View 重新画出整个画面。不去考虑某个精确的局部更新,而是全局更新。这样简化了程序设计的逻辑,从而降低了实现的难度。
当然,这是以 “时间换简洁” 的思路,建立在如今计算机运算速度显著提高的基础之上。
责任驱动的设计
将某一程序要实现的某一功能,合理地分配到最合适的类或对象中去实现,是初期程序设计中非常重要的一环。
网格化
本程序调用了 JFrame 中的图形界面。对于图形界面本身,有较多的解析度,也就相应地有着更多的复杂度。但将图形界面网格格式化后,数据便有了确切对应的坐标,使得更容易处理。
程序文件层次结构
1 2 3 4 5
| cellmachine/ ├── Cell.java # 细胞类,定义单个细胞的状态和行为 ├── Cellmachine.java # 主程序,控制游戏运行逻辑 ├── Field.java # 场地类,管理细胞网格 └── View.java # 视图类,负责图形渲染
|
类之间的关系
1 2 3 4 5 6 7 8 9 10
| ┌─────────────┐ ┌─────────────┐ │ View │────▶│ Field │ │ (渲染层) │ │ (数据层) │ └─────────────┘ └──────┬──────┘ │ ▼ ┌─────────────┐ │ Cell │ │ (细胞对象) │ └─────────────┘
|
程序源码
Cell.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| package cell; import java.awt.Graphics;
public class Cell { private boolean alive = false; public void die() { alive = false; } public void reborn() { alive = true; } public boolean isAlive() { return alive; } public void draw(Graphics g, int x, int y, int size) { g.drawRect(x, y, size, size); if (alive) { g.fillRect(x, y, size, size); } } }
|
Cellmachine.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| package cellmachine; import javax.swing.JFrame; import cell.Cell; import field.*;
public class Cellmachine { public static void main(String[] args) { Field field = new Field(30, 30); for (int row = 0; row < field.getHeight(); row++) { for (int col = 0; col < field.getWidth(); col++) { field.place(row, col, new Cell()); } }
for (int row = 0; row < field.getHeight(); row++) { for (int col = 0; col < field.getWidth(); col++) { Cell cell = field.get(row, col); if (Math.random() < 0.2) { cell.reborn(); } } }
View view = new View(field); JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setResizable(false); frame.setTitle("CellsMachine"); frame.add(view); frame.pack(); frame.setVisible(true);
for (int i = 0; i < 1000; i++) { for (int row = 0; row < field.getHeight(); row++) { for (int col = 0; col < field.getWidth(); col++) { Cell cell = field.get(row, col); Cell[] neighbour = field.getNeighbour(row, col); int numOfLive = 0; for (Cell c : neighbour) { if (c.isAlive()) { numOfLive++; } } System.out.print("[" + row + "][" + col + "]:"); System.out.print(cell.isAlive() ? "live" : "dead"); System.out.print(":" + numOfLive + "-->"); if (cell.isAlive()) { if (numOfLive < 2 || numOfLive > 3) { cell.die(); System.out.println("die"); } } else if (numOfLive == 3) { cell.reborn(); System.out.println("reborn"); } System.out.println(); } } System.out.println("UPDATE"); frame.repaint(); try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } } } }
|
Field.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| package field; import java.util.ArrayList; import cell.Cell;
public class Field { private int width; private int height; private Cell[][] field;
public Field(int width, int height) { this.width = width; this.height = height; field = new Cell[width][height]; }
public int getWidth() { return width; } public int getHeight() { return height; } public Cell get(int row, int col) { return field[row][col]; }
public Cell place(int row, int col, Cell o) { Cell ret = field[row][col]; field[row][col] = o; return ret; }
public Cell[] getNeighbour(int row, int col) { ArrayList<Cell> list = new ArrayList<Cell>(); for (int i = -1; i < 2; i++) { for (int j = -1; j < 2; j++) { int r = row + i; int c = col + j; if (r > -1 && r < height && c > -1 && c < width && !(r == row && c == col)) { list.add(field[r][c]); } } } return list.toArray(new Cell[list.size()]); }
public void clear() { for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { field[i][j] = null; } } } }
|
View.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| package field; import javax.swing.JPanel; import javax.swing.JFrame; import cell.Cell; import java.awt.Dimension; import java.awt.Graphics;
public class View extends JPanel { private static final long serialVersionUID = -5258995676212660595L; private static final int GRID_SIZE = 16; private Field theField;
public View(Field field) { theField = field; }
@Override public void paint(Graphics g) { super.paint(g); for (int row = 0; row < theField.getHeight(); row++) { for (int col = 0; col < theField.getWidth(); col++) { Cell cell = theField.get(row, col); if (cell != null) { cell.draw(g, col * GRID_SIZE, row * GRID_SIZE, GRID_SIZE); } } } }
@Override public Dimension getPreferredSize() { return new Dimension( theField.getWidth() * GRID_SIZE + 1, theField.getHeight() * GRID_SIZE + 1 ); }
public static void main(String[] args) { Field field = new Field(10, 10); for (int row = 0; row < field.getHeight(); row++) { for (int col = 0; col < field.getWidth(); col++) { field.place(row, col, new Cell()); } } View view = new View(field); JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setResizable(false); frame.setTitle("CellMachine"); frame.add(view); frame.pack(); frame.setVisible(true); } }
|
关于程序的几个问题
问题零:为什么不是在 Cell 中提供 setAlive(boolean) 函数,而是采用较复杂的 die() 和 reborn()?
答:对于这一问题,我没有明确的思路。毕竟两者没有时空复杂度上的区别。我目前能想到的改后的缺陷就是要传入的参数增多,代码结构复杂,可读性略微下降,但感觉都不算什么致命伤……
问题壹:为什么 Field.getNeighbour() 不直接通过 Cell.isAlive() 来返回周围存活细胞的数量,而是返回一个数组让外界来实现数量的统计?
答:Field 只是 Cell 的一个简单的容器,功能只是存储 Cell 对象的集合。但若由 Field 类来实现统计,则需调用 Cell 类中的接口,提高了两类的耦合度,违背了设计原则。
问题贰:为什么不是由 Cell 本身来判断周围邻居的存亡情况来决定接下来 die() 或 reborn() 的行为?
答:如果由 Cell 判断自己下一时刻的状态,那势必要从 Field 中获取周围细胞的数据和 Field 的大小来判断自身的位置,这样就需要定义 Field 对象。这使得 Cell 类与 Field 类的耦合度升高,违背了设计原则。
我对于本程序的看法
在本程序的根本代码逻辑实现中(即 Cellmachine.java 中),首先初始化了网格和细胞,其次在后续的更迭过程中,每次都是从左上一直到右下一格格 扫过,对每一格细胞的下一刻的生存状态进行判断后,改变当前细胞的生存状态,再对下一格的细胞进行如上操作。
但 如此行列有先后顺序的判断操作,会导致上一个细胞的状态改变影响到下一个细胞本应该进行的状态改变,算是该程序逻辑上的漏洞了。相应的反例也很容易举出,便不再赘述。
解决方案
较简单的方案是 Copy 一份相同的 Field,将每个位置的 Cell 的下一时刻的生存状态记录到新的 Field 中,最终用新的 Field 通过 View 展示出来。最终所体现的结果就是整体在同一时刻一起改变,而不是有先后的时间顺序。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| Field currentField = new Field(30, 30); Field nextField = new Field(30, 30);
for (int row = 0; row < height; row++) { for (int col = 0; col < width; col++) { } }
Field temp = currentField; currentField = nextField; nextField = temp;
|
目前感觉,Java 和 C++ 一样,主要是处理面向对象的程序设计,有一定的框架就可以随写随想,相对较为自由。但某些类的接口与数据成员的关系的处理上,降低其耦合度和依赖性的设计较为困难。
以上看法纯个人浅薄见解,如有错误,请包涵斧正。
程序功能演示
原视频演示已移除,可运行代码查看实际效果
参考资料