-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlife
More file actions
executable file
·74 lines (65 loc) · 1.97 KB
/
life
File metadata and controls
executable file
·74 lines (65 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#!/usr/bin/env python
# coding: utf-8
#
# Conway's Game of Life in Python
#
# Game of life is a 0-player game, it's more like a simulation.
# It consists of a bunch of cells that have neighbors, and are
# either alive or dead.
import numpy as np
import os
import time
class GameOfLife():
def __init__(self, h, w):
self.w = w
self.h = h
self.grid = np.zeros((h, w), np.int8)
def __str__(self):
g = self.grid
s = ""
for x in range(self.h):
for y in range(self.w):
if g[x][y] == 1: # alive
s += "#"
else:
s += " "
s += "\n"
return s
def init_glider(self):
alive = 1
self.grid[1][2] = alive
self.grid[2][3] = alive
self.grid[3][1] = alive
self.grid[3][2] = alive
self.grid[3][3] = alive
def step(self):
""" Evolve the game forward 1 time step
Any live cell with fewer than two live neighbours dies, as if caused by underpopulation.
Any live cell with two or three live neighbours lives on to the next generation.
Any live cell with more than three live neighbours dies, as if by overpopulation.
Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
"""
alive = 1
dead = 0
g = self.grid
ng = np.copy(self.grid) # ng stands for 'next grid'
for x in range(self.h):
for y in range(self.w):
xmin,xmax = (max(0, x-1), min(x+2, self.h))
ymin,ymax = (max(0, y-1), min(y+2, self.w))
neighbors = g[xmin:xmax, ymin:ymax]
alive_neighbor_count = neighbors.sum() - g[x][y] # if cell is alive, don't count it
if g[x][y] == alive and (alive_neighbor_count < 2 or alive_neighbor_count > 3):
ng[x][y] = dead
elif g[x][y] == dead and alive_neighbor_count == 3:
ng[x][y] = alive
self.grid = ng
# Glider Test
size = 20
game = GameOfLife(size,size)
game.init_glider()
while True:
os.system("clear")
print(game)
game.step()
time.sleep(0.2)