Beispiel #1
0
def main():

    g.setstep(0)
    g.setalgo('QuickLife')

    velocity = g.getstring('Please specify velocity', '(2,1)c/6')
    a, b, p = parse_velocity(velocity)
    params = partial_derivatives(a, b, p)

    dvdx = params['dvdx']
    dudx = params['dudx']
    dvdy = params['dvdy']
    dudy = params['dudy']
    dvdt = params['dvdt']
    dudt = params['dudt']

    cells = []

    for t in xrange(p):

        things = g.getcells(g.getrect())
        things = zip(things[::2], things[1::2])
        cells += [(dudx * x + dudy * y + dudt * t,
                   dvdx * x + dvdy * y + dvdt * t) for (x, y) in things]
        g.step()

    g.setlayer(g.addlayer())
    g.putcells([x for y in cells for x in y])
Beispiel #2
0
def check_for_shared_rule(rulename):
    # rulename has at least one hyphen so get all chars before the last hyphen
    prefix = rulename.rsplit('-', 1)[0]

    # replace any illegal filename chars with underscores
    filename = prefix.replace("/", "_").replace("\\", "_") + "-shared.rule"

    rulepath = g.getdir("rules") + filename
    if not os.path.isfile(rulepath):
        rulepath = g.getdir("app") + "Rules/" + filename
        if not os.path.isfile(rulepath):
            # there is no prefix-shared.rule file
            return ""

    # ask user if they would prefer to edit icons in shared file
    sharedname = prefix + "-shared"
    try:
        answer = g.getstring(
            "There are no icons in " + rulename + ".rule.\n" +
            "Would you prefer to edit the icons in " + sharedname + ".rule?",
            "Yes", "Edit icons in shared rule?")
    except:
        # user hit Cancel (which would normally abort script)
        return ""
    if len(answer) == 0 or (answer[0] != "Y" and answer[0] != "y"):
        return ""

    return sharedname  # user said Yes
Beispiel #3
0
def check_for_shared_rule(rulename):
    # rulename has at least one hyphen so get all chars before the last hyphen
    prefix = rulename.rsplit('-',1)[0]
    
    # replace any illegal filename chars with underscores
    filename = prefix.replace("/","_").replace("\\","_") + "-shared.rule"
    
    rulepath = g.getdir("rules") + filename
    if not os.path.isfile(rulepath):
        rulepath = g.getdir("app") + "Rules/" + filename
        if not os.path.isfile(rulepath):
            # there is no prefix-shared.rule file
            return ""
    
    # ask user if they would prefer to edit icons in shared file
    sharedname = prefix + "-shared"
    try:
        answer = g.getstring("There are no icons in " + rulename + ".rule.\n" +
                             "Would you prefer to edit the icons in " + sharedname + ".rule?",
                             "Yes", "Edit icons in shared rule?")
    except:
        # user hit Cancel (which would normally abort script)
        return ""
    if len(answer) == 0 or (answer[0] != "Y" and answer[0] != "y"):
        return ""
    
    return sharedname   # user said Yes
 def getuserinputint(self, text, default):
     """
     Gets user input from a popup window in Golly
     :param text: the text to be displayed
     :param default: the default value to show up in the entry field
     :return: the value that was inputted by the user
     """
     temp = int(g.getstring(text, default))
     return temp
Beispiel #5
0
def golly_lhistory():

    ngens = int(g.getstring('How many generations to run the pattern?', '1'))

    d = threes_and_fours(0)

    g.setstep(0)
    for i in range(ngens):
        g.step()
        d.update(threes_and_fours(i + 1))

    exes = [k[0] for k in d]
    whys = [k[1] for k in d]
    zeds = [k[2] for k in d]

    minx = min(exes)
    maxx = max(exes)
    miny = min(whys)
    maxy = max(whys)

    width = (maxx - minx) + 10
    height = maxy - miny

    g.addlayer()
    g.setrule('Grills')

    for (k, v) in d.iteritems():

        x = (k[0] - minx) + (k[2] * width)
        y = k[1] - miny
        c = {3: LIVE_VARIABLE_STATE, 4: DEAD_VARIABLE_STATE}[v]
        g.setcell(x, y, c)

    for i in range(1, max(zeds) + 1):
        for j in range(height + 1):
            g.setcell(i * width - 5, j, VERTICAL_LINE_STATE)

    for i in range(max(zeds) + 1):
        g.setcell(i * width + 3, -3, ORIGIN_STATE)
        g.setcell(i * width + 3, -4, ZEROTH_GENERATION_STATE + i)
Beispiel #6
0
def main():

    g.setstep(0)
    g.setalgo('QuickLife')

    velocity = g.getstring('Please specify velocity', '(2,1)c/6')
    a, b, p = parse_velocity(velocity)
    params = partial_derivatives(a, b, p)

    dvdy = params['dvdy']
    dudy = params['dudy']
    dvdt = params['dvdt']

    cells = g.getcells(g.getrect())
    cells = zip(cells[::2], cells[1::2])
    gcells = []

    for (u, v) in cells:
        for t in xrange(p):
            xp = dvdy * u - dudy * v - a * t
            yq = v - t * dvdt
            if (xp % p != 0):
                continue
            if (yq % dvdy != 0):
                continue
            x = xp // p
            y = yq // dvdy
            gcells.append((t, x, y))

    spacing = max([x for (_, x, _) in gcells]) - min([x for (_, x, _) in gcells])
    spacing += 10

    gcells = [(x + spacing * t, y) for (t, x, y) in gcells]

    g.setlayer(g.addlayer())
    g.putcells([x for y in gcells for x in y])
    g.fit()
Beispiel #7
0
# use same file name as in goto.pl
GotoINIFileName = g.getdir("data") + "goto.ini"
previousgen = ""
try:
   f = open(GotoINIFileName, 'r')
   previousgen = f.readline()
   f.close()
   if not validint(previousgen):
      previousgen = ""
except:
   # should only happen 1st time (GotoINIFileName doesn't exist)
   pass

gen = g.getstring("Enter the desired generation number as an\n" +
                  "expression, prepend -/+ for relative\n" +
                  "move back/forwards, prepend f to use faster\n"
                  "powers-of-2 steps:",
                  previousgen, "Go to generation")
# Evaluate the expression. This leaves leading "f" and/or "+/-"
# intact.
gen = expr_3(gen)

# Find out if they want to get there quickly
# %%% TODO: Use re instead of string.find and string.replace (which are
#           deprecated in later versions of Python)
fastmode = 0
if(gen.find("f") == 0):
  gen = gen.replace("f","")
  fastmode = 1

if len(gen) == 0:
Beispiel #8
0
    return abs(a - b)


def popcount(sel=0):
    dict_lc = {'BDRainbow': [2, 4], 'BGRainbowR2': [2, 4]}
    live_cells = dict_lc[g.getrule().split(':')[0]]
    if not sel:
        clist = g.getcells(g.getrect())
    else:
        clist = g.getcells(g.getselrect())
    return sum(clist[2::3].count(x) for x in live_cells)


dict_lc = {'BDRainbow': [2, 4], 'BGRainbowR2': [2, 4]}

input = (g.getstring('How many steps?/similarity distance?', '2000/1'))
numsteps = int(input.split('/')[0])
dmax = int(input.split('/')[1])

poplist = []
hashlist = [int(g.hash(g.getrect()))]
popold = int(g.getpop())
dead = 0

if g.getrule().split(':')[0] in dict_lc:
    popfunc = lambda: popcount()

else:
    popfunc = lambda: g.getpop()

for i in range(numsteps):
            is_rule_acceptable = False

    if is_rule_acceptable:
        break

spec = golly.getstring(
'''This script will create an AbsoluteTurmite CA for a given specification.

Enter a specification string: a curly-bracketed table of n_states rows
and n_colors columns, where each entry is a triple of integers.
The elements of each triple are:
a: the new color of the square
b: the direction(s) for the turmite to move: 'NESW'
c: the new internal state of the turmite

Example:
{{{1,'E',1},{1,'W',1}},{{1,'W',0},{1,'',0}}}
(example pattern #1)
Has 2 states and 2 colors. The triple {1,'W',0} says:
1. set the color of the square to 1
2. move West
3. adopt state 0 and move forward one square
This is a 1D busy beaver

Enter specification string:
(default is a random example)''', example_spec, 'Enter Absolute Turmite specification:')

# convert the specification string into action_table[state][color]
# (convert Mathematica code to Python and run eval)
action_table = eval(spec.replace('{','[').replace('}',']'))
n_states = len(action_table)
			
			mdx, mdy = putcells(results[i][0], (dx, dy))
			
			AddText(fname, dx + int(mdx / 2), dy - 10)
			
			dx += mdx + 60
				
		dy += 60 + mdy
		dx = 0
	
	AddText(path, 0, -100)

#Start Here 
CreateRule()
g.new("")
g.setrule("LifeBellman")

file_path = os.path.join(g.getdir("data"), "LastBellmanOutputDir.txt")
dir = ""

if os.path.exists(file_path):
	with open (file_path, "r") as f:
		dir=f.readline()

dir = g.getstring("Enter output directory", dir) 

with open(file_path, "w") as text_file:
    text_file.write(dir)

Place(dir)
Beispiel #11
0
   return result


CR = chr(13)
LF = chr(10)
pastepattern = "none"

yourclipboard = golly.getclipstr()
yourclipboard = yourclipboard.replace(CR+LF,LF)
yourclipboard = yourclipboard.replace(CR,LF)

if yourclipboard.startswith("#r "):
  rulestring = yourclipboard.split(" ")[1].split("\n")[0]
  pastepattern = yourclipboard.split("#r "+rulestring)[1]
else:
  rulestring = golly.getstring(dialog_box_message, "B2a/S12")


# The following code cleans up the rulestring
# so that it makes a valid and somewhat readable file name - eg "B2-a_S12.table"

rulestring = rulestring.replace(" ", "")
rulestring = rulestring.lower()
rulestring = rulestring.replace("b", "B")
rulestring = rulestring.replace("s", "S")

# The variable named rulestring will be parsed. 
# The variable named rule_name will be the name of the new file.
# Valid rules contain a slash character but filenames can not include slashes.

rule_name = rulestring.replace("/", "_") 
Beispiel #12
0
    # so was the rule acceptable, in the end?
    if is_rule_acceptable:
        break

spec = golly.getstring(
    '''This script will create a Turmite CA for a given specification.

Enter a number (1-59) for an example Turmite from Ed Pegg Jr.'s (extended) library.
(see http://demonstrations.wolfram.com/Turmites/ or the code of this script)

Otherwise enter a specification string: a curly-bracketed table of n_states rows
and n_colors columns, where each entry is a triple of integers. 
The elements of each triple are:
a: the new color of the square
b: the direction(s) for the Turmite to turn (1=noturn, 2=right, 4=u-turn, 8=left)
c: the new internal state of the Turmite

Example:
{{{1, 2, 0}, {0, 8, 0}}}
(example pattern #1)
Has 1 state and 2 colors. The triple {1,2,0} says: 
1. set the color of the square to 1
2. turn right (2)
3. adopt state 0 (no change) and move forward one square
This is Langton's Ant.

Enter integer or string:
(default is a random example)''', example_spec, 'Enter Turmite specification:')

if spec.isdigit():
    spec = EdPeggJrTurmiteLibrary[
        int(spec) - 1]  # (his demonstration project UI is 1-based)
Beispiel #13
0

def ConvertToList(sequence):

    result = []

    for item in sequence:
        try:
            i = len(item)
        except:
            result.append(item)

    return result


userSpeed = g.getstring("Please enter step/period", "1/8")

if userSpeed.split("/")[0] == 'c':
    userSpeed = userSpeed.replace("c", "1")
else:
    userSpeed = userSpeed.replace("c", "")

iniStep = int(userSpeed.split("/")[0])
iniPeriod = int(userSpeed.split("/")[1])

speed = float(iniStep) / iniPeriod

if speed >= 0.25:
    g.exit("This speed should be strictly less than c/4")

if (iniPeriod + 2 * iniStep) % 8 == 0:
Beispiel #14
0
if g.empty(): g.exit("There is no pattern.")

# check that a layer is available for population plot
layername = "population plot"
poplayer = -1
for i in xrange(g.numlayers()):
    if g.getname(i) == layername:
        poplayer = i
        break
if poplayer == -1 and g.numlayers() == g.maxlayers():
    g.exit("You need to delete a layer.")

# prompt user for number of steps
numsteps = xlen
s = g.getstring("Enter the number of steps:",
                str(numsteps), "Population plotter")
if len(s) > 0: numsteps = int(s)
if numsteps <= 0: g.exit()

# generate pattern for given number of steps
poplist = [ int(g.getpop()) ]
genlist = [ int(g.getgen()) ]
oldsecs = time()
for i in xrange(numsteps):
    g.step()
    poplist.append( int(g.getpop()) )
    genlist.append( int(g.getgen()) )
    newsecs = time()
    if newsecs - oldsecs >= 1.0:     # show pattern every second
        oldsecs = newsecs
        fit_if_not_visible()
Beispiel #15
0
import golly as g 

s = ":-4,-12,-6,-2,-8,-6,-12,-10,-12,-16,-6,-10,-8" 
s =g.getstring("type recipe")

v = s.split(':')
v1 = v[0].split(',')
v2 = v[1].split(',')

g.new("")
glider_cells = g.parse("3o$o$bo!")
block_cells = g.parse("2o$2o!", 0, 0)
#block_cells = g.parse("$3bo$3bo$3bo5$3o5$7b2o$7b2o8$4bo$4bo10bo$4bo9bobo$14b2o$3o3b3o2$4bo$4bo$4bo!", -20, -20)

def LeftMost(recipe):

	g.putcells(block_cells)
	
	idx = 1
	for r in recipe:
		#g.putcells(glider_cells, 80, 80 + r )
		g.putcells(glider_cells, 160 * idx, 160 * idx + int(r))
		idx += 1
		#g.step()
		
	rect = g.getrect()
	
	return rect[0]
	
LeftMost(v2)
Beispiel #16
0
import golly as g
from glife import validint 

# Python versions < 2.4 don't have "set" built-in
try:
   set
except NameError:
   from sets import Set as set

def chunks(l,w):
   for i in xrange(0, len(l), 2):
      yield l[i]+(w*l[i+1])

if g.empty(): g.exit("The pattern is empty.")
s = g.getstring("Enter the period:","", "Heat calculator")

if not validint(s): 
  g.exit('Bad number: %s' % s)
numsteps = int(s)
if numsteps < 2:
  g.exit('Period must be at least 2.')

g.show('Processing...')

heat = 0;
maxheat = 0;
minheat = 9*g.getpop();

for i in range(0, numsteps):
  bb = g.getrect()
Beispiel #17
0
    # so was the rule acceptable, in the end?
    if is_rule_acceptable:
        break

spec = golly.getstring(
'''This script will create a Turmite CA for a given specification.

Enter a number (1-59) for an example Turmite from Ed Pegg Jr.'s (extended) library.
(see http://demonstrations.wolfram.com/Turmites/ or the code of this script)

Otherwise enter a specification string: a curly-bracketed table of n_states rows
and n_colors columns, where each entry is a triple of integers.
The elements of each triple are:
a: the new color of the square
b: the direction(s) for the Turmite to turn (1=noturn, 2=right, 4=u-turn, 8=left)
c: the new internal state of the Turmite

Example:
{{{1, 2, 0}, {0, 8, 0}}}
(example pattern #1)
Has 1 state and 2 colors. The triple {1,2,0} says:
1. set the color of the square to 1
2. turn right (2)
3. adopt state 0 (no change) and move forward one square
This is Langton's Ant.

Enter integer or string:
(default is a random example)''', example_spec, 'Enter Turmite specification:')

if spec.isdigit():
    spec = EdPeggJrTurmiteLibrary[int(spec)-1] # (his demonstration project UI is 1-based)
        if len(lista) % 2 == 0:
            lista.append(0)

        yield lista

#calculate density of cells
def calculate_density():
    bbox = gl.rect(g.getrect())
    if bbox.empty:
        d = 0
    else:
        d = float(g.getpop()) / float(bbox.wd*bbox.ht)
    return d


grid_size = int(g.getstring("Tamanho do tabuleiro:", "3"))
max_iter = grid_size * 500

number_of_tests = 2 ** (grid_size**2)
name = "%dx%d" % (grid_size, grid_size)
out_filename = "output/results_%s.csv" % (name)
patterns_filename = "patterns/patterns_%s.csv" % (name)
rlepatterns_filename = "patterns/patterns_" + name + "-%d.rle"

g.autoupdate(False)
f = open(out_filename, 'w')
f.write("id,number_of_iterations,initial_pop,final_pop,initial_density,final_density,end_status,elapsed_time\n")
#f2 = open(patterns_filename, 'w')
#f2.write("id, initial_cell_list\n")

trial_number = 1
Beispiel #19
0
            if action_table[state][color][0]==color and action_table[state][color][1]==4 and action_table[state][color][2]==state:
                is_rule_acceptable = False
    # so was the rule acceptable, in the end?
    if is_rule_acceptable:
        break

spec = golly.getstring(
'''This script will create a TriTurmite CA for a given specification.

Enter a specification string: a curly-bracketed table of n_states rows
and n_colors columns, where each entry is a triple of integers.
The elements of each triple are:
a: the new color of the square
b: the direction(s) for the Turmite to turn (1=Left, 2=Right, 4=U-turn)
c: the new internal state of the Turmite

Example:
{{{1, 2, 0}, {0, 1, 0}}}
Has 1 state and 2 colors. The triple {1,2,0} says:
1. set the color of the square to 1
2. turn right (2)
3. adopt state 0 (no change) and move forward one square
This is the equivalent of Langton's Ant.

Enter string:
''', example_spec, 'Enter TriTurmite specification:')

'''Some interesting rule found with this script:
{{{2,4,0},{2,4,0},{1,2,1}},{{1,2,1},{2,1,0},{1,4,1}}} - lightning cloud
{{{1,1,1},{1,2,0},{2,1,1}},{{2,2,1},{2,2,1},{1,4,0}}} - makes a highway (seems to be rarer in tri grids compared to square grids?)
{{{2,2,1},{1,2,0},{1,1,1}},{{1,2,0},{2,1,0},{1,4,1}}} - data pyramid
{{{2,1,0},{1,4,1},{1,1,0}},{{2,4,0},{2,2,1},{1,1,1}}} - a filled version of the tri-grid Langton's ant
Beispiel #20
0
		else:
			sel=g.getselrect()
			pbox=g.getselrect()
			clist=g.getcells(pbox)
			
			
			for i in range(int(len(clist)/3)):
				clist[3*i]   = clist[3*i]-sel[0]
				clist[3*i+1] = clist[3*i+1]-sel[1]
			clist.insert(0,sel[2])
			clist.insert(1,sel[3])
			tile.append(clist)
			pboxlist.append(pbox)
	return tile

input=g.getstring('maxnum/step/boxwidth','100/1/40')
maxnum=int(input.split('/')[0])
step=int(input.split('/')[1])
boxwidth=int(input.split('/')[2])

input=g.getstring('what cell state to screen for/ \n \
			treat selection as torus?/ \n \
			how many repeating units?','%s/%s/%s'%(g.getoption("drawingstate"),'1','2'))
state=int(input.split('/')[0])
torus=int(input.split('/')[1])
n=int(input.split('/')[2])

# box=makebox(boxwidth)	
box=makebox(boxwidth)
pboxlist=[]
tile=loadtopo(maxnum,step,boxwidth)
def main ():
  g.update ()
  g.check (False)

  path = g.getstring ("Output directory:")
  files = glob.glob (os.path.join (path, "*.out"))

  mingls = g.getstring ("Min number of gliders at accept:")
  if mingls == "":
    mingl = 0
    minpop = 0
    maxpop = 1024
  else:
    mingl = int (mingls)
    minpops = g.getstring ("Min population except catalyzers:")
    if minpops == "":
      minpop = 0
      maxpop = 1024
    else:
      minpop = int (minpops)
      maxpop = int (g.getstring ("Max population except catalyzers:"))

  if g.getname () != "catbellman_temp":
    g.addlayer ()

  hashdir = {}
  catlist = []
  catix = 0

  g.new ("catbellman_temp")
  g.setrule ("LifeBellman")

  for fix, filename in enumerate (files):
    patt = g.getrect ()
    if patt != []:
      g.select (patt)
      g.clear (0)
  
    g.setgen ("0")
	
    with open(filename, 'r') as f:
      filetext = f.read ()
      if fix % 16 == 0:
        g.show ("Analysing " + str (fix) + "/" + str (len (files)))
		
      (gogen, glcnt) = convbellman (filetext, 0, 0)
      if gogen == -1:
	    gogen = 128
	  
      (use, hash) = analyse (gogen, glcnt, minpop, maxpop, mingl)

      if use:
        if not hash in hashdir:
          catlist.append ([])
          hashdir [hash] = catix
          catix += 1

        cat = hashdir [hash]
        catlist [cat].append (filetext)

  g.new ("catbellman_temp")
  g.setrule ("LifeBellman")

  fix = 0
  y = 0
  for cat in catlist:
    x = 96 * (len (cat) - 1)
    for filetext in cat:
      convbellman (filetext, x, y)
      x -= 96
      fix += 1
      if fix % 32 == 0:
        g.show ("Rendering " + str (fix) + "/" + str (len (files)))
        g.fit ()
        g.check (True)
        g.update ()
        g.check (False)

    y += 96

  g.show ("Done")
  g.fit ()
  g.setstep (-1)
  g.check (True)
Beispiel #22
0
        result = [[]]
        for pool in pools:
            result = [x + [y] for x in result for y in pool]
        for prod in result:
            yield tuple(prod)


spec = golly.getstring(
    """This script will write and select the rule "Fredkin-mod-n", for a given N.

This rule is the Winograd extension of the Fredkin Replicator rule (the parity rule):
  c,{s} -> sum(s)%N    (where N=2 for the original parity rule)

If N is prime, this will result in any pattern being replicated at N^m timesteps
(if the pattern is small enough that it doesn't overlap its copies).

Specify the neighborhood (N = von Neumann, M = Moore, T = triangular von Neumann,
H = hexagonal, TM = triangular Moore) and the value of N (2-255). e.g. H2, N7

(Larger values of N can take a long time.)
""",
    "N3",
    "Enter specification:",
)

# work out what the string meant
nhood = ""
nhoods = {"N": "vonNeumann", "TM": "triangularMoore", "M": "Moore", "T": "triangularVonNeumann", "H": "hexagonal"}
for nh in nhoods.keys():
    if nh in spec:
        nhood = nhoods[nh]
Beispiel #23
0
# We owe a lot to MCell's implementation of the Margolus neighbourhood. Thanks Mirek!
#
# Tim Hutton <*****@*****.**>

import golly as g

# ask the user for the MCell string to convert (comma-separated works too)
s = g.getstring("Enter a specification string.\n\nThis can either be an MCell format Margolus\nstring or just a comma-separated list of the 16 case indices.\n\nSee: http://psoup.math.wisc.edu/mcell/rullex_marg.html\n","MS,D0;8;4;3;2;5;9;7;1;6;10;11;12;13;14;15","Enter Margolus specification") # defaults to BBM

# pull out the 16 numeric tokens that tell us what each partition becomes
becomes = map(int,s.replace('M',' ').replace('S',' ').replace(',',' ').replace('D',' ').replace(';',' ').split())

# we should be able to write straight into the user's rules folder,
# so we can call setrule immediately
folder = g.getdir('rules')

# construct a rule_name from next case indices
rule_name = 'Margolus-' + '-'.join(map(str,becomes))
# ask the user to confirm this name or suggest a more readable one (e.g. "BBM")
rule_name = g.getstring("Enter a name for the rule:",rule_name,"Enter rule name")

# todo: detect slashes and tildes, tell user that can't change dir like that

# open the rule table file for writing
f = open(folder + rule_name + '.table','w')

# write the initial descriptors and some variables
f.write('# Emulation of Margolus neighbourhood for MCell string:\n# %s\n\n'%s)
f.write('# (see: http://psoup.math.wisc.edu/mcell/rullex_marg.html )\n')
f.write('#\n')
f.write('# Rule table produced by convert-MCell-string.py, which can\n')
Beispiel #24
0
# use same file name as in goto.pl
GotoINIFileName = g.getdir("data") + "goto.ini"
previousgen = ""
try:
    f = open(GotoINIFileName, 'r')
    previousgen = f.readline()
    f.close()
    if not validint(previousgen):
        previousgen = ""
except:
    # should only happen 1st time (GotoINIFileName doesn't exist)
    pass

gen = g.getstring(
    "Enter the desired generation number,\n" +
    "or -n/+n to go back/forwards by n:", previousgen, "Go to generation")
if len(gen) == 0:
    g.exit()
elif gen == "+" or gen == "-":
    # clear the default
    savegen(GotoINIFileName, "")
elif not validint(gen):
    g.exit('Sorry, but "' + gen + '" is not a valid integer.')
else:
    # best to save given gen now in case user aborts script
    savegen(GotoINIFileName, gen)
    oldstep = g.getstep()
    goto(gen.replace(",", ""))
    g.setstep(oldstep)
Beispiel #25
0
if g.empty(): g.exit("There is no pattern.")

# check that a layer is available for population plot
layername = "population plot"
poplayer = -1
for i in xrange(g.numlayers()):
    if g.getname(i) == layername:
        poplayer = i
        break
if poplayer == -1 and g.numlayers() == g.maxlayers():
    g.exit("You need to delete a layer.")

# prompt user for number of steps
numsteps = 500
s = g.getstring("Enter the number of steps:", str(numsteps),
                "Population plotter")
if len(s) > 0: numsteps = int(s)
if numsteps <= 0: g.exit()


def boxdm(orientation):
    if not g.empty():
        shrink()
        return g.getselrect()[orientation]
    else:
        return 0


def area():
    if not g.empty():
        shrink()
Beispiel #26
0
    "2o$bo$bobo$2b2o!",
    "3bo$b3o$o$2o!",
    "2o$obo$2bo$2b2o!",
    "2b2o$3bo$3o$o!",  # one chirality of eater
    "2o$o$b3o$3bo!",
    "2b2o$bobo$bo$2o!",
    "o$3o$3bo$2b2o!",
    "2b2o$2bo$obo$2o!",  # the other chirality of eater
    "2o$obo$bobo$2bo!",
    "2b2o$bobo$obo$bo!",
    "bo$obo$bobo$2b2o!",
    "2bo$bobo$obo$2o!",  # longboats
    "bo$3o$bo!"
]  # and last but not least, the weird case -- blinkers

MAXOBJ = int(g.getstring("Enter max number of objects to place: ", "3"))
if MAXOBJ < 1: g.exit("Invalid MAXOBJ value.")

ans = g.getstring("Enter X and Y bounding box sizes, separated by a space:",
                  "8 6")
if ans.find(" ") == -1: g.exit("Invalid bounding box: '" + ans + "'.")
answers = ans.split(" ")
xsize, ysize = int(answers[0]), int(answers[1])
if xsize < 2 or ysize < 2: g.exit("Invalid numbers for bounding box size.")

outfname = "C:\users\{USERNAME}\Desktop\const-output.txt"


def getinp(s):
    ###########################
    temp = g.getcell(x, y)
p_init = d_patterns_rom_body["init"]
delta_x, delta_y = d_patterns_rom_body["delta"]
for i_addr, (_, binstring) in enumerate(l_binstring):
    for i_bit, bit in enumerate(binstring):
        d_patterns_rom_body[int(bit)].put(p_init[0] + delta_x * i_bit,
                                          p_init[1] + i_addr * delta_y,
                                          (1, 0, 0, 1, "copy"))

g.show("Done.")

N_BITS_ROM = 13
N_BITS_RAM = 12

ram_length_in = g.getstring("""ROM size: {}
Input maximum RAM address (RAM size - 1) (3 <= n <= (1 << {})):""".format(
    len(parsed), N_BITS_RAM))

ram_negative_in = g.getstring("Input negative RAM buffer size:")

ROM_LENGTH = len(parsed)
RAM_NEGATIVE_BUFFER_SIZE = int(ram_negative_in)
RAM_POSITIVE_BUFFER_SIZE = int(ram_length_in) + 1
RAM_LENGTH = RAM_NEGATIVE_BUFFER_SIZE + RAM_POSITIVE_BUFFER_SIZE

d_patterns_rom_params = {"init": (183, 40)}

# d_patterns_ram_xoffset = 96+8*2
d_patterns_ram_xoffset = 96 + 8 * 2 - 8 * 7

d_patterns_rom_demultiplexer = {
Beispiel #28
0
# OpenSCAD generator for Golly
# [email protected]

import golly

rect = golly.getrect()
if len(rect) == 0:
	golly.exit("Please create a pattern.")

count = int(golly.getstring("Number of generations to evolve:","8"))
ofile = open(golly.getstring("OpenSCAD output file:","golly.scad"),"w")

preamble = """
module skew_cube(a,b) {
	multmatrix(m = [
		[1, 0, a, 0],
		[0, 1, b, 0],
		[0, 0, 1, 0]
	]) cube(size=1.00001);
}

module span_cube(x1,y1,x2,y2,z) {
	translate(v=[x1,y1,z])
	skew_cube(x2-x1,y2-y1);
}

"""


def cell_set(cell_list):
	cells = set()
# encoding: 
# (0-n_colors: empty square)
def encode(c,s,d):
    # turmite on color c in state s facing direction d
    return n_colors + n_dirs*(n_states*c+s) + d

prefix = 'LangtonsAnt' 
# (We choose a different name to the inbuilt Langtons-Ant rule to avoid
#  name collision between the rules we output and the existing icons.)

spec = golly.getstring(
'''This script will create a Langton's Ant CA for a given string of actions.

The string specifies which way to turn when standing on a square of each state.

Examples: RL (Langton's Ant), RLR (Chaos), LLRR (Cardioid), LRRL (structure)

Permitted moves: 'L':Left, 'R':Right, 'U':U-turn, 'N':No turn

Enter string:''', 'RL', 'Enter string:')

n_colors = len(spec)

d={'R':'2','L':'8','U':'4','N':'1'} # 1=noturn, 2=right, 4=u-turn, 8=left
turmite_spec = "{{"+','.join(['{'+str((i+1)%n_colors)+','+d[spec[i]]+',0}' for i in range(n_colors)])+"}}"
rule_name = prefix+'_'+spec
action_table = eval(turmite_spec.replace('}',']').replace('{','['))
n_states = len(action_table)
n_dirs=4
# (N.B. The terminology 'state' here refers to the internal state of the finite
#       state machine that each Turmite is using, not the contents of each Golly
            is_rule_acceptable = False
            break # (just an optimisation)
    # so was the rule acceptable, in the end?
    if is_rule_acceptable:
        break

spec = golly.getstring(
'''This script will create an Absolute-movement HexTurmite CA for a given specification.

Enter a specification string: a curly-bracketed table of n_states rows
and n_colors columns, where each entry is a triple of integers.
The elements of each triple are:
a: the new color of the square
b: the direction(s) for the Turmite to move ('A', 'B', .. , 'F')
c: the new internal state of the Turmite

Example:
{{{1, 'A', 0}, {0, 'B', 0}}}
Has 1 state and 2 colors. The triple {1,'A',0} says:
1. set the color of the square to 1
2. move in direction 'A'
3. adopt state 0

Enter string:
''', example_spec, 'Enter AbsoluteHexTurmite specification:')

# convert the specification string into action_table[state][color]
# (convert Mathematica code to Python and run eval)
action_table = eval(spec.replace('}',']').replace('{','['))
n_states = len(action_table)
n_colors = len(action_table[0])
    [startWd, endWd] = getIndices(wd)
    [startHt, endHt] = getIndices(ht)
    #formatStr = 'Width: {0}   Height: {1}\nStart Pos: ({2},{3})\nEnd Pos:{4},{5}\np,q = {6} {7} ' 
    #golly.note(formatStr.format(wd,ht,startWd,startHt,endWd,endHt,p,q))

    # Only search the candidate matrix cells which can contain
    # the matrix we're searching for
    candidates = [(x,y) for x in range(startWd,endWd-cols+2) for y in range(startHt,endHt-rows+2)]
    for (iCol, iRow) in candidates:
        jCol = 0
        jRow = 0 
        while(golly.getcell(iCol + jCol,iRow + jRow) == searchPatt[jRow][jCol]):
            if (jCol == cols-1) and (jRow == rows-1):
                print '        Match = ({0},{1})'.format(iCol,iRow)
                matches.append((iCol,iRow))
                break
            jCol = jCol + 1
            if (jCol > cols - 1):
                jCol = 0
                jRow = jRow + 1
                if (jRow > rows - 1):
                    print '        Break = ({0},{1})'.format(iCol,iRow)
                    break ## End of search space, and no match found
    return [matches, candidates]

#golly.note('Vals = {0}  {1}'.format(golly.getcell(0,0),golly.getcell(-2,0)))
searchPattern = golly.getstring("Define a pattern to search for (enter as a Python list)", "[[1,0],[1,1],[0,0]]", "Enter A Pattern")
[results, candidates] = bruteForceSearch(eval(searchPattern))
golly.note('Total Matches: {0}\nTotal Candidate Cells:{1}\n{2}'.format(
        len(results), len(candidates), results))
site_step = 0

rect = g.getselrect()
if not rect:
    site_step = find_best_selection()
    rect = g.getselrect()
    if not rect:
        g.exit(
            "No selection. Could not locate a valid separation and offset automatically."
        )
    g.fitsel()
    g.update()

if site_step == 0:
    site_step = int(g.getstring("Enter step between construction sites"))
delay2 = int(
    g.getstring(
        "Enter delay for 2nd construction (only relevant for spaceships)",
        "0"))
offset = 100

paranoidcheck = int(
    g.getstring(
        "Enter number of ticks to check below binary search result (min=1)",
        "100"))
if paranoidcheck < 1:
    g.exit(
        "Invalid value for maximum ticks to double-check the binary search result."
    )
srect = g.getselrect()
{{{2,16,1},{2,16,0},{1,8,1}},{{1,32,1},{2,4,0},{1,2,0}}} - loose growth
{{{1,1,1},{2,32,1},{1,8,1}},{{2,8,0},{2,16,1},{1,1,0}}} - loose geode growth
"""

spec = golly.getstring(
    """This script will create a HexTurmite CA for a given specification.

Enter a specification string: a curly-bracketed table of n_states rows
and n_colors columns, where each entry is a triple of integers.
The elements of each triple are:
a: the new color of the square
b: the direction(s) for the Turmite to turn (1=Forward, 2=Left, 4=Right, 8=Back-left,
    16=Back-right, 32=U-turn)
c: the new internal state of the Turmite

Example:
{{{1, 4, 0}, {0, 2, 0}}}
Has 1 state and 2 colors. The triple {1,4,0} says:
1. set the color of the square to 1
2. turn right (4)
3. adopt state 0 and move forward one square
This is the equivalent of Langton's Ant.

Enter string:
""",
    example_spec,
    "Enter HexTurmite specification:",
)

# convert the specification string into action_table[state][color]
# (convert Mathematica code to Python and run eval)
action_table = eval(string.replace(string.replace(spec, "}", "]"), "{", "["))
Beispiel #34
0
# This script calculate and emulate a B0 composite from the current emulated rule. (Try B024/S0123 or B678/S1278)
# Author: Feng Geng([email protected]), Sep 2016.

import golly as g
from glife import *

rule = g.getrule()
rule = rule.split(':')[0]
rule = g.getstring('rule to alternate', rule)
ruleB = rule.split('/')[0][1:]
ruleS = rule.split('/')[1][1:]
S = ['S']
B = ['B']
for i in range(5):
    if str(i) in ruleB:
        S.append(str(4 - int(i)))
    if str(i) in ruleS:
        B.append(str(4 - int(i)))

B = ''.join(B)
S = ''.join(S)
rule = '/'.join([B, S])
rule = ''.join([rule, 'V'])
# g.note(rule)
g.setrule(rule)
Beispiel #35
0
from string import lower
import golly as g
import math

rules = ("JvN29", "Nobili32", "Hutton32")

rule = g.getrule ()
if rule not in rules:
    g.exit ("Invalid rule: " + rule + " (must be " + rules + ")")

rect = g.getselrect ()
if len (rect) == 0:
    g.exit ("There is no selection.")

answer = g.getstring("Enter axis to mirror on\n" +
                     "(valid axes are x and y, default is y):",
                     "y",
                     "Mirror selection")

if answer != "x" and answer != "y":
    g.exit ("Unknown mode: " + answer + " (must be x/y)")

cells = g.getcells (rect)

jvn_flip_x = ((10, 12), (14, 16), (18, 20), (22, 24))
jvn_flip_y = ((9, 11), (13, 15), (17, 19), (21, 23))

if answer == "x":
    flips = jvn_flip_x
else:
    flips = jvn_flip_y
Beispiel #36
0
import golly as g

s = ":-4,-12,-6,-2,-8,-6,-12,-10,-12,-16,-6,-10,-8"
s = g.getstring("type recipe")

v = s.split(':')
v1 = v[0].split(',')
v2 = v[1].split(',')

g.new("")
glider_cells = g.parse("3o$o$bo!")
block_cells = g.parse("2o$2o!", 0, 0)
#block_cells = g.parse("$3bo$3bo$3bo5$3o5$7b2o$7b2o8$4bo$4bo10bo$4bo9bobo$14b2o$3o3b3o2$4bo$4bo$4bo!", -20, -20)


def LeftMost(recipe):

    g.putcells(block_cells)

    idx = 1
    for r in recipe:
        #g.putcells(glider_cells, 80, 80 + r )
        g.putcells(glider_cells, 160 * idx, 160 * idx + int(r))
        idx += 1
        #g.step()

    rect = g.getrect()

    return rect[0]

Beispiel #37
0
		
		recipe[idx] = (x, y % modY, i)

def ConvertToList(sequence):
	
	result = []
	
	for item in sequence:
		try:
			i = len(item)
		except:
			result.append(item)
			
	return result

userSpeed = g.getstring("Please enter step/period", "1/8")

if userSpeed.split("/")[0] == 'c':
	userSpeed = userSpeed.replace("c", "1")
else:
	userSpeed = userSpeed.replace("c", "")
	
iniStep = int(userSpeed.split("/")[0]) 
iniPeriod = int(userSpeed.split("/")[1])

speed = float(iniStep) / iniPeriod

if speed >= 0.25:
	g.exit("This speed should be strictly less than c/4")

if (iniPeriod + 2 * iniStep) % 8 == 0:
Beispiel #38
0
# Output an adjacency matrix for current selection to clipborad in a "Mathematica" list fomart
# Use AdjacencyGraph[] in Mathematica for downstream processing.
# Author: Feng Geng([email protected]), May 2016.

import golly as g
from glife import *
import numpy as np
import hashlib

pt = g.getcells(g.getrect())
width = g.getstring('width of torus', '200')
rule = g.getrule()
nrule = rule.split(':')[0] + ':T{},512'.format(width)
g.note(nrule)
g.setrule(nrule)
Beispiel #39
0
## This script generate an ECA rule and emulate it on a torus of width 200.
## Written by Feng ([email protected]) Feb 2017.
import golly

ali = golly.getstring('TCA rulestring', golly.getrule().split(':')[0])


def alias2rnum(ali):
    rule = ['0'] * 18
    ali = ali.replace('/', '').lower().lstrip('b')
    (b, s) = ali.split('s')
    lst = list(str(int(i) + 9) for i in s)
    golly.note(str(lst))
    bs = list(b) + (lst)
    for i in bs:
        rule[int(i)] = '1'
    # golly.note(bs)
    # golly.note(''.join(rule[::-1]))
    rnum = int(''.join(rule[::-1]), 2)
    return (rnum)


# golly.setalgo("QuickLife")
# # golly.note(alias)
# golly.setrule(alias);
rnum = str(alias2rnum(ali))
golly.setclipstr(rnum)
golly.note(rnum)
Beispiel #40
0
import golly as g
import quiescentauton as q

soupfilepath = "/home/scorbie/Apps/ptbtest/random"
nsoups = int(g.getstring("How many soups?", "1000"))
soupsize = 10  # int(g.getstring('Soup size?', '10'))

if g.getrule() == "LifeHistory":
    g.setrule("B3/S23")
if g.numstates() > 2:
    g.exit("This script only works with two-state rules.")

soups = []
x, y, w, h = r = [0, 0, soupsize, soupsize]
cellchar = [".", "a"]
while len(soups) < nsoups:
    g.new("Generating Soups")
    g.select(r)
    g.randfill(40)
    g.run(250)
    # To avoid 'Empty Pattern!' messages in status bar.
    if int(g.getpop()) == 0:
        continue
    if not q.testquiescence(60):
        g.reset()
        soupstr = "!".join(
            "".join(cellchar[g.getcell(i, j)] for j in xrange(0, soupsize + 1)) for i in xrange(0, soupsize + 1)
        )
        soups.append(soupstr)
        g.show("Soup {}/{}".format(len(soups), nsoups))
with open(soupfilepath, "w") as soupfile:
Beispiel #41
0
# isotropic-rule.py
# Generate a rule table for an isotropic rule using Alan Hensel's
# isotropic, non-totalistic rule format for CA on the Moore neighbourhood

import golly as g
import isotropicRulegen as isorg

rulestring = g.getstring(
    "Enter rule string in Alan Hensel's isotropic rule notation", "B2-a/S12")

rg = isorg.RuleGenerator()

rg.setrule(rulestring)
rg.saveIsotropicRule()
g.setrule(rg.rulename)

g.show("Created rule in file: " + rg.rulename + ".rule")
Beispiel #42
0
# Inverse the pattern in the selection after each step.
# Author: Feng Geng([email protected]), SEP 2016.

import golly as g
from glife import *
import numpy as np
import hashlib

stepmax = int(g.getstring('steps to advance', '100'))
sel = g.getselrect()
step = 1
while step <= stepmax:
    g.advance(0, 1)
    execfile('invert.py')
    step = step + 1
    g.update()
Beispiel #43
0
selrect = g.getselrect()
if len(selrect) == 0: g.exit("There is no selection.")

# use same file name as in shift.lua
INIFileName = g.getdir("data") + "shift.ini"
oldparams = "0 0 or"
try:
    f = open(INIFileName, 'r')
    oldparams = f.readline()
    f.close()
except:
    # should only happen 1st time (INIFileName doesn't exist)
    pass

answer = g.getstring(
    "Enter x y shift amounts and an optional mode\n" +
    "(valid modes are copy/or/xor, default is or):", oldparams,
    "Shift selection")
xym = answer.split()

# extract x and y amounts
if len(xym) == 0: g.exit()
if len(xym) == 1: g.exit("Supply x and y amounts separated by a space.")
if not validint(xym[0]): g.exit("Bad x value: " + xym[0])
if not validint(xym[1]): g.exit("Bad y value: " + xym[1])
x = int(xym[0])
y = int(xym[1])

# extract optional mode
if len(xym) > 2:
    mode = lower(xym[2])
    if mode == "c": mode = "copy"
    for i in range(len(clist[0::3])):
        if 3 * i + 3 <= len(clist):
            temp = clist[3 * i:3 * i + 3]
            for x in [pbox[2] * i for i in range(n)]:
                for y in [pbox[3] * i for i in range(n)]:
                    newlist.append(temp[0] + x)
                    newlist.append(temp[1] + y)
                    newlist.append(temp[2])

    newlist.append(0)
    return newlist


input = g.getstring(
    'what cell state to screen for/ \n \
			treat selection as torus?/ \n \
			how many repeating units?',
    '%s/%s/%s' % (g.getoption("drawingstate"), '1', '2'))

state = int(input.split('/')[0])
torus = int(input.split('/')[1])
n = int(input.split('/')[2])

pbox = g.getselrect()
clist = getquad(pbox, n=n)
g.setclipstr(str(clist))

parsed_clist = parse_list(clist)
g.show('clist %i %s,  parsed_clist %i %s' %
       (len(clist), str(clist), len(parsed_clist), str(parsed_clist)))
Beispiel #45
0
opposite_dirs=[2,3,0,1] # index of opposite direction

# encoding: 
# (0-n_colors: empty square)
def encode(c,s,d):
    # turmite on color c in state s facing direction d
    return n_colors + n_dirs*(n_states*c+s) + d

prefix = 'LangtonsAnt' 
# (We choose a different name to the inbuilt Langtons-Ant rule to avoid
#  name collision between the rules we output and the existing icons.)

spec = golly.getstring(
'''This script will create a Langton's Ant CA for a given string of actions.

The string specifies which way to turn when standing on a square of each state.

Examples: RL (Langton's Ant), RLR (Chaos), LLRR (Cardioid), LRRL (structure)

Enter string:''', 'RL', 'Enter string:')

n_colors = len(spec)

d={'R':'2','L':'8'} # 1=noturn, 2=right, 4=u-turn, 8=left
turmite_spec = "{{"+','.join(['{'+str((i+1)%n_colors)+','+d[spec[i]]+',0}' for i in range(n_colors)])+"}}"
rule_name = prefix+'_'+spec
action_table = eval(turmite_spec.replace('}',']').replace('{','['))
n_states = len(action_table)
n_dirs=4
# (N.B. The terminology 'state' here refers to the internal state of the finite
#       state machine that each Turmite is using, not the contents of each Golly
#       cell. We use the term 'color' to denote the symbol on the 2D 'tape'. The
Beispiel #46
0
        
        table += "\n# Birth\n"
        for n in self.allneighbours_flat:
            if self.bee[n]:
                table += "off,"
                table += self.notationdict2[n]
                table += ",1\n"
        
        table += "\n# Survival\n"
        for n in self.allneighbours_flat:
            if self.ess[n]:
                table += "1,"
                table += self.notationdict2[n]
                table += ",1\n"

        table += "\n# Death\n"
        table += self.scoline("","",1,2,0)
        
        colours = ""
        self.saverule(self.rulename, comments, table, colours)

rulestring = g.getstring("To make a History rule, enter rule string in Alan Hensel's isotropic rule notation", 
                         "B2-a/S12")

rg = RuleGenerator()

rg.setrule(rulestring)
rg.saveIsotropicRule()
g.setrule(rg.rulename)

g.show("Created rule in file: " + rg.rulename + ".rule")
Beispiel #47
0
# use previous values if they exist
inifilename = g.getdir("data") + "random-fill.ini"
previousvals = "50 1 " + str(maxlive)
try:
    f = open(inifilename, "r")
    previousvals = f.readline()
    f.close()
except:
    # should only happen 1st time (inifilename doesn't exist)
    pass

result = g.getstring(
    "Enter percentage minstate maxstate values\n"
    + "where the percentage is an integer from 0 to 100\n"
    + "and the state values are integers from 1 to "
    + str(maxlive)
    + "\n"
    + "(maxstate is optional, default is minstate):",
    previousvals,
    "Randomly fill selection",
)

# save given values for next time this script is called
try:
    f = open(inifilename, "w")
    f.write(result)
    f.close()
except:
    g.warn("Unable to save given values in file:\n" + inifilename)

# extract and validate values
pmm = result.split()
Beispiel #48
0
import golly as g
from glife import *
from glife.text import make_text
t = g.getstring('what text?', g.getclipstr())
make_text(t).put(-50, -50)
Beispiel #49
0
from string import lower
import golly as g
import math

rules = ("JvN29", "Nobili32", "Hutton32")

rule = g.getrule ()
if rule not in rules:
    g.exit ("Invalid rule: " + rule + " (must be " + rules + ")")

rect = g.getselrect ()
if len (rect) == 0:
    g.exit ("There is no selection.")

answer = g.getstring("Enter direction to rotate in\n" +
                     "(valid rotations are cw and ccw, default is cw):",
                     "cw",
                     "Rotate selection")

if answer != "cw" and answer != "ccw":
    g.exit ("Unknown direction: " + answer + " (must be cw/ccw)")

cells = g.getcells (rect)

jvn_rotate = (( 9, 12, 11, 10),
              (13, 16, 15, 14),
              (17, 20, 19, 18),
              (21, 24, 23, 22))

def rotated (rotations, direction, state):
    for rotation in rotations:
        length = len (rotation)
Beispiel #50
0
# use same file name as in goto.lua
GotoINIFileName = g.getdir("data") + "goto.ini"
previousgen = ""
try:
    f = open(GotoINIFileName, 'r')
    previousgen = f.readline()
    f.close()
    if not validint(previousgen):
        previousgen = ""
except:
    # should only happen 1st time (GotoINIFileName doesn't exist)
    pass

gen = g.getstring("Enter the desired generation number,\n" +
                  "or -n/+n to go back/forwards by n:",
                  previousgen, "Go to generation")
if len(gen) == 0:
    g.exit()
elif gen == "+" or gen == "-":
    # clear the default
    savegen(GotoINIFileName, "")
elif not validint(gen):
    g.exit('Sorry, but "' + gen + '" is not a valid integer.')
else:
    # best to save given gen now in case user aborts script
    savegen(GotoINIFileName, gen)
    oldstep = g.getstep()
    goto(gen.replace(",",""))
    g.setstep(oldstep)
# getminpopandminbb.py
import golly as g

maxticks = g.getstring ("Enter maximum number of ticks to search: ", "1024")
r = g.getrect()
count, minT, minpop, minbbx, minbby, minbbt = 0, 0, int(g.getpop()), r[2], r[3], 0
newpop = minpop
while count<int(maxticks):
  if count%100==0:
    g.show("T: " + str(count) + "    Current pop: "+str(newpop)+"    Current minimum pop: " + str(minpop) + " at T = " + str(minT) + ". Min box = "+str([minbbx, minbby]) + " at T = " + str(minbbt) + ".  'q' to quit.")
    g.update()
    cancel=0
    for i in range(100): # clear buffer if, e.g., mouse events have been piling up
      evt = g.getevent()
      if evt == "key q none":
        cancel = 1
    if cancel==1: break 
  g.run(1)
  count+=1
  newpop = int(g.getpop())
  if newpop<minpop:
    minpop = newpop
    minT = count
  r = g.getrect()
  if r[2]*r[3]<minbbx*minbby:
    minbbx, minbby, minbbt = r[2], r[3], count
g.note("Finished scan of " + str(count) + " ticks.  Minimum population: " +str(minpop) + " at T = " + str(minT) + ". Min box = "+str([minbbx, minbby]) + " at T = " + str(minbbt))
    else:
        return ord_gcd(n2, n1)


def ord_gcd(l, g):
    if g % l == 0:
        return l
    return gcd(g % l, l)


def lcm(n1, n2):
    return n1 * n2 / gcd(n1, n2)


rawentry1 = g.getstring(
    "Enter the most common naturally occurring periods of oscillators and spaceships in this rule separated by commas (no spaces):"
)
rawentry2 = g.getstring(
    "What is the maximum number of generations to run each soup?")
rawentry3 = g.getstring("How many soups do you want to test?")

periodlist = map(int, rawentry1.split(','))
maxgens = int(rawentry2)
soups = int(rawentry3)

totalperiod = 1
for period in periodlist:
    totalperiod = lcm(period, totalperiod)

longest = [], 0
for soupnum in range(soups):
Beispiel #53
0
# -----------------------------------------------------

def show_status_text(s, d, t):
    if d==-1:
        if t==1:
            g.show(s + "Speed is " + str(t) + " tick per step.")
        else:
            g.show(s + "Speed is " + str(t) + " ticks per step.")
    else:
        g.show(s + "Delay between ticks is " + str(d) + " seconds.")

# -----------------------------------------------------

# if there are multiple layers, get permission to remove them
if g.numlayers() > 1:
    answer = g.getstring("All existing layers will be removed. OK?")
    if lower(answer[:1]) == "n":
        g.exit()
oldswitch = g.setoption("switchlayers", True) # allow user to switch layers
oldtile = g.setoption("tilelayers", True)
rule()
try:
    burp()
finally:
    # remove the cloned layers added by the script
    while g.numlayers() > 1: g.dellayer()
    g.setname("Stable Pseudo-Heisenburp Device")
    g.setoption("tilelayers", oldtile)
    g.setoption("switchlayers", oldswitch)
    g.show("")
Beispiel #54
0
# TODO:  track down bug where a trailing comment after the RLE keeps the
#        .cells pattern from being created (unless it's the lack of #N?)
# TODO:  automate retrieval of synthesiscosts.txt, but only do it on specific
#        request (in response to getstring question) and update the local copy
# TODO:  refactor the scanning system so that .cells files can be created
#        at the same time as .rle to be uploaded (currently this takes two passes,
#        so to get .cells file for new articles, first .rle files are created
#        and (manually) uploaded, then those same .rle files are downloaded again
#        the next time the script is run, and are used to make .cells files)

import golly as g
import urllib.request
import re
import os

samplepath = g.getstring("Enter path to generate .rle and .cells files",
                         "C:/users/{username}/Desktop/LW/")
if samplepath == "C:/users/{username}/Desktop/LW/":
    g.note("Please run this script again and change the sample path to something that works on your system.\n\n" \
         + "If the path you supply does not point to folders that you have permission to write to, " \
         + "or if synthfile is not present, the data collection process will eventually fail with an error.")
    g.exit()

outfolder = samplepath + "rle/"
cellsfolder = samplepath + "cells/"
rlefolder = samplepath + "rledata/"
synthfolder = samplepath + "synthesis-costs/"
synthfile = synthfolder + "synthesis-costs.txt"

if not os.path.exists(samplepath):
    resp = g.getstring(
        "No folder exists at '" + samplepath + "'.  Create it and subfolders?",
Beispiel #55
0


m,p,p,m,m,m,f,g,p,%s
m,p,1,m,m,m,f,g,p,%s
m,1,p,m,m,m,f,g,p,%s
m,1,1,m,m,m,f,g,p,%s
m,p,p,m,m,m,f,g,1,%s
m,p,1,m,m,m,f,g,1,%s
m,1,p,m,m,m,f,g,1,%s
m,1,1,m,m,m,f,g,1,%s
1,a,b,d,e,f,g,h,c,1
p,a,b,d,e,f,g,h,c,p

'''
rnum = golly.getstring('ECA number', '110')
name = 'W' + rnum
file = golly.getdir("rules") + name + ".rule"

r = bin(int(rnum))
r = r[:1:-1]
r += '0' * (8 - len(r))
rule = r
# rule=[0, 1, 1, 1, 1, 1, 0, 0];

dct = ['p', '1']
with open(file, 'w') as f:
    f.write(head % ((name, ) + tuple([dct[int(x)] for x in rule])))
golly.setalgo("RuleLoader")
golly.setrule(name + ':T1000,0')
Beispiel #56
0
# Shift current selection by given x y amounts using optional mode.
# Author: Andrew Trevorrow ([email protected]), June 2006.
# Updated to use exit command, Nov 2006.
# Updated to check for bounded grid, Oct 2010.

from glife import validint, inside
from string import lower
import golly as g

selrect = g.getselrect()
if len(selrect) == 0: g.exit("There is no selection.")

answer = g.getstring("Enter x y shift amounts and an optional mode\n" +
                     "(valid modes are copy/or/xor, default is or):",
                     "0 0 or",
                     "Shift selection")
xym = answer.split()

# extract x and y amounts
if len(xym) == 0: g.exit()
if len(xym) == 1: g.exit("Supply x and y amounts separated by a space.")
if not validint(xym[0]): g.exit("Bad x value: " + xym[0])
if not validint(xym[1]): g.exit("Bad y value: " + xym[1])
x = int(xym[0])
y = int(xym[1])

# extract optional mode
if len(xym) > 2:
    mode = lower(xym[2])
    if mode=="c": mode="copy"
    if mode=="o": mode="or"
    while i < w:
        j = 0
        while j < h:
            g.setcell(i, j, update[i][j])
            j += 1
        i += 1
    g.update()
    return update


try:
    g.new("Conway's Game of life")
    g.setrule("Life")
    g.setcolors([1, 255, 255, 255])
    g.setcolors([0, 0, 0, 0])
    maxsize = 100000
    count = 0
    width = int( g.getstring("Enter a width for the game of life:", "100") )
    height = int( g.getstring("Enter a height for the game of life:", "100") )
    g.select([0, 0, width, height])
    g.randfill(50)
    update = [[0 for x in range(width + 1)] for x in range(height + 1)]
    while count < maxsize:
        g.show("In main " + str(count))
        update = main(width, height, update)
        count += 1


finally:
    g.note("Goodbye")