听起来你希望世界每次都像康威的生活一样以同样的方式发展。在 Life 中,您查看每个单元格并根据之前的状态计算它的结果。如果细胞有两个邻居,它就会活到下一代,不管这些邻居在下一代是否会存在。原始状态应该是只读的,无论如何规则都应该起作用。
例如,如果你有两只狼靠近一只羊,它们会同时吃掉它,还是只吃一只呢?如果只有一个,那么您需要一个规则,其中一个可以吃羊,另一个需要知道这一点。你可以走相反的路,即看羊,找一只会吃它的动物。假设您只想让一只狼吃羊,并且您说具有最低“Y”坐标的狼得到羊,或者如果有两只具有相同“Y”的狼,则最低的“X”坐标。如果你正在处理一只狼,你需要确保没有其他狼会先吃羊。这可能会变得更加混乱,因为也许它附近会有另一只羊会吃,所以它不会吃第一只......
最简单的方法是说所有动物都可以做它们的动作,不管它们在进化到下一轮的过程中发生了什么,或者任何其他动物做了什么。如果一只羊被三只狼围着,下一轮就死了,所有的狼都分食。如果羊旁边有草,即使羊被狼包围,羊也会吃草。对于狼来说,他们都会在这一轮被喂饱,因为他们旁边是一只羊。
public class Cell {
public int CellType = 0; // 0 == empty, 1 == grass, 2 == sheep, 3 == wolf
public int Feedings = 0;
}
public class World {
public Cell [] Cells = new Cell[100];
public int Rows = 10, Cols = 10;
public Cell GetCell(x, y) {
if (x < 0 || x >= Cols || y < 0 || y >= Rows) return null;
if (Cells[y * Cols + x] == null) {
Cells[y * Cols + x] = new Cell();
}
return Cells[y * Cols + x];
}
public World Evolve() {
World w = new World();
for (int y = 0; y < Rows; y++) {
for (int x = 0; x < Cols; x++) {
HandleCell(w, x, y);
}
}
return w;
}
public void HandleCell(World newWorld, int x, int y) {
Cell result = newWorld.GetCell(x, y);
Cell c = GetCell(x, y);
if (c.CellType == 2) { // sheep
bool foundWolf = false;
bool foundGrass = false;
// code here to find if a wolf or grass are around the sheep
if (foundWolf) {
// default cell type is empty, so leave it be (wolf ate me)
} else {
result.cellType = 2; // still a sheep here
if (foundGrass) {
result.Feedings = c.Feedings + 1; // and he ate!
} else {
result.Feedings = c.Feedings; // or not...
}
}
}
if (c.CellType == 3) { // wolf
bool foundSheep = false;
// code here to find if a sheep is around the wolf
result.CellType = 3;
if (foundSheep) {
result.Feedings = c.Feedings + 1; // ate the sheep!
} else {
result.Feedings = c.Feedings;
}
}
}