-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")
你是什麼意思「看起來不正確」? –
@arc_lupus查看圖片 –
你期待什麼? –