Skip to content

Instantly share code, notes, and snippets.

@dev001hajipro
Created March 9, 2017 07:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dev001hajipro/c75124209419833b46f16632b0319de5 to your computer and use it in GitHub Desktop.
Save dev001hajipro/c75124209419833b46f16632b0319de5 to your computer and use it in GitHub Desktop.
function initCanvas(w, h) {
var canvas = document.getElementById("myCanvas");
canvas.width = w;
canvas.height = h;
canvas.style.width = w + "px";
canvas.style.height = h + "px";
return canvas.getContext('2d');
}
function main() {
var maxRows = 600;
var maxColumns = 600;
var ctx = initCanvas(maxRows,maxColumns);
// 初期設定
var cells = new Array(maxRows);
for (var i = 0; i < maxColumns; i++) {
cells[i] = new Array(maxColumns).fill(0);
}
cells[0][maxColumns/2] = 1;
// 画面クリア
ctx.fillStyle = "rgba(255,255,255,1)";
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
rule = [0,0,0,1,1,1,1,0];
var boxSize = 1;
for (var t = 0; t < maxRows; t++) {
for (var x = 0; x < maxColumns; x++) {
// 計算
if (t > 0) {
var l = (x+maxColumns-1) % maxColumns;
var r = (x+1) % maxColumns;
var code = cells[t-1][l] * 4 + cells[t-1][x] * 2 + cells[t-1][r] * 1;
cells[t][x] = rule[7-code];
}
// 描画
if (cells[t][x] == 1) {
ctx.fillStyle = "rgba(0,0,0, 1)";
ctx.fillRect(x * boxSize, t * boxSize, boxSize, boxSize);
}
}
}
}
main();
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Rule30 - Cellular Automaton</title>
</head>
<body style="margin:0;padding:0">
<canvas id="myCanvas"></canvas>
<script src="cellular_automaton_rule30.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment