Skip to content

Instantly share code, notes, and snippets.

@bennuttall
Last active August 29, 2015 14:02
Show Gist options
  • Save bennuttall/d22cf340a44b029e164d to your computer and use it in GitHub Desktop.
Save bennuttall/d22cf340a44b029e164d to your computer and use it in GitHub Desktop.
conway.py
#!/usr/bin/python
from itertools import product
from random import choice
from time import sleep
import mcpi.minecraft as minecraft
mc = minecraft.Minecraft.create()
PX, PY, PZ = mc.player.getPos()
class GameOfLife(object):
def __init__(self, width, height):
self.size = (width, height)
self.random_world()
def __iter__(self):
return self
def __next__(self):
self.evolve_world()
self.mc_draw()
return self
next = __next__
def evolve_cell(self, cell):
alive = cell in self.live_cells
neighbours = self.count_neighbours(cell)
return neighbours == 3 or (alive and neighbours == 2)
def count_neighbours(self, cell):
x, y = cell
deltas = set(product([-1, 0, 1], repeat=2)) - set([(0, 0)])
neighbours = ((x + dx, y + dy) for (dx, dy) in deltas)
return sum(neighbour in self.live_cells for neighbour in neighbours)
def evolve_world(self):
width, height = self.size
world = product(range(width), range(height))
self.live_cells = {cell for cell in world if self.evolve_cell(cell)}
def random_world(self):
width, height = self.size
world = product(range(width), range(height))
self.live_cells = {cell for cell in world if choice([0, 1])}
def draw_cell(self, x, y):
cell = (x, y)
block = 1 if cell in self.live_cells else 0
mc.setBlock(x + PX, PY, y + PZ, block)
def mc_draw(self):
width, height = self.size
for x in range(width):
for y in range(height):
self.draw_cell(x, y)
def main():
mc.camera.setFixed()
mc.camera.setPos(PX, PY + 14, PZ)
game = GameOfLife(10, 10)
for i in game:
sleep(1)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment