简单细胞自动机

细胞自动机

绘制二维简单细胞自动机

使用processing编辑简单细胞自动机

图片显示:
在这里插入图片描述
###自定义条件及规则

  1. 其中细胞的生命状态1为生,0为死
  2. 细胞的形式为方格形式
  3. 更新规则:开始死亡状态:当期周围的细胞活着的数量>=4或者=1时;开始重生状态:当该细胞处于死亡状态以及周围的细胞活着的数量=3时;保持生状态:本身为生且周围的获得细胞数量=2、3;保持死状态:本身为死且周围活着的细胞数量不等于3;
  4. 颜色变化:之前状态是死,当前细胞状态是活着,显示绿色;之前状态为活着,当前细胞状态为死亡,那么填充红色;细胞保持活,为黑色;其他情况方格为白色

####源码

主程序:

RULES rules;
void setup() {
  size(500, 400);
  smooth();
  rules = new RULES();
}
void draw() {
  background(255);
  rules.generate();
  rules.display();
}
void mousePressed() {
  rules.init();
}

Cell类

class Cell {
  float x, y;
  float w;
  int state;  //细胞的当前状态
  int previous;  //细胞的之前状态
  Cell(float x_, float y_, float w_) {
    x = x_;
    y = y_;
    w = w_;
    state = int(random(2));  //初始状态为随机
    previous = state;  //之前状态设为细胞初始状态
  }
  void savePrevious() {
    previous = state;   
  }
  void newState(int s) {
    state = s;
  }
  void display() {
    if (previous == 0 && state == 1) fill(0,255,0);
    else if (state == 1) fill(0);
    else if (previous == 1 && state == 0) fill(255,0,0);
    else fill(255);
    stroke(0);
    rect(x, y, w, w);
  }
}

Rules类

class RULES {
  int w = 10;
  int columns, rows;
  Cell[][] board;
  RULES() {
    columns = width/w;
    rows = height/w;
    board = new Cell[columns][rows];
    init();
  }
  //给每个二维细胞随机状态
  void init() {
    for (int i =0;i < columns;i++) {
      for (int j =0;j < rows;j++) {
        board[i][j] = new Cell(i*w, j*w, w);
      }
    }
  }
  void generate() {
    for ( int i = 0; i < columns;i++) {
      for ( int j = 0; j < rows;j++) {
        board[i][j].savePrevious();
      }
    }
    for (int x = 0; x < columns; x++) {
      for (int y = 0; y < rows; y++) {
        int neighbors = 0;
        for (int i = -1; i <= 1; i++) {
          for (int j = -1; j <= 1; j++) {
              neighbors += board[(x+i+columns)%columns][(y+j+rows)%rows].previous; 
              //使用之前的状态统计邻居活着的数量
          }
        }
        neighbors -= board[x][y].previous;
        if      ((board[x][y].state == 1) && (neighbors <  2)) board[x][y].newState(0); 
         // 中心细胞活着,邻居细胞活着少于2个细胞,下一代中心细胞死亡
        else if ((board[x][y].state == 1) && (neighbors >  3)) board[x][y].newState(0);
         // 中心细胞活着,邻居细胞活着大于3个细胞,下一代中心细胞死亡
        else if ((board[x][y].state == 0) && (neighbors == 3)) board[x][y].newState(1);
        // 中心细胞死亡,邻居细胞活着等于3个细胞,下一代中心细胞活着
      }
    }
  }
  void display() {
    for ( int i = 0; i < columns;i++) {
      for ( int j = 0; j < rows;j++) {
        board[i][j].display();
      }
    }
  }
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值