プロンプト
import tkinter as tk
# ゲームの設定
GRID_SIZE = 50
CELL_SIZE = 10
DELAY = 100 # ミリ秒
# グローバル変数
grid = [[0] * GRID_SIZE for _ in range(GRID_SIZE)]
next_grid = [[0] * GRID_SIZE for _ in range(GRID_SIZE)]
running = False
# グリッドの初期化
def initialize_grid():
for i in range(GRID_SIZE):
for j in range(GRID_SIZE):
grid[i][j] = 0
# グリッドの描画
def draw_grid():
canvas.delete('rect')
for i in range(GRID_SIZE):
for j in range(GRID_SIZE):
x1 = i * CELL_SIZE
y1 = j * CELL_SIZE
x2 = x1 + CELL_SIZE
y2 = y1 + CELL_SIZE
if grid[i][j] == 1:
canvas.create_rectangle(x1, y1, x2, y2, fill='black', tags='rect')
# ライフゲームのルールに基づいて次の世代のグリッドを計算
def compute_next_generation():
for i in range(GRID_SIZE):
for j in range(GRID_SIZE):
count = count_neighbors(i, j)
if grid[i][j] == 1:
if count < 2 or count > 3:
next_grid[i][j] = 0
else:
next_grid[i][j] = 1
else:
if count == 3:
next_grid[i][j] = 1
else:
next_grid[i][j] = 0
# 指定されたセルの周囲の生きているセルの数をカウント
def count_neighbors(row, col):
count = 0
for i in range(-1, 2):
for j in range(-1, 2):
if i == 0 and j == 0:
continue
if row + i < 0 or row + i >= GRID_SIZE or col + j < 0 or col + j >= GRID_SIZE:
continue
if grid[row + i][col + j] == 1:
count += 1
return count
# ゲームの状態を進める
def step():
compute_next_generation()
for i in range(GRID_SIZE):
for j in range(GRID_SIZE):
grid[i][j] = next_grid[i][j]
draw_grid()
if running:
root.after(DELAY, step)
# セルをクリックしたときの処理
def cell_clicked(event):
x = event.x // CELL_SIZE
y = event.y // CELL_SIZE
if grid[x][y] == 0:
grid[x][y] = 1
else:
grid[x][y] = 0
draw_grid()
# ゲームの開始と停止
def toggle_game():
global running
running = not running
if running:
start_button.config(text='停止')
step()
else:
start_button.config(text='開始')
# ウィンドウの作成
root = tk.Tk()
root.title('ライフゲーム')
# キャンバスの作成
canvas_width = GRID_SIZE * CELL_SIZE
canvas_height = GRID_SIZE * CELL_SIZE
canvas = tk.Canvas(root, width=canvas_width, height=canvas_height)
canvas.bind('', cell_clicked)
canvas.pack()
# ボタンの作成
button_frame = tk.Frame(root)
button_frame.pack()
start_button = tk.Button(button_frame, text='開始', command=toggle_game)
start_button.pack(side='left')
reset_button = tk.Button(button_frame, text='リセット', command=initialize_grid)
reset_button.pack(side='left')
# グリッドの初期化と描画
initialize_grid()
draw_grid()
# ゲームのメインループを開始
root.mainloop()