⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 game of life.pde

📁 这是一个很经典的编程项目
💻 PDE
字号:
// Based on the work of Bjoern Froehli. Many thanks!

// The grid size 
final int ROW = 30;
final int COL = 30;

// A two dimension array/matrix 
Life[][] world;

void setup() 
{   
  size(600, 600);
  frameRate(8);
  world = new Life[ROW][COL];
  for(int x = 0; x < ROW; x++) {
    for (int y = 0; y < COL; y++) {
      world[x][y] = new Life(width, height, ROW, COL, x, y);
    }
  }
  noStroke();
  smooth();
} 

void draw() 
{
  background(0); 

  // Drawing and update cycle 
  for (int x = 0; x < ROW; x++) { 
    for (int y = 0; y < COL; y++) {
      if (world[x][y].getState() == Life.ALIVE || world[x][y].getState() == Life.BORN) { 
        if (world[x][y].getState() == Life.BORN) {
          world[x][y].setState(Life.ALIVE);
          world[x][y].playSound();
        } 
        world[x][y].display(); 
      } 
    } 
  }

  // Birth and death cycle
  for (int x = 0; x < ROW; x++) { 
    for (int y = 0; y < COL; y++) { 
      int count = aliveNeighbors(x, y); 
      if (count == 3 && world[x][y].getState() == Life.DEAD ) { 
        world[x][y].setState(Life.BORN); 
      }
      if ((count < 2 || count > 3) && world[x][y].getState() == Life.ALIVE) { 
        world[x][y].setState(Life.DEAD);
      } 
    } 
  } 
} 

// Give birth to life
void mouseDragged() {
  for(int i = 0; i < COL; i++) {
    for(int j = 0; j < ROW; j++) {
      world[i][j].clicked(mouseX, mouseY);        
    }
  }     
} 

// Give birth to life
void mousePressed() {
  for(int i = 0; i < COL; i++) {
    for(int j = 0; j < ROW; j++) {
      world[i][j].clicked(mouseX, mouseY);        
    }
  }    
} 

int aliveNeighbors(int x, int y) {
  int numberAlive = 0;

  // NORTH neighbor 
  if (world[x][(y + COL - 1) % COL].getState() == Life.ALIVE)
    numberAlive++;
  // NORTH EAST neighbor
  if (world[(x + 1) % ROW][(y + COL - 1) % COL].getState() == Life.ALIVE)
    numberAlive++;
  // EAST neighbor
  if (world[(x + 1) % ROW][y].getState() == Life.ALIVE)
    numberAlive++;
  // SOUTH EAST neighbor
  if (world[(x + 1) % ROW][(y + 1) % COL].getState() == Life.ALIVE)
    numberAlive++;
  // SOUTH neighbor
  if (world[x][(y + 1) % COL].getState() == Life.ALIVE)
    numberAlive++;
  // SOUTH WEST neighbor
  if (world[(x + ROW - 1) % ROW][(y + 1) % COL].getState() == Life.ALIVE)
    numberAlive++;
  // WEST neighbor
  if (world[(x + ROW - 1) % ROW][y].getState() == Life.ALIVE)
    numberAlive++;  
  // NORTH WEST neighbor
  if (world[(x + ROW - 1) % ROW][(y + COL - 1) % COL].getState() == Life.ALIVE)
    numberAlive++;

  return numberAlive; 
} 

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -