日々夢想

つれづれなるままに ひぐらし すずりにむかいて 

PHPでライフゲーム実装

PHPの腕試しにライフゲームを実装。
改善点は残っていますが、とりあえずアップ。
今後は、関数化とライフゲーム関連処理の別ファイルへの移動、セッション削除をやってみる。
あと、手動でブラウザ更新かけないと世代が進まないので、自動更新したい。
オブジェクト指向もやってみたい。

<?php
session_start();

define('CELL_STATUS_ERROR', -1);
define('CELL_STATUS_DEATH', 0);
define('CELL_STATUS_ALIVE', 1);

function drawLifeGameField($cellField) {
  $int2CellStatusClassName = array ('cell-death', 'cell-alive' );

  print "<table class=\"life-game-field\">";
  for ($i = 0; $i<count($cellField); $i++) {
    print '<tr>';
    for ($j = 0; $j<count($cellField[$i]); $j++) {
      print "<td class='" . $int2CellStatusClassName[$cellField[$i][$j]] . "'>";
      print '</td>';
    }
    print '</tr>';
  }
  print '</table>';
}

function whatNextStatusOfCell($totalAliveCells, $cellStatus) {
  $nextCellStatus;
  switch ( $cellStatus ) {
    case CELL_STATUS_ALIVE;
      if ( $totalAliveCells <= 1 || $totalAliveCells >= 4) {
        $nextCellStatus = CELL_STATUS_DEATH;
      } else /*if ( $totalAliveCells === 2 || $totalAliveCells === 3 )*/ {
        $nextCellStatus = CELL_STATUS_ALIVE;
      }
      break;
    case CELL_STATUS_DEATH;
        if ( $totalAliveCells === 3 ) {
          $nextCellStatus = CELL_STATUS_ALIVE;
        } else {$nextCellStatus = CELL_STATUS_DEATH;}
      break;
    default:
      $nextCellStatus = CELL_STATUS_ERROR;
      break;
  }
  return $nextCellStatus;
}

function updateCell($x, $y, &$cellField) {
  $lifeStatus = CELL_STATUS_ERROR;

  $totalAliveCells = 0;
  for ( $dy = -1;  $dy <= 1; $dy++ ) {
    for ( $dx = -1; $dx <= 1; $dx++ ) {
      if ( $dy === 0 && $dx === 0 ) continue;
      if ( isset($cellField[$y+$dy][$x+$dx]) ) {
        $totalAliveCells += $cellField[$y+$dy][$x+$dx];
      }
    }
  }

  $lifeStatus = whatNextStatusOfCell($totalAliveCells, $cellField[$y][$x]);
  if ( $lifeStatus === CELL_STATUS_ERROR ) {
    alert('システムエラーが発生しました。プログラムを強制終了します。');
    exit;
  }

  return $lifeStatus;
}

$xSize = 10;
$ySize = 10;
$cellFieldTmp = array();

// initialize
if ( !isset($_SESSION['cellField']) ) {
  for ($i=0; $i<$ySize; $i++) {
    for ($j=0; $j<$xSize; $j++) {
      $_SESSION['cellField'][$i][$j] = mt_rand(0,1);
    }
  }
}

// start life-game
for ( $y=0; $y<$ySize; $y++ ) {
  for ( $x=0; $x<$xSize; $x++ ) {
    $cellFileldTmp[$y][$x] = updateCell($x,$y,$_SESSION['cellField']);
  }
}
$_SESSION['cellField'] = $cellFileldTmp;
?>

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>ライフゲーム</title>
<style>
table.life-game-field td.cell-death{
  width:10px;
  height:10px;
}
table.life-game-field td.cell-death {
  background-color:#000;
}
table.life-game-field td.cell-alive {
  background-color:#f00;
}
</style>
</head>

<body>
<?php drawLifeGameField($_SESSION['cellField']); ?>
</body>
</html>

<?php