# Kirby Urner, 4D Studios, Portland, Oregon  July 27, 2006


# Random walk the HexaPent using a globalmatrix from OFF file read in gm2.


# Serves as a basis for other such studies, e.g. games with cellular automata

# ala Wolfram, Conway et al


# See:  http://www.4dsolutions.net/ocn/hexapent.html


from visual import *
import gm2
from random import randint
import time

globalmatrix, theverts, thefaces, theedges = gm2.getneighbors('globalmatrix.off')

edgehandles = {}

scene2 = display(title='Wandering in a HexaPent', width=1200, height=800)

for e in theedges:
    v1,v2 = [vector(*i) for i in (theverts[e[0]], theverts[e[1]]) ]
    theaxis = v2-v1
    edgehandles[e] = cylinder(pos=v1, axis=theaxis, radius=0.004, color=color.white)


class Cell (object):

    thinradius = 0.004
    fatradius = 0.008
    muted = color.green
    highlight = color.red
    
    def __init__(self, address):
	self.address = address
	self.radius=0.002
	self.neighbors = globalmatrix[self.address]
	if len(self.neighbors)==6:
  	    self.type = 'hexagon'
	else:
	    self.type = 'pentagon'
	self.edges = self._getedges()
	self.setcolor(Cell.highlight, Cell.fatradius)

    def _getedges(self):
        pairs = zip(self.address, list(self.address[1:]) + [self.address[0]])
        theedges = []
        for p in pairs:
            theedges.append(tuple(sorted(p)))
        return theedges
        
    def next(self):
        if self.type == 'hexagon':
            nxt = randint(0,5)
        else:
            nxt = randint(0,4)
        self.setcolor(Cell.muted, Cell.thinradius)
        return Cell(self.neighbors[nxt])
    
    def setcolor(self, thecolor, theradius):
        for e in self.edges:
            edge = edgehandles[e]
            edge.radius = theradius
            edge.color = thecolor

    def __repr__(self):
	return "Cell %s (%s)" % (self.address, self.type)
    

def main(howmany):
    thecell = Cell(globalmatrix.keys()[0])
    cycles = 0
    while cycles < howmany:
        thecell = thecell.next()
        time.sleep(0.1)
        cycles += 1
        
main(500)
# code highlighted using py2html.py version 0.8