Skip to content

Instantly share code, notes, and snippets.

@niklaskorz
Created May 2, 2014 19:21
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 niklaskorz/571a701f3267c8d47d28 to your computer and use it in GitHub Desktop.
Save niklaskorz/571a701f3267c8d47d28 to your computer and use it in GitHub Desktop.
from time import sleep
w, h = world.getSizeX(), world.getSizeY()
grid = {}
def set_grid(x, y, val):
if x not in grid:
grid[x] = {}
grid[x][y] = val
def kara_scan():
for y in xrange(h):
for x in xrange(w):
set_grid(x, y, kara.onLeaf())
kara.move()
kara.turnRight()
kara.move()
kara.turnLeft()
def kara_put():
for y in xrange(h):
for x in xrange(w):
if grid[x][y]:
if not kara.onLeaf():
kara.putLeaf()
elif kara.onLeaf():
kara.removeLeaf()
kara.move()
kara.turnRight()
kara.move()
kara.turnLeft()
def scan():
for x in xrange(w):
for y in xrange(h):
set_grid(x, y, world.isLeaf(x, y))
def put():
for x in grid:
for y in grid[x]:
world.setLeaf(x, y, grid[x][y])
def get_neighbours(grid, x, y):
neighbours = 0
#if 0 < x < w - 1 and 0 < y < h - 1:
for x_add in xrange(-1, 2):
for y_add in xrange(-1, 2):
if x_add == 0 and y_add == 0:
continue
new_x = x + x_add
if new_x < 0:
new_x = w - new_x - 2
if new_x >= w:
new_x = new_x - w
new_y = y + y_add
if new_y < 0:
new_y = h - new_y - 2
if new_y >= h:
new_y = new_y - h
if grid[new_x][new_y]:
neighbours += 1
return neighbours
def grid_copy(grid):
copied_grid = {}
for x in grid:
copied_grid[x] = {}
for y in grid[x]:
copied_grid[x][y] = grid[x][y]
return copied_grid
def process():
changed = False
old_grid = grid_copy(grid)
for x in old_grid:
for y in old_grid[x]:
neighbours = get_neighbours(old_grid, x, y)
if old_grid[x][y]:
if neighbours != 2 and neighbours != 3:
grid[x][y] = False
changed = True
elif neighbours == 3:
grid[x][y] = True
changed = True
return changed
def main():
scan()
run = True
while run:
run = process()
put()
tools.checkState()
def kara_main():
kara_scan()
has_fields = True
while has_fields:
has_fields = process()
kara_put()
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment