Skip to content

Instantly share code, notes, and snippets.

@bslatkin
Forked from hermit0810/my_coroutine_in_py_27
Created December 22, 2017 18:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bslatkin/6934d53441198f3db30d32cb7f1dbf73 to your computer and use it in GitHub Desktop.
Save bslatkin/6934d53441198f3db30d32cb7f1dbf73 to your computer and use it in GitHub Desktop.
from collections import namedtuple
ALIVE = '*'
EMPTY = '-'
Query = namedtuple('Query',('y','x'))
Transition = namedtuple('Transition', ('y', 'x', 'state'))
TICK = object()
class MyReturn(Exception):
def __init__(self, value):
self.value = value
def count_neighbors(y, x):
n_ = yield Query(y + 1, x + 0)
ne = yield Query(y + 1, x + 1)
e_ = yield Query(y + 0, x + 1)
se = yield Query(y - 1, x + 1)
s_ = yield Query(y - 1, x + 0)
sw = yield Query(y - 1, x - 1)
w_ = yield Query(y + 0, x - 1)
nw = yield Query(y + 1, x - 1)
neighbor_state = [ n_, ne, e_, se, s_, sw, w_, nw]
count = 0
for state in neighbor_state:
if state == ALIVE:
count += 1
raise MyReturn(count)
def step_cell(y, x):
state = yield Query(y, x)
#neighbors = yield from count_neighbors(y, x)
it = count_neighbors(y, x)
try:
value = next(it)
while True:
value = it.send((yield value))
except MyReturn as e:
neighbors = e.value
print('Count: ', neighbors)
next_state = game_logic(state, neighbors)
yield Transition(y, x, next_state)
def game_logic(state, neighbors):
if state == ALIVE:
if neighbors < 2:
return EMPTY
elif neighbors > 3:
return EMPTY
else:
if neighbors == 3:
return ALIVE
return state
it = step_cell(10, 5)
q0 = next(it)
print('Me: ', q0)
q1 = it.send(ALIVE)
print('First yield: ', q1)
q2 = it.send(ALIVE)
print('Second yield: ', q2)
q3 = it.send(ALIVE)
print('Third yield: ', q3)
q4 = it.send(EMPTY)
print('Forth yield: ', q4)
q5 = it.send(EMPTY)
print('Fifth yield: ', q5)
q6 = it.send(EMPTY)
print('Sixth yield: ', q6)
q7 = it.send(EMPTY)
print('Seventh yield: ', q7)
q8 = it.send(EMPTY)
print('Eight yield: ', q8)
t1 = it.send(EMPTY)
print('Outcome: ', t1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment