Beispiel #1
0
else:
    popfunc = lambda: g.getpop()

for i in range(numsteps):
    g.run(1)
    if g.empty():
        break
    poplist.append(int(popfunc()))
    h = int(g.hash(g.getrect()))
    if h in hashlist:
        break
    hashlist.append(h)

layername = "recurrent 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.")

if poplayer == -1:
    poplayer = g.addlayer()
else:
    g.setlayer(poplayer)
g.new(layername)

rp_plot(poplist)
Beispiel #2
0
            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)
    return tile


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():
bitOnHorzLine = pattern('4.DBD$.F3.B.B$.F2.2B.2B$5.D.2D$D.B2.F.D2.D$3BD2FDF.2B$D4.D2.B.D$5.B2.B$.F2.DBD$.F2.DBD$4.DBD!')

"""
x = 11, y = 11, rule = Varlife
4.DBD$.F3.B.B$.F2.2B.2B$5.D.2D$D.B2.F.D2.D$3BD2FDF.2B$D4.D2.B.D$5.B2.B$.F2.DBD$.F2.DBD$4.DBD!
"""

# startX = -1610
# startY = 706
startX = 3199
startY = 738
# g.select([startX-3200, startY, 3201, 700])
# g.clear(0)

for layer in range(0, g.numlayers()):
    if g.getname(layer) == "ROM-3ins":
        g.setlayer(layer)

        g.dellayer()
        break

#g.addlayer()
#g.new('ROM-3ins')
#g.setrule('Varlife')


#code = g.getclipstr()
#open("c:\\tmp\\glife.log","a").write(code + "\n\n")

code = open("lang/out.asm","r").read()
#code = open("lang/bj-randomer.asm").read()
Beispiel #4
0
g.show("")

# set initial directory for the save dialog
initdir = ""
savename = g.getdir("data") + "save-image.ini"
try:
    # try to get the directory saved by an earlier run
    f = open(savename, 'r')
    initdir = f.readline()
    f.close()
except:
    # this should only happen the very 1st time
    initdir = g.getdir("data")

# remove any existing extension from layer name and append .png
initfile = g.getname().split('.')[0] + ".png"

# prompt user for output file (image type depends on extension)
outfile = g.savedialog(
    "Save image file",
    "PNG (*.png)|*.png|BMP (*.bmp)|*.bmp|GIF (*.gif)|*.gif" +
    "|TIFF (*.tif)|*.tif|JPEG (*.jpg)|*.jpg", initdir, initfile)
if len(outfile) > 0:
    im.save(outfile)
    g.show("Image saved as " + outfile)

    # remember file's directory for next time
    try:
        f = open(savename, 'w')
        f.write(os.path.dirname(outfile))
        f.close()
        g.setoption("showicons", True)
        g.update()

    if fileexists:
        g.note("Updated the icon data in " + rulepath)
    else:
        g.note("Created " + rulepath)


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

# WARNING: changing this prefix will require same change in icon-importer.py
layerprefix = "imported icons for "

# check that the current layer was created by icon-importer.py
layername = g.getname()
if not layername.startswith(layerprefix):
    g.exit("The current layer wasn't created by icon-importer.py.")

# get the original rule
rulename = layername.split(" for ")[1]

icondata = extract_icons(31)
icondata += extract_icons(15)
icondata += extract_icons(7)

if len(icondata) == 0:
    g.exit("There are no icon images to export.")

if not multi_color_icons:
    # check if the icon data matches Golly's built-in grayscale icons
# Modified by Andrew Trevorrow, 5 October 2007 (metafied pattern is
# created in a separate layer so we don't clobber the selection).

import os
import golly as g
from glife import *

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

# check that a layer is available for the metafied pattern;
# if metafied layer already exists then we'll use that
layername = "metafied"
metalayer = -1
for i in xrange(g.numlayers()):
   if g.getname(i) == layername:
      metalayer = i
      break
