Skip to content

Instantly share code, notes, and snippets.

Last active Aug 29, 2015
What would you like to do?
#!/usr/bin/env python
from copy import deepcopy
from random import shuffle
X = 10
Y = 12
grid = [[None for i in range(X)] for j in range(Y)]
indices = [(i,j) for j in range(Y) for i in range(X)]
# patterns will be a dict of dict of lists, such that:
# patterns[c1][c2] = [(dx, dy), ...] where (dx, dy) are the offsets
# from a tile of color c2 to a tile of color c1
patterns = {}
for i,j in indices:
c = 0
while True:
c += 1
# check if we're the same color of adjacent tiles
print 'on tile ', i, j, ' trying ', c
if j>0:
if i>0:
if grid[j-1][i-1] == c:
print 'matches above left'
if i+1<X:
if grid[j-1][i+1] == c:
print 'matches above right'
if grid[j-1][i] == c:
print 'matches above'
if i>0:
if grid[j][i-1] == c:
print 'matches left'
if i+1<X:
if grid[j][i+1] == c:
print 'matches right'
if j+1<Y:
if i>0:
if grid[j+1][i-1] == c:
print 'matches below left'
if i+1<X:
if grid[j+1][i+1] == c:
print 'matches below right'
if grid[j+1][i] == c:
print 'matches below'
# now check the offsets. the test algorithm is destructive, so
# copy the dict
newpatterns = deepcopy(patterns)
flag = False
for ii,jj in [(ii,jj)
for jj in range(Y)
for ii in range(X)]:
# skip testing ourself
if i == ii and j == jj: continue
dx = ii-i
dy = jj-j
testcolor = grid[jj][ii]
# skip if there's no one there
if not testcolor: continue
matches = newpatterns.setdefault(c, {}).setdefault(testcolor, [])
if (dx, dy) in matches:
print 'matches %d at (%d, %d)' % (testcolor, dx, dy)
flag = True
{}).setdefault(c, []).append((-dx,-dy))
# can't tell if we broke the loop or fell off the end. I know
# flags are unpythonic but this was a quick hack. if the flag was
# never set, we didn't conflict with any existing patterns, so
# overwrite the old dict with the ones we've testing by the append
# statement above
if not flag:
patterns = newpatterns
print 'setting (%d, %d) to %d' % (i, j, c)
grid[j][i] = c
for line in grid:
print ' '.join(['%02d' % tile for tile in line])
print 'total used: ', max([max(row) for row in grid])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment