Python(3.2) で Tkinter モジュールを使い始めたばかりなので、古いプログラム (curses モジュールを使用) をこのモジュールで書き直すことにしました。このプログラムは、Game of Lifeシミュレーターです。私が実装したアルゴリズムは、ユーザー インターフェイスがなくてもすぐに機能します。これは私のプログラムです(これは簡単な実験であり、キャンバスウィジェットを使用したことはありません):
#!/usr/bin/python3
import gol
import Tkinter as tk
class Application(tk.Frame):
def __init__(self):
self.root = tk.Tk()
self.root.wm_title('Canvas Experiments')
tk.Frame.__init__(self, self.root)
self.draw_widgets()
self.world = gol.World(30, 30)
self.world.cells[25][26] = True
self.world.cells[26][26] = True
self.world.cells[27][26] = True
self.world.cells[25][27] = True
self.world.cells[26][28] = True
def draw_widgets(self):
self.canvas = tk.Canvas(
width = 300,
height = 300,
bg = '#FFF')
self.canvas.grid(row = 0)
self.b_next = tk.Button(
text = 'Next',
command = self.play)
self.b_next.grid(row = 1)
self.grid()
def play(self):
def draw(x, y, alive):
if alive:
self.canvas.create_rectangle(x*10, y*10, x*10+9, y*10+9, fill='#F00')
else:
self.canvas.create_rectangle(x*10, y*10, x*10+9, y*10+9, fill='#FFF')
for y in range(self.world.width):
for x in range(self.world.height):
draw(x, y, self.world.cells[x][y])
self.world.evolve()
app = Application()
app.mainloop()
私はゴールを報告しませんでしたが、問題はそのモジュールにはありません。問題は、プログラムが非常に遅いことです。キャンバスをうまく使えていないと思います。
編集: ここに gol モジュールがありますが、これは問題ではないと思います...
#!/usr/bin/python3
class World:
def __init__(self, width, height):
self.width, self.height = width, height
self.cells = [[False for row in range(self.height)] for column in range(self.width)]
def neighbours(self, x, y):
counter = 0
for i in range(-1, 2):
for j in range(-1, 2):
if ((0 <= x + i < self.width) and (0 <= y + j < self.height) and not (i == 0 and j == 0)):
if self.cells[x + i][y + j]:
counter += 1
return counter
def evolve(self):
cells_tmp = [[False for row in range(self.height)] for column in range(self.width)]
for x in range(self.width):
for y in range(self.height):
if self.cells[x][y]:
if self.neighbours(x, y) == 2 or self.neighbours(x, y) == 3:
cells_tmp[x][y] = True
else:
if self.neighbours(x, y) == 3:
cells_tmp[x][y] = True
self.cells = cells_tmp