if metalayer < 0 and g.numlayers() == g.maxlayers():
   g.exit("You need to delete a layer.")

# note that getrule returns canonical rule string
rulestr = g.getrule().split(":")[0]
if (not rulestr.startswith("B")) or (rulestr.find("/S") == -1):
   g.exit("This script only works with B*/S* rules.")

# get the current selection
slist = g.getcells(selrect)
selwidth = selrect[2]
selheight = selrect[3]
Beispiel #7
0
        g.fit()
        g.setoption("showicons",True)
        g.update()
    
    if fileexists:
        g.note("Updated the icon data in " + rulepath)
    else:
        g.note("Created " + rulepath)

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

# WARNING: changing this prefix will require same change in icon-importer.py
layerprefix = "imported icons for "

# check that the current layer was created by icon-importer.py
layername = g.getname()
if not layername.startswith(layerprefix):
    g.exit("The current layer wasn't created by icon-importer.py.")

# get the original rule
rulename = layername.split(" for ")[1]

icondata = extract_icons(31)
icondata += extract_icons(15)
icondata += extract_icons(7)

if len(icondata) == 0:
    g.exit("There are no icon images to export.")

if not multi_color_icons:
    # check if the icon data matches Golly's built-in grayscale icons
Beispiel #8
0
    try:
        r = rect(g.getrect())
        if (not r.empty) and (not r.visible()): g.fit()
    except:
        # getrect failed because pattern is too big
        g.fit()

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

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()) ]
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 #10
0
                else:
                    g.note(
                        "Pre-processing failed on lines:\n" + Zline + "\n" +
                        line +
                        "\nNeed a Z and NZ line for each state, or * / ZZ syntax."
                    )
                    g.exit()

numstates = len(progonly)

statedict = {}
for i in range(0, numstates, 2):
    parts = progonly[i].split("; ")
    statedict[parts[0]] = i

if g.getname()[:3] != "GPC":
    g.new("Compiled " + progname)
    GPClayer = -1
else:
    GPClayer = g.getlayer()
    g.addlayer()
    g.setname("Compiled " + progname)

g.putcells(startpat)

