🌸 「なでしこ」
>
🍯 「貯蔵庫」
lifegame
🌟新規
📒一覧
🔌
🔍検索
🚪ログイン
lifegame 📖
lifegameprogram
プログラム:
(→大)
<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>ライフゲーム</title> <script src="https://pyscript.net/releases/2025.8.1/core.js" type="module"></script> </head> <body style="text-align: center;"> <!-- ゲーム画面となるCanvasを配置 --- (*1) --> <canvas id="canvas" width="400" height="400"></canvas> </body> <script type="mpy"> import random from js import document, setTimeout # 定数 --- (*2) DEAD, ALIVE = 0, 1 # 生死を表すセルの値 COLORS = ["white", "red"] # セルの色 SIZE = 20 # セルの大きさ COLS = 400 // SIZE # X方向のセルの数 ROWS = 400 // SIZE # Y方向のセルの数 # 描画対象のCanvasとコンテキストの取得 --- (*3) canvas = document.getElementById("canvas") context = canvas.getContext("2d") # セル(二次元リスト)の初期配置をランダムに決定 --- (*4) cells = [[random.choice([DEAD, ALIVE]) for x in range(COLS)] for y in range(ROWS)] def next_generation(cells): """次の世代の処理を行う関数""" # --- (*5) # 次世代のセルの状態をすべて死で初期化 new_cells = [[DEAD] * COLS for _ in range(ROWS)] # 全セルをチェック for y in range(ROWS): for x in range(COLS): # ルールに従って次世代の状態を決定 --- (*6) count = count_alive_cells(cells, x, y) if cells[y][x] == ALIVE: # 生きているセル if count == 2 or count == 3: new_cells[y][x] = ALIVE else: # 死んでいるセル if count == 3: new_cells[y][x] = ALIVE return new_cells def count_alive_cells(cells, x, y): """周囲(8方向)の生きているセルの数をカウント""" # --- (*7) count = 0 for dy in [-1, 0, 1]: for dx in [-1, 0, 1]: if dy == 0 and dx == 0: continue nx, ny = x + dx, y + dy if 0 <= nx < COLS and 0 <= ny < ROWS: count += cells[ny][nx] return count def draw_canvas(): """セルの状態をCanvasに描画する関数""" # --- (*8) for y in range(ROWS): for x in range(COLS): color = COLORS[cells[y][x]] context.fillStyle = color context.fillRect(x*SIZE, y*SIZE, SIZE, SIZE) context.strokeRect(x*SIZE, y*SIZE, SIZE, SIZE) def update(): """定期的に処理を行う関数""" # --- (*9) global cells cells = next_generation(cells) draw_canvas() setTimeout(update, 500) # 500ミリ秒後に再度実行 update() # 最初の描画 </script></html>
プログラムを実行
⭐ isatomoko 作
タイトル:
lifegame
ライセンス:
自分用 (貯蔵庫のみ/転載不可/ハブ保存なし)
タイプ:
html
タグ:
-
利用バージョン:
3.7.9
作成日時:
2025/11/17 00:56
公開の投稿
ログイン
して★を付けよう!
📝作品を編集
作品公開情報
📍この作品のURL:
📍アプリ(即時実行)のURL:
📍アプリ(実行ボタンあり)のURL:
📍ブログパーツ:
上記HTML↑をブログに貼り付けることでアプリを埋め込めます。
📍ライブラリ直リンク - 『!「***」を取込』で使うとき:
通報数:
0
通報って何?