Skip to content

Instantly share code, notes, and snippets.

@Kos
Created November 28, 2018 20:33
Show Gist options
  • Save Kos/6df986d4369b7f80dd81d47dd281f149 to your computer and use it in GitHub Desktop.
Save Kos/6df986d4369b7f80dd81d47dd281f149 to your computer and use it in GitHub Desktop.
Game of Life
import numpy as np
from scipy.signal import convolve2d
def get_neighbour_counts(array):
kernel = np.array([[1, 1, 1], [1, 0, 1], [1, 1, 1]], dtype=int)
return convolve2d(array, kernel, mode="same", boundary="wrap")
def get_next_state(state, neighbours):
return (neighbours == 3) | (state & (neighbours == 2))
def life(array):
return get_next_state(array, get_neighbour_counts(array))
import numpy as np
import curses
import time
from life import life
def format_array(array):
return "\n".join("".join("[]" if col else " " for col in row) for row in array)
initial = np.array(
[
[0] * 10,
[0, 0, 1] + [0] * 7,
[0, 0, 0, 1] + [0] * 6,
[0, 1, 1, 1] + [0] * 6,
[0] * 10,
[0] * 10,
[0] * 10,
[0] * 10,
[0] * 10,
[0] * 10,
],
dtype=bool,
)
def main_curses(stdscr):
curses.curs_set(0)
array = initial
while True:
stdscr.addstr(0, 0, format_array(array))
stdscr.refresh()
time.sleep(0.1)
array = life(array)
def main_stdout():
array = initial
while True:
print(format_array(array))
time.sleep(0.1)
array = life(array)
if __name__ == "__main__":
try:
from curses import wrapper
wrapper(main_curses)
except ImportError:
main_stdout()
import numpy as np
import pytest
from life import get_neighbour_counts, get_next_state
@pytest.mark.parametrize(
"input, expected_output",
[
(
np.array([[0, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], dtype=bool),
np.array([[1, 0, 1, 0], [1, 1, 1, 0], [1, 1, 1, 0]], dtype=int),
),
(
np.array([[0, 1, 1], [1, 0, 0], [1, 0, 1]], dtype=bool),
np.array([[5, 4, 4], [4, 5, 5], [4, 5, 4]], dtype=int),
),
],
)
def test_get_neighbour_counts(input, expected_output):
output = get_neighbour_counts(input)
assert (expected_output == output).all()
@pytest.mark.parametrize(
"state, neighbours, expected_output",
[
[False, 0, False],
[False, 1, False],
[False, 2, False],
[False, 3, True],
[False, 4, False],
[False, 5, False],
[False, 6, False],
[True, 0, False],
[True, 1, False],
[True, 2, True],
[True, 3, True],
[True, 4, False],
[True, 5, False],
],
)
def test_get_next_state(state, neighbours, expected_output):
output = get_next_state(state, neighbours)
assert output == expected_output
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment