2016-04-10 105 views
-1

我試圖讓康威在python中的生活遊戲,然後將輸出保存到圖片中,但我認爲邏輯有問題,因爲大多數圖片看起來不太完整正確。 (見圖片)game of life pic康威在python中的生活遊戲

import PIL.Image, random 

WIDTH = 1366 
HEIGHT = 768 
ROUNDS = 10 

DEAD = (0, 0, 0) 
ALIVE = (0, 64, 255) 

print("Creating image") 
img = PIL.Image.new("RGB", (WIDTH, HEIGHT)) 
data = img.load() 

print("Creating grid") 
grid = [] 
for y in range(HEIGHT): 
    grid.append([]) 
    for x in range(WIDTH): 
     grid[y].append(random.randint(0, 1)) 

for i in range(ROUNDS): 
    print("Starting round", i + 1, "of", ROUNDS) 
    for y in range(HEIGHT): 
     for x in range(WIDTH): 
      n = 0 
      for y2 in range(-1, 2): 
       for x2 in range(- 1, 2): 
        if x2 != 0 and y2 != 0 and grid[(y + y2) % HEIGHT][(x + x2) % WIDTH] == 1: 
         n += 1 
      if n < 2: 
       grid[y][x] = 0 
      elif n > 3: 
       grid[y][x] = 0 
      elif grid[y][x] == 1 and n > 1 and n < 4: 
       grid[y][x] = 1 
      elif grid[y][x] == 0 and n == 3: 
       grid[y][x] = 1 

print("Rendering image") 
for y in range(HEIGHT): 
    for x in range(WIDTH): 
     if grid[y][x] == 1: 
      data[x, y] = ALIVE 
     else: 
      data[x, y] = DEAD 

print("Saving image") 
img.save("gofl.png") 
+0

你是什麼意思「看起來不正確」? –

+0

@arc_lupus查看圖片 –

+0

你期待什麼? –

回答

1

你的程序不能在當前狀態下正常工作,因爲你在最後一代被存儲在同一格計算的下一代。您需要一個新的(空的)網格來存儲下一代。在你的實現中,你在計算下一代時已經覆蓋了上一代。