您的位置:首页 > 其它

模拟条件超简单的细胞繁衍游戏之二

2015-12-27 00:00 239 查看
前面给出了Cell类和Field类的代码,现在再把View类的代码写出来:

import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import cell.Cell;
import field.Field;
public class View extends JPanel {
private static final int GIRD_SIZE = 16;
private Field field;

public View(Field field){
this.field = field;
}

@Override
public void paint(Graphics g) {
super.paint(g);
for(int row = 0; row < field.getHeight(); row ++) {
for( int col = 0; col < field.getWidth(); col ++) {
Cell cell = field.getCell(row, col);
if(cell != null) {
cell.draw(g, row * GIRD_SIZE, col * GIRD_SIZE, View.GIRD_SIZE);
}
}
}
}

@Override
public Dimension getPreferredSize() {
return new Dimension(field.getHeight() * View.GIRD_SIZE + 1, field.getWidth() * View.GIRD_SIZE + 1);
}

}

至此,已经给出了数据类,表现类,现在再来看看指挥类:

import javax.swing.JFrame;
import cell.Cell;
import field.Field;
import view.View;
public class Cellmachine {

public static void main(String[] args) {
//初始化field
Field field = new Field(30, 30);
//设置每个cell对象的位置;
for(int row = 0; row < field.getHeight(); row ++) {
for(int col = 0; col < field.getWidth(); col ++) {
field.place(row, col, new Cell());
}
}
//随机激活cell对象;
for(int row = 0; row < field.getHeight(); row ++) {
for(int col = 0; col < field.getWidth(); col ++) {
Cell cell = field.getCell(row, col);
if(Math.random() < 0.2) {
cell.reborn();
}
}
}
//创建窗口
JFrame frame = new JFrame();
View view = new View(field);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setTitle("cellMachine");
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.getCell(row, col);
Cell[] neighbour = field.getNeighbour(row, col);
int numofAlive = 0;
for(Cell c : neighbour){
if(c.isAlive()) {
numofAlive ++;
}
}
System.out.print("[" + row + "][" + col + "]: ");
System.out.print(cell.isAlive() ? "alive" : "dead");
System.out.print("-->");
if(cell.isAlive()){
if(numofAlive < 2 || numofAlive > 3) {
cell.die();
System.out.print("die");
}
}else if(numofAlive == 3) {
cell.reborn();
System.out.print("reborn");
}
System.out.println();
}
}
frame.repaint();
System.out.println("repaint");
System.out.println(i);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

这个游戏跑起来很简单,代码还有好多改进的空间。所谓数据与表现分离,也可略窥一二:Field类只管对Cell类数据的管理,包括 对Cell对象指定位置place(),取得位置,取得邻居对象;View类只管把Cell对象画出来;Cell对象既不认识Field类对象,也不知道自己的位置和邻居;这样它们之间的耦合就很低了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: