■
Pythonでライフゲーム書いてみた。
Pythonいいなあ。GUIのプログラムが簡単に書けるのはいいよね。
あと標準でGUIのライブラリがあるのもいいよね。
#!/usr/bin/env python import Tkinter class lifeGameBoard(): def __init__(self,w,h): self.w = w self.h = h self.map = [] for ii in range(self.w): row = [] self.map.append(row) for jj in range(self.h): self.map[ii].append(0) def increment(self,inc=1): if inc==0: return w, h = self.w, self.h map = [] for ii in range(w): map.append(self.map[ii][:]) for ii in range(w): for jj in range(h): cntArnd = 0 if 0 < ii-1 < w and 0 < jj-1 < h and map[ii-1][jj-1]: cntArnd = cntArnd + 1 if 0 < ii < w and 0 < jj-1 < h and map[ii ][jj-1]: cntArnd = cntArnd + 1 if 0 < ii+1 < w and 0 < jj-1 < h and map[ii+1][jj-1]: cntArnd = cntArnd + 1 if 0 < ii-1 < w and 0 < jj < h and map[ii-1][jj ]: cntArnd = cntArnd + 1 # if 0 < ii < w and 0 < jj < h and map[ii ][jj ]: cntArnd = cntArnd + 1 if 0 < ii+1 < w and 0 < jj < h and map[ii+1][jj ]: cntArnd = cntArnd + 1 if 0 < ii-1 < w and 0 < jj+1 < h and map[ii-1][jj+1]: cntArnd = cntArnd + 1 if 0 < ii < w and 0 < jj+1 < h and map[ii ][jj+1]: cntArnd = cntArnd + 1 if 0 < ii+1 < w and 0 < jj+1 < h and map[ii+1][jj+1]: cntArnd = cntArnd + 1 if cntArnd==3 and map[ii][jj]==0: self.map[ii][jj] = 1 elif 2 <= cntArnd <= 3 and map[ii][jj]==1: self.map[ii][jj] = 1 else: self.map[ii][jj] = 0 self.increment(inc-1) def press(self,w,h): if self.map[w][h]: self.map[w][h] = 0 else: self.map[w][h] = 1 class Lifegame: def __init__(self): window = Tkinter.Tk() self.width = 200 self.height = 150 self.scale = 4 self.gameBoard = lifeGameBoard(self.width,self.height) self.objects = [] self.canvas = Tkinter.Canvas(window, bg="white", width=self.width*self.scale, height=self.height*self.scale) self.canvas.pack() self.move = Tkinter.Button(window, text="increment", command=self.increment) self.move.pack(side=Tkinter.RIGHT) self.chooser = Tkinter.Scale(window, from_=1, to=10000, orient=Tkinter.HORIZONTAL) self.chooser.pack(side=Tkinter.LEFT) self.canvas.bind("<ButtonPress-1>",self.pressCanvas) self.canvas.bind("<B1-Motion>",self.pressCanvas) self.window = window window.mainloop() def increment(self,count=-1): if count==-1: count = self.chooser.get() if count==0: return self.gameBoard.increment(1) self.paintBoard() self.window.after(1,self.increment,count-1) def paintBoard(self): self.clearCanvas() scale = self.scale for ii in range(self.width): for jj in range(self.height): if self.gameBoard.map[ii][jj]: self.objects.append(self.canvas.create_rectangle(ii*scale, jj*scale, ii*scale+scale, jj*scale+scale, outline="black", fill="black")) def pressCanvas(self,event): self.gameBoard.press(event.x/self.scale,event.y/self.scale) self.paintBoard() def clearCanvas(self): for item in self.objects[:]: self.canvas.delete(item) Lifegame()
すげえ遅いんだけど、どこが遅いんだろう。