firstreflx, firstrefly = -1, -1
for k in range(0, numstates, 2):
    g.putcells(Snark_N, 184 + k * 72, -20 + k * 56)
    g.putcells(Snark_E, -2177 + numstates * 72 + len(outputdict) * 16,
               -2369 - k * 16 + numstates * 72 + len(outputdict) * 16)
    g.putcells(
Beispiel #11
0
    eaterNE = eaterSE(0, 10, flip_y)
    eY = 59
    eaters = (eaterNE(0, eY), eaterSE(0, eY))
    eX = (bmheight + 1) * LMdx - (copies * bmwidth - 1) * pdx   
    eX = 1 + eX // 2 * 2
    all = pattern()
    for i in xrange(bmheight):
        all += eaters[i % (1 + LMsx % 2)](eX, i * LMdy)
    all.put()   
    golly.setpos(str(-pdx * bmwidth // 2 + (bmheight - 1) * LMdx), str(Ly//2))
    golly.fit()
    #golly.setcursor(3)
"""

if __name__  ==  '__main__':   
    title = golly.getname().split('.')[0] + '-printer'
    prog = "bits = '%s'\n%s" % (get_bitmap(), prog)
    exec compile(prog, '<string>', 'exec')
    golly.duplicate()
    golly.setoption("syncviews", False)
    main(16, 1, title)   

    #Save pattern as a Python program
    hdr = '#Golly Python script\nimport golly\nfrom glife import *\n'
    ftr = "main(16, 1, '%s')" % title 
    s = """#Golly Python script
import zlib,base64
s=zlib.decompress(base64.decodestring('''
%s'''))
try:import golly
except ImportError:print s
Beispiel #12
0
# The "envelope" layer remembers all live cells.
# Author: Andrew Trevorrow ([email protected]), December 2006.
# Updated for better compatibility with envelope.pl, June 2007.
# Updated to use new setcolors command, September 2008.

import golly as g

if g.empty(): g.exit("There is no pattern.")

currindex = g.getlayer()
startindex = 0
envindex = 0
startname = "starting pattern"
envname = "envelope"

if currindex > 1 and g.getname(currindex - 1) == startname \
                 and g.getname(currindex - 2) == envname :
    # continue from where we left off
    startindex = currindex - 1
    envindex = currindex - 2

elif currindex + 2 < g.numlayers() \
                 and g.getname(currindex + 1) == startname \
                 and g.getname(currindex)     == envname :
    # switch from envelope layer to current layer and continue
    currindex += 2
    g.setlayer(currindex)
    startindex = currindex - 1
    envindex = currindex - 2

elif currindex + 1 < g.numlayers() \
import golly as g
import os.path

# default base path as the Desktop, change it if needed
default_path = os.path.expanduser('~/Desktop')
# default name is the current pattern name without extension
pattern_name = g.getname().split('.')[0]
# getting an output path
export_path = g.savedialog('Choose the directory and name',
                           'All files (*)|*',
                           default_path,
                           pattern_name)
if export_path == "":
    export_path = default_path

# number of generations
num_generations = 10

# has a selection been made?
selected = 1 if len(g.getselrect()) > 0 else 0

for i in range(num_generations):
    # advance by one generation (checking if something is selected)
    if selected == 1:
        g.advance(0, 1)
    else:
        g.run(1)
    # export to a new file
    file_path = '%s-%d.rle' % (export_path, i)
    g.show(file_path)
    g.save(file_path, 'rle')
Beispiel #14
0
g.show("")

# set initial directory for the save dialog
initdir = ""
savename = g.getdir("data") + "save-image.ini"
try:
   # try to get the directory saved by an earlier run
   f = open(savename, 'r')
   initdir = f.readline()
   f.close()
except:
   # this should only happen the very 1st time
   initdir = g.getdir("data")

# remove any existing extension from layer name and append .png
initfile = g.getname().split('.')[0] + ".png"

# prompt user for output file (image type depends on extension)
outfile = g.savedialog("Save image file",
                       "PNG (*.png)|*.png|BMP (*.bmp)|*.bmp|GIF (*.gif)|*.gif" +
                       "|TIFF (*.tif)|*.tif|JPEG (*.jpg)|*.jpg",
                       initdir, initfile)
if len(outfile) > 0:
   im.save(outfile)
   g.show("Image saved as " + outfile)
   
   # remember file's directory for next time
   try:
      f = open(savename, 'w')
      f.write(os.path.dirname(outfile))
      f.close()
Beispiel #15
0
# The "envelope" layer remembers all live cells.
# Author: Andrew Trevorrow ([email protected]), December 2006.
# Updated for better compatibility with envelope.pl, June 2007.
# Updated to use new setcolors command, September 2008.

import golly as g

if g.empty(): g.exit("There is no pattern.")

currindex = g.getlayer()
startindex = 0
envindex = 0
startname = "starting pattern"
envname = "envelope"

if currindex > 1 and g.getname(currindex - 1) == startname \
                 and g.getname(currindex - 2) == envname :
    # continue from where we left off
    startindex = currindex - 1
    envindex = currindex - 2

elif currindex + 2 < g.numlayers() \
                 and g.getname(currindex + 1) == startname \
                 and g.getname(currindex)     == envname :
    # switch from envelope layer to current layer and continue
    currindex += 2
    g.setlayer(currindex)
    startindex = currindex - 1
    envindex = currindex - 2

elif currindex + 1 < g.numlayers() \
Beispiel #16
0
def multi_color_icons(iconcolors):
    # return True if at least one icon color isn't a shade of gray
    for R,G,B in iconcolors:
        if R != G or G != B: return True
    # grayscale
    return False

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

# check that a layer is available
if g.numlayers() == g.maxlayers():
    g.exit("You need to delete a layer.")

# WARNING: changing this prefix will require same change in icon-exporter.py
layerprefix = "imported icons for "
if g.getname().startswith(layerprefix):
    g.exit("You probably meant to run icon-exporter.py.")

g.addlayer()
rulename = g.getrule().split(":")[0]

# search for rulename.rule and import any icon data (also builds iconcolors)
import_icons(rulename)

if len(iconcolors) == 0 and ("-" in rulename) and not (rulename.endswith("-shared")):
    # rulename.rule has no icons and rulename contains a hyphen, so
    # check if prefix-shared.rule exists and ask user if they want to edit
    # the icons in that file
    sharedname = check_for_shared_rule(rulename)
    if len(sharedname) > 0:
        rulename = sharedname
Beispiel #17
0
def dmprinter(pdy, copies=1):
    ''' Generate & display a dot matrix printer for named bitmap pattern '''
    #Horizontal pixel separation between LineMakers. minimum = 5
    LMsx = 5

    #Horizontal distance between bitmap pixels. Constant, due to LineMaker period
    pdx = 15

    #Distance between LineMakers
    LMdx, LMdy = -LMsx * pdx, pdy

    #Get bitmap pattern from current selection.
    bm = get_bitmap()

    #Make printer in a new layer
    golly.duplicate()
    golly.setoption("syncviews", False)

    #Build new window title from old
    title = golly.getname().split('.')[0]
    title = '%s_Printer [%d] v0.10' % (title, pdy)
    golly.new(title)

    #Make sure we're using the standard Life generation rule
    golly.setrule("B3/S23")

    #Bitmap dimensions. Width MUST be of form 4m, for m >=1
    bmheight = len(bm)
    bmwidth = len(bm[0])
    mid = (bmheight + 1) // 2

    loopw = (bmwidth - 8) // 4
    loopm = pdx * loopw

    #Gliders, heading north-east
    g0 = pattern('2bo$2o$b2o!')
    g1 = pattern('obo$2o$bo!')
    gliders = [
        g0, g1,
        g1(0, 2, rccw),
        g0(0, 2, rccw),
        g0(2, 2, flip),
        g1(2, 2, flip),
        g1(2, 0, rcw),
        g0(2, 0, rcw)
    ]

    #Create full Glider loop.
    gg = []
    ox, oy = 35, 23
    for j in xrange(loopw + 1):
        dd = pdx * j
        gg += [
            gliders[0](ox + dd, oy - dd), gliders[1](ox + 8 + dd, oy - 7 - dd)
        ]
    dd = loopm
    gg += [gliders[2](45 + dd, 4 - dd), gliders[3](37 + dd, -3 - dd)]

    ox, oy = 26 + loopm, -4 - loopm
    for j in xrange(loopw + 1):
        dd = pdx * j
        gg += [
            gliders[4](ox - dd, oy + dd), gliders[5](ox - 8 - dd, oy + 7 + dd)
        ]
    dd = loopm
    gg += [gliders[6](16, 15), gliders[7](24, 22)]
    parity = 2 * ((loopw + 1) * (0, 0) + (1, 1))

    def buildLM():
        ''' Build a complete LineMaker '''
        #Populate glider loop. (jj, ii) are bitmap coords
        gloop = pattern()
        for j in xrange(bmwidth):
            jj = (j - delta + bmwidth - 1) % bmwidth

            #Is there a pixel at this location?
            if bm[ii][jj] == parity[j]:
                gloop += gg[j]  #Add glider to the loop

        #Only put LineMaker if glider loop isn't empty
        if len(gloop) > 0:
            (LMBlank + gloop).put(Lx, Ly, trans)

    #Assemble blank LineMaker
    LMBlank = linemaker(loopm)

    #Do upper LineMakers
    trans = identity
    for i in xrange(mid):
        ii = mid - (i + 1)
        io = mid + (i + 1)
        Lx, Ly = io * LMdx, ii * LMdy
        delta = LMsx * io
        buildLM()

    #Do lower LineMakers
    trans = flip_y
    for i in xrange(mid, bmheight):
        ii = i
        io = i + 2
        Lx, Ly = io * LMdx + pdx, ii * LMdy + 128
        delta = LMsx * io - 1
        buildLM()

    #Eaters facing south-east & north-east
    eaterSE = pattern('2o$bo$bobo$2b2o!')
    eaterNE = eaterSE(0, 10, flip_y)
    eY = 59
    eaters = (eaterNE(0, eY), eaterSE(0, eY))

    #Eater horizontal displacement. Must be odd
    #bmwidth muliplier determines number of copies visible 'outside' printer.
    eX = (bmheight + 1) * LMdx - (copies * bmwidth - 1) * pdx
    eX = 1 + eX // 2 * 2  #Adjust parity
    all = pattern()
    for i in xrange(bmheight):
        all += eaters[i % (1 + LMsx % 2)](eX, i * LMdy)
    all.put()

    #Centre view over bitmap output area
    golly.setpos(str(-pdx * bmwidth // 2 + (bmheight - 1) * LMdx),
                 str(Ly // 2))
    #golly.setmag(-2)    #Aliasing effects happen at smaller scales than -2 :(
    golly.fit()
import golly as g
import os.path

# default base path as the Desktop, change it if needed
default_path = os.path.expanduser('~/Desktop')
# default name is the current pattern name without extension
pattern_name = g.getname().split('.')[0]
# getting an output path
export_path = g.savedialog('Choose the directory and name', 'All files (*)|*',
                           default_path, pattern_name)
if export_path == "":
    export_path = default_path

# number of generations
num_generations = 10

# has a selection been made?
selected = 1 if len(g.getselrect()) > 0 else 0

for i in range(num_generations):
    # advance by one generation (checking if something is selected)
    if selected == 1:
        g.advance(0, 1)
    else:
        g.run(1)
    # export to a new file
    file_path = '%s-%d.rle' % (export_path, i)
    g.show(file_path)
    g.save(file_path, 'rle')
Beispiel #19
0
    if statecount[state] > 0:
        # show count on top of bar
        t, twd, tht = color_text(str(statecount[state]), extrastate)
        t.put(barwd * (state + 1) - barwd / 2 - twd / 2, -barht - tht - 3)


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

if g.empty(): g.exit("There is no pattern.")
if g.numstates() == 256: g.exit("No room for extra state.")

# check that a layer is available for the histogram
histname = "histogram"
histlayer = -1
for i in xrange(g.numlayers()):
    if g.getname(i) == histname:
        histlayer = i
        break
if histlayer == -1 and g.numlayers() == g.maxlayers():
    g.exit("You need to delete a layer.")

# use selection rect if it exists, otherwise use pattern bounds
label = "Selection"
r = rect(g.getselrect())
if r.empty:
    label = "Pattern"
    r = rect(g.getrect())

# count all cell states in r
g.show("Counting cell states...")
counted = 0
Beispiel #20
0
    # return True if at least one icon color isn't a shade of gray
    for R, G, B in iconcolors:
        if R != G or G != B: return True
    # grayscale
    return False


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

# check that a layer is available
if g.numlayers() == g.maxlayers():
    g.exit("You need to delete a layer.")

# WARNING: changing this prefix will require same change in icon-exporter.py
layerprefix = "imported icons for "
if g.getname().startswith(layerprefix):
    g.exit("You probably meant to run icon-exporter.py.")

g.addlayer()
rulename = g.getrule().split(":")[0]

# search for rulename.rule and import any icon data (also builds iconcolors)
import_icons(rulename)

if len(iconcolors) == 0 and (
        "-" in rulename) and not (rulename.endswith("-shared")):
    # rulename.rule has no icons and rulename contains a hyphen, so
    # check if prefix-shared.rule exists and ask user if they want to edit
    # the icons in that file
    sharedname = check_for_shared_rule(rulename)
    if len(sharedname) > 0: