Last active
November 28, 2023 18:01
-
-
Save villares/646497878b5a74eef51f876d95d912f5 to your computer and use it in GitHub Desktop.
silly game of life with Processing and Python, using py5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# You *need* to install py5! | |
# Instructions at https://py5.ixora.io/ | |
from collections import Counter | |
from random import randint | |
import py5 | |
cell_size = 4 | |
current_board = set() | |
def setup(): | |
py5.size(512, 512) | |
global ox, oy | |
ox, oy = py5.width / 2, py5.height / 2 | |
py5.no_stroke() | |
add_cells() | |
def add_cells(): | |
for _ in range(500): | |
cell = randint(-50, 50), randint(-50, 50) | |
current_board.add(cell) | |
def draw(): | |
py5.translate(ox * cell_size, oy * cell_size) | |
py5.background(0) | |
for x, y in current_board: | |
py5.square(x * cell_size, y * cell_size, cell_size) | |
if py5.frame_count % 2 == 0: | |
update() | |
def update(): | |
global current_board | |
n_counts = Counter() | |
for x, y in current_board: | |
n_counts.update(neighbours(x, y)) | |
next_board = set() | |
for cell in n_counts.keys(): | |
live_n = n_counts[cell] | |
if live_n < 2 or live_n > 3: | |
continue | |
elif live_n == 3: | |
next_board.add(cell) | |
elif cell in current_board: | |
next_board.add(cell) | |
current_board = next_board | |
def neighbours(x, y): | |
neighbourhood = ((-1, 0), (1, 0), (-1, -1), (0, -1), | |
(1, -1), (-1, 1), (0, 1), (1, 1)) | |
return [((x + i), (y + j)) for i, j in neighbourhood] | |
def mouse_dragged(): | |
cell = (py5.mouse_x // cell_size - ox), (py5.mouse_y // cell_size - oy) | |
current_board.add(cell) | |
def key_pressed(): | |
global cell_size, ox, oy | |
if py5.key == ' ': | |
add_cells() | |
elif py5.key == 'a': | |
cell_size *= 2 | |
elif py5.key == 'z' and cell_size > 0.5: | |
print(cell_size) | |
cell_size /= 2 | |
elif py5.key_code == py5.UP: | |
oy -= 16 | |
elif py5.key_code == py5.DOWN: | |
oy += 16 | |
elif py5.key_code == py5.LEFT: | |
ox -= 16 | |
elif py5.key_code == py5.RIGHT: | |
ox += 16 | |
py5.run_sketch() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment