ランダムな状態で始まるライフゲームを表示するアプリ
ライフゲームアプリ
ライフゲームアプリ
以下が、ユーザーの要望に基づいた、可能な限りセキュリティを考慮したライフゲームアプリのサンプルコードです。このコードには、サードパーティのライブラリや外部のスクリプトは含まれていません。 注意:このアプリは、ブラウザのJavaScriptエンジンに依存しています。一部のブラウザでは実行できないか、動作が遅い場合があります。 ``` <!doctype html> <html> <head> <meta charset="UTF-8"> <title>ライフゲームアプリ</title> <style> td {width: 10px; height: 10px;} </style> </head> <body> <h1>ライフゲームアプリ</h1> <table id="life" border="1"></table> <button id="play">再生</button> <button id="stop">停止</button> <button id="step">一歩進む</button> <script> const ROWS = 50; const COLS = 50; const INTERVAL = 250; const lifeTable = document.getElementById('life'); const playButton = document.getElementById('play'); const stopButton = document.getElementById('stop'); const stepButton = document.getElementById('step'); let playing = false; let timer = null; let generation = 0; // 初期状態をランダムに生成する let state = Array.from(Array(ROWS), () => Array.from(Array(COLS), () => Math.random() < 0.5)); // 画面に描画する function render() { const tableHTML = state.map(row => `<tr>${row.map(cell => `<td bgcolor="${cell ? '#000000' : '#FFFFFF'}"></td>`).join('')}</tr>`).join(''); lifeTable.innerHTML = tableHTML; } // 状態を進める function step() { const nextState = Array.from(Array(ROWS), () => Array.from(Array(COLS), () => false)); for (let row = 0; row < ROWS; row++) { for (let col = 0; col < COLS; col++) { const neighborCount = getNeighborCount(row, col); if (state[row][col]) { // 生きているセル if (neighborCount === 2 || neighborCount === 3) { // 2か3つの隣接セルが生きている場合、次の世代でも生き残る nextState[row][col] = true; } } else { // 死んでいるセル if (neighborCount === 3) { // ちょうど3つの隣接セルが生きている場合、次の世代で誕生する nextState[row][col] = true; } } } } state = nextState; generation++; render(); } // (row, col)のセルの隣接セルの生存数を返す function getNeighborCount(row, col) { let count = 0; for (let i = -1; i <= 1; i++) { for (let j = -1; j <= 1; j++) { if (i === 0 && j === 0) continue; const neighborRow = row + i; const neighborCol = col + j; if (neighborRow < 0 || neighborRow >= ROWS) continue; if (neighborCol < 0 || neighborCol >= COLS) continue; if (state[neighborRow][neighborCol]) count++; } } return count; } // 再生ボタンが押された時に呼ばれる function startPlaying() { if (playing) return; playing = true; playButton.disabled = true; stopButton.disabled = false; stepButton.disabled = true; timer = setInterval(step, INTERVAL); } // 停止ボタンが押された時に呼ばれる function stopPlaying() { if (!playing) return; playing = false; clearInterval(timer); timer = null; playButton.disabled = false; stopButton.disabled = true; stepButton.disabled = false; } playButton.addEventListener('click', startPlaying); stopButton.addEventListener('click', stopPlaying); stepButton.addEventListener('click', step); render(); </script> </body> </html> ``` ジョーク:「このアプリは、科学的に証明されている唯一の方法で、除草剤に対する耐性を身につけることができます。」