OneHourProcessing 七日目

OneHourProcessing 七日目

一週間経った…だと…?
今日作ったのは「ライフゲーム
内容はこんな感じ

作るのにかかった時間は「52分58秒」
久々の時間内…やったぜ

コード

Board board;

void setup()
{
  size(800, 450);
  reset();
}

void draw()
{
  background(0);
  board.game();
}

void reset()
{
  board = null;
  board = new Board(80, 45);
  board.addPerturn(int(random(40)) + 20, int(random(15)) + 15, "RANDOM");
  board.addPerturn(int(random(40)) + 20, int(random(15)) + 15, "RANDOM");
  board.addPerturn(int(random(40)) + 20, int(random(15)) + 15, "RANDOM");
}

void mousePressed()
{
  if (mouseButton == LEFT)
    board.addPerturn(2, mouseY / (height / 45), "SPACESHIP");
  else
    reset();
}

Boardクラス

class Board
{
  int Xsize, Ysize;
  Cell[][] cells;

  Board(int Xsize, int Ysize)
  {
    this.Xsize = Xsize;
    this.Ysize = Ysize;
    cells = new Cell[Xsize][Ysize];

    for (int x = 0; x < Xsize; x++)
      for (int y = 0; y < Ysize; y++)
        cells[x][y] = new Cell(x, y, height / Ysize);
  }

  void game()
  {
    update();
    display();
    finish();
  }

  void display()
  {
    for (int x = 0; x < Xsize; x++)
      for (int y = 0; y < Ysize; y++)
        cells[x][y].display();
  }

  void update()
  {
    for (int x = 1; x < Xsize - 1; x++)
      for (int y = 1; y < Ysize - 1; y++)
        checkNeighbor(x, y);
  }

  void finish()
  {
    for (int x = 0; x < Xsize; x++)
      for (int y = 0; y < Ysize; y++)
        cells[x][y].finish();
  }

  void checkNeighbor(int x, int y)
  {
    int neighbor = 0;
    for (int addX = -1; addX <= 1; addX++)
      for (int addY = -1; addY <= 1; addY++)
        neighbor += cells[x + addX][y + addY].state;

    neighbor -= cells[x][y].state;

    switch(neighbor)
    {
    case 2:
      if (cells[x][y].state == 0)
        break;
    case 3:
      cells[x][y].nextState = 1;
      break;

    default:
      cells[x][y].nextState = 0;
    }
  }

  void addPerturn(int x, int y, String perturn)
  {
    if (x < 1 || y < 1 || x > Xsize - 2 || y > Ysize - 2)
      return;

    switch(perturn)
    {
    case "RANDOM":
      for (int addX = 0; addX < 3; addX++)
        for (int addY = 0; addY < 3; addY++)
          cells[x + addX][y + addY].state = int(random(2));
      break;
      
    case "SPACESHIP":
          cells[x][y].state = 1;
          cells[x][y + 2].state = 1;
          cells[x + 1][y + 3].state = 1;
          cells[x + 2][y + 3].state = 1;
          cells[x + 3][y + 3].state = 1;
          cells[x + 4][y + 3].state = 1;
          cells[x + 4][y + 2].state = 1;
          cells[x + 4][y + 1].state = 1;
          cells[x + 3][y].state = 1;
      break;
    }
  }
}

Cellクラス

class Cell
{
  int x, y, state, nextState;
  float size;

  Cell(int x, int y, float size)
  {
    this.x = x;
    this.y = y;
    state = 0;
    nextState = 0;
    this.size = size;
  }
  
  void finish()
  {
    state = nextState;
  }

  void display()
  {
    if (state == 1)
      fill(0, 255, 0);
    else
      fill(0, 0);

    rect(x * size, y * size, size, size);
  }
}