就像题目说的,这是一个模拟细胞繁衍的游戏,规则是:
当细胞周围<2 || >3 个细胞时,那个细胞就挂掉(太挤太窄都不行啊,怪我咯);
当一个死掉的细胞周围恰好有 3 个细胞时(换成2太拥挤,4的话就没得玩了,没几轮就不动了),它就满血复活啦~~
其实这个游戏主要还是想说明这个道理:表现和数据分离,这尼玛到底是怎么来玩的。
就这么简单的规则。来看看怎么样实现;
先来撸一撸思路啊(其实我是想打捋一捋的~·~),是这样:
既然是模拟细胞,不用说,必然有个Cell Class;
既然是表现和数据分离,那我们总的有个表现类和数据类啊。
好丑的图,不忍直视....
下面就开撸吧:
先把一个个类先建好,不要求弄好,先搭个架子
来个最简单的Cell类:
public class Cell {
private boolean isAlive = false;
public boolean isAlive() {
return this.isAlive;
}
public void die() {
this.isAlive = false;
}
public void reborn() {
this.isAlive = true;
}
public void draw(Graphics g, int row, int col, int size){
g.drawRect(row, col, size, size);
if(isAlive){
g.fillRect(row, col, size, size);
}
}
}
再来个复杂点的:
package field;
import java.util.ArrayList;
import java.util.List;
import cell.Cell;
public class Field {
private int height;
private int width;
private Cell[][] cells;
public Field(int height, int width) {
this.height = height;
this.width = width;
cells = new Cell[height][width];
}
public int getHeight() {
return this.height;
}
public int getWidth() {
return this.width;
}
public Cell place(int row, int col, Cell cell) {
Cell ret = cells[row][col];
cells[row][col] = cell;
return ret;
}
public Cell getCell(int row , int col) {
return cells[row][col];
}
public Cell[] getNeighbour(int row , int col) {
List<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 && c > -1 && r < this.height && c < this.width
&& !( r == row && c == col)) {
list.add(cells[r][c]);
}
}
}
return list.toArray(new Cell[list.size()]);
}
}