예제 #1
0
	def LoadMoveTable(self, path, report):
		ins = open(path, "r" )
		array = []
		
		bestdxrecipe = []
		
		for line in ins:
			vals = line.split(":")
			
			vals[0] = vals[0].replace("m", "")
			vals[0] = vals[0].split(",")
			x = int(vals[0][0])
			y = int(vals[0][1])
			vals[1] = vals[1].replace("E", "").replace("\n", "")
			vals[1] = vals[1].split(",")
			
			for i in xrange(0, len(vals[1])):
				vals[1][i] = int(vals[1][i])
			
			if x - y == -1 and len(bestdxrecipe) == 0:
				bestdxrecipe = vals[1]
				
			array.append([x, y, vals[1]])
			
		if report:
			g.show(str(bestdxrecipe))
			g.setclipstr(str(bestdxrecipe))
			
		ins.close()
		
		return array	
예제 #2
0
	def LoadMoveTable(self, path, report):
		ins = open(path, "r" )
		array = []
		
		bestdxrecipe = []
		bestdx = 1
		idx = 0
		
		for line in ins:
			vals = line.split(":")
			
			vals[0] = vals[0].replace("m", "")
			vals[0] = vals[0].split(",")
			x = int(vals[0][0])
			y = int(vals[0][1])
			vals[1] = vals[1].replace("E", "").replace("\n", "").replace(" ", "")
			vals[1] = vals[1].split(",")
			
			for i in xrange(0, len(vals[1])):
				vals[1][i] = int(vals[1][i])
			
			if x < 0 and -x * len(bestdxrecipe) > -bestdx * len(vals[1]):
				bestdxrecipe = vals[1]
				bestdx = x
				idx = len(array)
				
			array.append([x, y, vals[1]])
			
		if report:
			g.show(str(bestdxrecipe) + ":" + str(idx))
			g.setclipstr(str(bestdxrecipe))
			
		ins.close()
		
		return array	
예제 #3
0
def retrieveparam(article, param, s):
    if s.find(param) < 0:
        g.note("Setting clipboard to current html -- can't find '" + param +
               "'.")
        g.setclipstr(s)
        g.exit()
    regexstr = param + r'\s*=\s*(.*)$'  #######################
    match = re.search(regexstr, s, re.MULTILINE)
    if match:
        # pval = match.group(1)
        # if pval[-1:]=="\n": pval = pval[:-1]
        # # handle the case where newlines are not added before each pipe character
        # pval += "|"
        # g.note(pval + " :: " + pval[:pval.index("|")])
        # return pval[:pval.index("|")]

        # try to fix problem with multiple EmbedViewers on one line and pname as last parameter, as in Density article
        grp = match.group(1)
        if grp.find("}") > -1:
            pval = grp[:grp.find("}")] + "|"
        else:
            pval = grp + "|"

        return pval[:pval.index("|")].strip()
    else:
        g.note("Could not find definition of parameter '" + param +
               "' in article '" + article + "'.")
        g.setclipstr(s)
        g.exit()
예제 #4
0
def HWSS3SLsEdgeShooter(slv):
	
	slv.AppendExternalRecipe([-4, -6, -8, -9, -17])
	slv.block0[0] += 19
	slv.block0[1] += -12
	
	slv.block1[0] += 17
	slv.block1[1] += 1
	
	#salvo.GotoAdvanced(12, -20, 10)
	#'MOVE', 18908, -1, 'MOVE', 297, 10
	slv.ApplyRecipeSmart(18908, -1)
	slv.ApplyRecipeSmart(297, 10)
	slv.Swap()
	#'MOVE', 1968, -1, 'MOVE', 25, 5]
	#salvo.GotoAdvanced(13, -11, 5)
	slv.ApplyRecipeSmart(1968, -1)
	slv.ApplyRecipeSmart(25, 5)

	slv.block0[0] = 0
	slv.block0[1] = 0
	slv.AppendExternalRecipe([-22, -10, -27])

	slv.PlaceRecipe()
	g.setclipstr(str(slv.recipe))
예제 #5
0
	def PlaceRecipe(self, x = 0, y = 0, makenew = True):
		if makenew:
			g.new("Results")
			
		g.show(str(self.recipeIdxList))
		g.setclipstr(str(self.recipeIdxList))
		g.putcells(blck, x, y)
		i = 0 
		for r in self.recipe:
			g.putcells(gld, x + 80 + i * 128, y + 80 + i * 128 + r)
			i += 1
예제 #6
0
def retrieveparam(article, param, s):
  if s.find(param)<0:
    g.note("Setting clipboard to current html -- can't find '"+param+"'.")
    g.setclipstr(s)
    g.exit()
  regexstr = param+r'\s*=\s*(.*)$' #######################
  match = re.search(regexstr, s, re.MULTILINE)
  if match:
    pval = match.group(1)+"|"
    return pval[:pval.index("|")] # handle the case where newlines are not added before each pipe character
  else:
    g.note("Could not find definition of parameter '"+param+"' in article '"+article+"'.")
    g.setclipstr(s)
    g.exit()
예제 #7
0
def canonise():

    p = bijoscar(1000)

    representation = "#"
    for i in range(abs(p)):
        rect = g.getrect()
        representation = compare_representations(
            representation,
            canonise_orientation(rect[2], rect[3], rect[0], rect[1], 1, 0, 0,
                                 1))
        representation = compare_representations(
            representation,
            canonise_orientation(rect[2], rect[3], rect[0] + rect[2] - 1,
                                 rect[1], -1, 0, 0, 1))
        representation = compare_representations(
            representation,
            canonise_orientation(rect[2], rect[3], rect[0],
                                 rect[1] + rect[3] - 1, 1, 0, 0, -1))
        representation = compare_representations(
            representation,
            canonise_orientation(rect[2], rect[3], rect[0] + rect[2] - 1,
                                 rect[1] + rect[3] - 1, -1, 0, 0, -1))
        representation = compare_representations(
            representation,
            canonise_orientation(rect[3], rect[2], rect[0], rect[1], 0, 1, 1,
                                 0))
        representation = compare_representations(
            representation,
            canonise_orientation(rect[3], rect[2], rect[0] + rect[2] - 1,
                                 rect[1], 0, -1, 1, 0))
        representation = compare_representations(
            representation,
            canonise_orientation(rect[3], rect[2], rect[0],
                                 rect[1] + rect[3] - 1, 0, 1, -1, 0))
        representation = compare_representations(
            representation,
            canonise_orientation(rect[3], rect[2], rect[0] + rect[2] - 1,
                                 rect[1] + rect[3] - 1, 0, -1, -1, 0))
        g.run(1)

    if (p < 0):
        prefix = "q" + str(abs(p))
    elif (p == 1):
        prefix = "s" + str(g.getpop())
    else:
        prefix = "p" + str(p)

    g.setclipstr("x" + prefix + "_" + representation)
예제 #8
0
def check_keyboard():
    global runflag
    while 1:
        evt = g.getevent()
        if evt != "":
            g.show(state + " -- " + nextstate + " :: " + instr + "; regs=" +
                   str(registers) +
                   " -- 'r' to toggle run mode, any key to step")
        if evt == "key q none":
            g.setclipstr(s)
            g.exit()
        if evt == "key r none":
            runflag = 1 - runflag
        elif evt == "key g none":
            break
        else:
            g.doevent(evt)
        if runflag == 1:
            break
예제 #9
0
        g.setmag(0)
        g.show("")

        # plot the data (do last because it could take a while if numsteps is huge)
        x = int(float(genlist[0] - mingen) / genscale)
        y = int(float(poplist[0] - minpop) / popscale)
        oldsecs = time()
        for i in xrange(numsteps):
            newx = int(float(genlist[i + 1] - mingen) / genscale)
            newy = int(float(poplist[i + 1] - minpop) / popscale)
            draw_line(x, -y, newx, -newy)
            x = newx
            y = newy
            newsecs = time()
            if newsecs - oldsecs >= 1.0:  # update plot every second
                oldsecs = newsecs
                g.update()
        htlist.append(g.getrect()[3])
        plotlist.append(g.getcells(g.getrect()))

g.setlayer(plotlayer)
g.new('')
ht = 0
for i in range(len(plotlist)):
    ht = ht + htlist[i] + 20
    make_text(str(i)).put(-500, ht)
    g.putcells(plotlist[i], 0, ht)

g.setclipstr(str(htlist))
g.setname('bk_plot')
예제 #10
0
# Get catalyst in various positions
if g.getselrect() != []:
    g.shrink()
pattern = g.getcells(r)
patrlelist = []
translist =[(1,0,0,1), (1,0,0,-1), (-1,0,0,1), (-1,0,0,-1),
            (0,1,1,0), (0,-1,1,0), (0,1,-1,0), (0,-1,-1,0)]
# Get unique transformed patterns
for trans in translist:
    g.new('')
    g.putcells(g.transform(pattern, 0, 0, *trans))
    g.select(g.getrect())
    g.copy()
    patrle = ''.join(g.getclipstr().split('\n')[1:])
    if patrle not in patrlelist:
        patrlelist.append(patrle)
patrles = '\n'.join(patrlelist)

# Save data to file
catpath = g.savedialog('Catalyst File', 'all files(*.*)|*', catdir)
try:
    with open(catpath, 'w') as catfile:
        catfile.write(patrles)
    g.exit('Catalyst file successfully generated at {}'.format(catpath))
except:
    if catpath == '':
        g.setclipstr(patrles)
        g.exit('No filename specified, saved it to clipboard instead.')
    else:
        raise
예제 #11
0
파일: mc2asm.py 프로젝트: marcan/ctf
import golly as g

x,y=0,0
w=110
h=7*8
bits = ""
dump = ""

for row in xrange(y, y+h):
   for col in xrange(x, x+w):
      if g.getcell(col, row) > 0:
         bits += "1"
         dump += "%d,%d\n" % (col, row)
      else:
         bits += "0"

g.setclipstr(dump+"r\n")

data = ""
i = 0
while len(bits) >= 8:
    v = int(bits[:8],2)
    bits = bits[8:]
    if 12 < (i % 0x6e) and i > 0x10 and i != 0x6d:
        v = 0xf4
    data += chr(v)
    i += 1

open("/tmp/life.bin","w").write(data)
os.system("objdump -M intel -b binary -m i386 -D /tmp/life.bin | grep -v hlt > /tmp/life.txt")
예제 #12
0
x, y = 0, 0
w = 110
h = 7 * 8
bits = ""
dump = ""

for row in xrange(y, y + h):
    for col in xrange(x, x + w):
        if g.getcell(col, row) > 0:
            bits += "1"
            dump += "%d,%d\n" % (col, row)
        else:
            bits += "0"

g.setclipstr(dump + "r\n")

data = ""
i = 0
while len(bits) >= 8:
    v = int(bits[:8], 2)
    bits = bits[8:]
    if 12 < (i % 0x6e) and i > 0x10 and i != 0x6d:
        v = 0xf4
    data += chr(v)
    i += 1

open("/tmp/life.bin", "w").write(data)
os.system(
    "objdump -M intel -b binary -m i386 -D /tmp/life.bin | grep -v hlt > /tmp/life.txt"
)
예제 #13
0
        g.run(p)  # get rid of bounding-box marker sparks first
        g.setrule("LifeHistory")
        # there are no pseudo-period template guns, so one cycle should be enough
        g.run(p)
        originalONcells = g.getcells(r)
        g.run(p)
        g.clear(1)
        g.setgen("0")
        g.save(os.path.join(LHoutfolder, item), "rle")
        if str(originalONcells) != str(g.getcells(r)):
            mismatchreport += "Template gun LifeHistory mismatch found at period " + str(
                p) + " after one cycle and two cycles.\n"

missinggunreport = ""
for i in range(14, 1025):
    if i not in perioddict:
        missinggunreport += "Missing gun with period " + str(i) + "\n"

outmsg = "Done." if warnings == "" else "Done.  Errors:\n" + warnings
outmsg += "\nGuns built=" + str(countbuilt) \
       + ", fixed=" + str(countfixed) \
       + ", special=" +str(countspecial) \
       + ", from var folder=" + str(countvar0) \
       + "\n -- total=" + str(countbuilt + countfixed + countspecial + countvar0)
if missinggunreport != "":
    outmsg += "\n" + missinggunreport
if mismatchreport != "":
    outmsg += "\n" + mismatchreport
g.show("Processing complete.")
g.setclipstr(outmsg)
g.note(outmsg)
예제 #14
0
     if x == "S" or x == "B":
         totalistic_context = "none"
     if x == "S":
         bs = "1,"
     if x == "B":
         bs = "0,"
  elif x == "-":
    positive_or_inverse = "inverse"
  elif x in ["c", "a", "e", "k", "i", "v", "j", "y", "q", "r", "w", "t", "z"] and totalistic_context != "none":
     if positive_or_inverse == "positive":
        notation_letter = x
        f.write(create_table_row(bs, totalistic_context, notation_letter, []))   
     else:
        notation_letter = x
        inverse_list.append(x)


f.write("# Death otherwise"+"\n")
f.write("1,a,b,c,d,e,f,g,h,0"+"\n\n")
f.flush()
f.close()
golly.setalgo("RuleTable")
golly.setrule(rule_name)
if pastepattern != "none":
  golly.setclipstr(pastepattern)
  golly.show("Paste the pattern when you are ready....")
else:
  golly.show("Created "+rule_name+".table in "+golly.getdir("rules"))


                    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)))

fclist = full_clist(parsed_clist, pbox)
adjmat = adjacencymatrix(parsed_clist, pbox, torus, n=n)
s = mathematica(str(adjmat))
g.setclipstr(s)
예제 #16
0
# Use LifeHistory. Indicate the single channel lane by
# drawing a single NE glider in state 4 (red).
# The output cell list will have your pattern roughly
# centered on (0,0)
import golly as g

cells = g.getcells(g.getrect())
sm = smy = cnt = 0
lane = -999
for i in range(0, len(cells)-2, 3):
    if cells[i+2] == 4:
        lane = max(lane, cells[i] + cells[i+1])
    elif cells[i+2] % 2:
        cnt += 1
        sm += cells[i] - cells[i+1]

sm //= 2 * cnt

dx = lane // 2 + sm - 1
dy = lane - lane // 2 - sm

outstr = "./elbow "
for i in range(0, len(cells)-2, 3):
    if cells[i+2] % 2:
        outstr += "%d %d " % (cells[i] - dx, cells[i+1] - dy)

g.show(outstr)
g.setclipstr(outstr)
예제 #17
0
import golly as g
rule = g.getstring(
    "Initial MAP rule to modify (default is CGoL) without the MAP prefix. Leave blank to start from scratch (B/S)",
    "ARYXfhZofugWaH7oaIDogBZofuhogOiAaIDogIAAgAAWaH7oaIDogGiA6ICAAIAAaIDogIAAgACAAIAAAAAAAA"
)
if rule == "":
    rule = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
changes = int(g.getstring("How many changes are you planning?", "1"))
for i in range(changes):
    newcase = g.getstring("Binary code to implement:", "000000000")
    defect = int(newcase, 2)
    base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
    rulepos = (defect - (defect % 6)) // 6
    checkcase = int(base64.index(rule[rulepos]))
    bcheckcase = "{0:06b}".format(checkcase)
    if bcheckcase[defect % 6] == "1":
        newdec = int(bin(base64.index(rule[rulepos]))[2:]) - int(
            bin(2**(5 - (defect % 6)))[2:])
    elif bcheckcase[defect % 6] == "0":
        newdec = int(bin(base64.index(rule[rulepos]))[2:]) + int(
            bin(2**(5 - (defect % 6)))[2:])
    newdecnum = int(str(newdec), 2)
    pointdefect = base64[newdecnum]
    newrule = rule[0:rulepos] + pointdefect + rule[(rulepos + 1):len(rule)]
    g.show("Last transition changed: " + str(pointdefect) + " replaced " +
           str(rule[rulepos]) + " at position " + str(rulepos) +
           ", new rule is MAP" + newrule)
    rule = newrule

g.setclipstr("MAP" + newrule)
예제 #18
0
import golly as g
base64dict = {}
for index, char in enumerate(
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"):
    base64dict[char] = "".join(
        ["1" if index & 2**(5 - j) else "0" for j in range(6)])
mapstr = g.getstring(
    "Enter MAP string to convert to a rule: ",
    "ARYXfhZofugWaH7oaIDogBZofuhogOiAaIDogIAAgAAWaH7oaIDogGiA6ICAAIAAaIDogIAAgACAAIAAAAAAAA"
)
if mapstr[:3] == "MAP": mapstr = mapstr[3:]
if len(mapstr) != 86:
    g.warn("Map string is the wrong length -- should be 86 characters.")
    g.exit()
s = "".join([base64dict[char] for char in mapstr])
ruletablestr="@RULE MAPblahblahblah\nRule table for nontotalistic rule MAPblahblahblah" \
            +"\n\n@TABLE\nn_states:2\nneighborhood:Moore\nsymmetries:none\n\n"
for i in range(512):
    binary = "{0:09b}".format(i)
    for j in binary[4] + binary[:4] + binary[5:]:
        ruletablestr += j + ","
    ruletablestr += s[i] + "\n"
g.setclipstr(ruletablestr.replace("blahblahblah", mapstr))
예제 #19
0
            space_len = len(comments[i])-1
    if not began: #if still introduction
        comments2 += comments[i] + '\n'
    elif i != len(comments)-1 and '#O' in comments[i+1]: #puts pattern discoverer on name line with brackets
        comments2 += comments[i] + ' [' + comments[i+1][3:] + ']\n'
    elif '#C' in comments[i] and '----' not in comments[i]: #spaces comment lines to match pattern number
        comments2 += '#C' + ' '*space_len*began + comments[i][3:] + '\n'
    elif '#O' in comments[i]: #discoverers are put on the previous line; this is so that they're not duplicated
        pass
    else:
        comments2 += comments[i] + '\n'
comments2_intro = comments2[:comments2.index('1.0.0')]
comments2_patterns = comments2[comments2.index('1.0.0'):]
comments2_patterns = comments2_patterns.replace("#N ","#C ") #comments file only has one #N, and it's at the very beginning
comments2_patterns = comments2_patterns.replace(' #C', '\n#C')
comments2 = comments2_intro + comments2_patterns
    
# show_message('Comments size: %s KB' % ((len(comments2)+500)//1000),0.5)
show_message('Comments size: %s KB text, %s KB LifeViewer labels' % ((len(comments2)+500)//1000, (len(lvcomments)+500)//1000),0)
tempname = os.path.join(g.getdir("temp"),"oscillators.rle")
g.save(tempname, "rle")
with open(tempname,"r") as f:
    allrle = f.read()
with open(tempname,"w") as f:
    f.write(comments2 + "\n" + allrle)
g.open(tempname)  # this integrates the comments into the currently open pattern file
                  # there still seem to be some issues with keeping the comments after re-saving the file,
                  # but I'll deal with that separately.  Meanwhile:
g.note("Click OK to copy pattern to the clipboard, including comments at the beginning and LifeViewer commands at the end.")
g.setclipstr(comments2 + "\n" + allrle + lvcomments)
예제 #20
0
# Calculates the density of live cells in the current pattern.
# Author: Andrew Trevorrow ([email protected]), March 2006.
# Updated to use exit command, Nov 2006.

import golly as g
from glife import *
from utils import *


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)


pop = popcount(sel=1)
medium = int(len(g.getcells(g.getselrect())) / 3)

density = float(pop) / float(medium) * 100

g.setclipstr(str(density))
g.show('density=%i/100,pop=%i,medium=%i' % (density, pop, medium))
예제 #21
0
while LONG_ENOUGH < len(deltalist) * 4 * sep + 4000:
    LONG_ENOUGH *= 2

ptr = 0
while ptr < len(deltalist):
    mindelta, maxdelta = -100, sep
    newlist = deltalist[:]
    while 1:
        midpoint = int(mindelta + (maxdelta - mindelta) / 2)
        newlist[ptr] = midpoint
        g.show(str([len(deltalist) - ptr, newlist]).replace(" ", ""))
        makerecipe(nongliderpat, zip(recipelist, newlist))
        g.run(LONG_ENOUGH)
        output = g.getrect()
        if len(output) == 0: g.exit("Need a hashable output.")
        newhash = g.hash(output)
        if hash == newhash:
            if maxdelta == midpoint: break
            maxdelta = midpoint
        else:
            if mindelta == midpoint: break
            mindelta = midpoint
    deltalist[ptr] = mindelta + 1  # take the last good one and continue
    makerecipe(nongliderpat, zip(recipelist, deltalist))
    g.fit()
    g.update()
    ptr += 1

g.setclipstr(recipe + "\n\n" + str(deltalist))
g.show("Done.")
예제 #22
0
  parity=1 if s[0]=="O" else 0
  input+=[[int(s[1:]),parity]]
for i,p in input:
  if elbowloc%2==0: # which recipe to use depends on current elbow chirality
    targetlane = i
  else:
    targetlane = -i
  if elbowloc<-48: # -32 doesn't work for the end of the recipe
    move,recipe,parity = posdict[targetlane]
  else:
    move,recipe,parity = negdict[targetlane]
  elbowloc+=move
  adjustedrecipe = recipe[2:] # skip the initial "0"
#  g.note(str([targetlane, move, recipe, parity]))
  if (total+parity+p)%2==1:
    # change the last number in the previous recipe, to flip the parity of the current recipe
    output[-1]+=1
    total+=1
  # now add the current recipe to the total
  for s in adjustedrecipe.split(","): total+=int(s)

  output+=eval("["+adjustedrecipe+"]")
 
# build the resulting recipe and display in a new layer
 
g.setclipstr(str(output).replace("["," ").replace("]","").replace(" ",""))
pat=makerecipe(output[:-1])
g.addlayer()
g.putcells(g.join(elbow,g.transform(pat,5,2)))
g.setalgo("HashLife")
# extract-single-channel-recipe.py
# glider stream should be pointed northwest.  First glider should be in 3o$o$bo! phase, point at (0,0).
# no selection needed -- script works on entire pattern in current universe
#
# For very large single-channel streams, a variant of recognizer.py would be enormously more efficient

import golly as g
count = 0
recipe = []
while int(g.getpop())>0:
  if g.getcell(0,0)==1 and g.getcell(1,0)==1 and g.getcell(2,0)==1 and g.getcell(0,1)==1 and g.getcell(1,2)==1:
    g.setcell(0,0,0)
    g.setcell(1,0,0)
    g.setcell(2,0,0)
    g.setcell(0,1,0)
    g.setcell(1,2,0)
    recipe+=[count]
    count=0
    if len(recipe)%10 == 0:
      g.show(str(len(recipe)))
      g.fit()
      g.update()
  else:
    count+=1
    g.run(1)
g.note("Done.  Click OK to copy results to clipboard.")
g.setclipstr(str(recipe))
g.show(str(len(recipe)))
예제 #24
0
state, nextstate, nextoutput, outputtext = "START", "INITIAL", "Z", ""

g.show(state + " -- " + nextstate + " :: " + instr + "; regs=" +
       str(registers) + " -- 'r' to toggle run mode, any key to step")

check_keyboard()

while 1:

    if nextoutput == "":
        g.show(state + " -- " + nextstate + " :: " + instr + "; regs=" +
               str(registers) + "; mem=" + str(memory))
        g.note(
            "Program reached halt state (because no bit value was returned by any instruction)."
        )
        g.setclipstr(s)
        g.exit()

    state = nextstate + ";" + nextoutput
    # get info from program dictionary, move to next state
    nextstate, instr = program[state]

    # process instructions for current state
    # -- there may be just one instruction,
    #    or several comma-separated instructions
    nextoutput = ""  # if some instruction doesn't set this variable, the program will halt
    for i in instr.split(","):
        # allow stepping or full-speed run from keyboard (toggle "r")
        check_keyboard()

        if i == "NOP":
예제 #25
0
import KBs

import random, re, os

# rulestr=golly.getstring('NTCA number',golly.getclipstr()).split('_')[-1];
kb = KBs.kb_2dntca()
# alias = golly.getrule()
prefix, curr, suffix = KBs.interpret(golly.getrule().split(':'))

rulestr = kb.alias2rulestr(curr)
bitstr = KBs.hex2bin(rulestr, 102)
# assert KBs.bin2hex(bitstr)==rulestr
bitlst = list(bitstr)

idx = random.randrange(102)
flip = {'0': '1', '1': '0'}
bitlst[idx] = flip[bitlst[idx]]
rulestr = KBs.bin2hex(''.join(bitlst))
alias = kb.rulestr2alias(rulestr)

if prefix:
    DIR = golly.getdir('rules')
    fname = os.path.join(DIR, prefix + alias + '.rule')
    with open(fname, 'w') as f:
        print >> f, kb.rulestr2table(rulestr, reverse=1)
newrule = '%s%s:%s' % (prefix, alias, suffix)
golly.note(newrule)
golly.setclipstr(newrule.split(':')[0])

golly.setrule(newrule)
예제 #26
0
            if i < 3:
                g.note(
                    "No spaces in the first 72 characters of this overlength line: '"
                    + line + "'")
                t += line + "\n"
                line = ""
                break
        if i < 3:
            break
        else:
            j = i
            while j > 0:
                j -= 1
                if line[j] == "}": break  # didn't find an open link marker
                if line[j] == "{":
                    if line[j - 1] == " ":
                        i = j - 1
                        break
                    else:
                        g.note(
                            "Found weird formatting:  left curly brace just after non-space character\n"
                            + line)
                        g.exit()
            t += line[:i] + "\n   "
            line = line[i + 1:].lstrip()
            maxlen = 69
    t += line + "\n"

g.note("All done.  Lines processed = " + str(count))
g.setclipstr(t)
예제 #27
0
    if not aline:
        return b
    if not bline:
        return a

    if (value == 1):
        if aline[ii] > bline[ii]:
            return a
        else:
            return b
    else:
        if aline[ii] > bline[ii]:
            return b
        else:
            return a


# p = int(g.getstring('Enter period of pattern', '1'))
p, dxdy = bijoscar(1000)
if dxdy is None:
    if p == 0:
        g.exit('Pattern has died out.')
    else:
        g.exit('Pattern periodicity not detected within 1000 generations.')

canonPatt = sof_canonise(p, dxdy)
g.setclipstr(canonPatt)
g.show('SOF representation of pattern is: ' + canonPatt +
       ' (copied to clipboard).')
예제 #28
0
    cells = g.getcells([x0, y0, l, h])
    allcells.append(cells)

idx = 0
for let in letters:
    x0, y0, l, h = let
    g.new("")
    g.putcells(allcells[idx], -x0)
    allcells[idx] = g.getcells([0, y0, l, h])
    idx += 1


def Write(dic, L, dx=0, dy=0):
    d = 0
    for i in range(len(L)):
        let, dl = dic[L[i]]
        g.putcells(let, dx + d, dy)
        d += dl


dic = {}
for i in range(len(textLet)):
    dic[textLet[i]] = (allcells[i], letters[i][2])

dic[' '] = ([], 5)

g.new("")
Write(dic, "Hello World!")

g.setclipstr(str(dic))
예제 #29
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)
예제 #30
0
    else:
        s += "\n" + url + "\n" + pname + "_synth: found synthesis that has not yet been uploaded."
        start = html.index('name="wpTextbox1">')
        rle = html[start + 18:html.index('!', start + 17) + 1]
        filename = outfolder + pname + "_synth.rle"
        data = pnamedict[pname]
        discoverer, discoveryear = data[2], data[3]
        sourceurl = data[0]
        articlename = sourceurl.replace(
            "https://conwaylife.com/w/index.php?title=",
            "").replace("&action=edit", "")
        url = 'https://conwaylife.com/wiki/' + articlename
        paturl = 'https://www.conwaylife.com/patterns/' + pname + "_synth.rle"
        with open(filename, 'w') as f:
            f.write("#N " + pname + "_synth.rle\n")
            f.write("#C " + url + "\n")
            f.write("#C " + paturl + "\n")
            f.write(rle)
        g.show("Wrote " + filename)

g.note("Done!  Click OK to write exceptions to clipboard.")
g.setclipstr(s + "\nCells files created: " + str(missingcells) + "\nPatterns too big to create cells files, or multistate: " + str(toobigforcells) \
               + "\nIllegal capitalized pnames: " + str(capitalizedpnames) + "\npnames with no RLE header: " + str(noRLEheader) \
               + "\nNo RLE param in infobox: " + str(norleparam) + "\nNo plaintext param in infobox: " + str(noplaintextparam) \
               + "\napgcodes where LifeWiki synth agrees with Catagolue: " + str(apgcodesLWsynthagreeswithC) \
               + "\napgcodes where LifeWiki synth is better than Catagolue: " + str(apgcodesLWsynthbetterthanC) \
               + "\napgcodes where LifeWiki synth is worse than Catagolue: " + str(apgcodesLWsynthworsethanC) \
               + "\napgcodes where LifeWiki synth exists but no Catagolue synth: " +str(apgcodesLWsynthbutnoCsynth) \
               + "\napgcodes where Catagolue synth exists but no LifeWiki synth: " +str(apgcodesnoLWsynthbutCsynth) \
               )
예제 #31
0
   letters = getletters(nlist)
   bestletters = letters
   
   for affine in affinelist:
     altlist = []
     for k in nlist:
       a, b, c = k
       m,n,o,p,q,r,s,t,u = affine
       d = m*a + n*b + o*c
       e = p*a + q*b + r*c
       f = s*a + t*b + u*c
       altlist += [(d,e,f)]
     altletters = getletters(altlist)
     if altletters<bestletters: bestletters = altletters
     # g.note(str(i) + ": " + str(nlist)+ " -- " + bestletters + " // " + str(affine) + " = " + str(altlist) + " :: " + altletters)
   # if bestletters not in isodict:
   #   isodict[bestletters]=1
   # else:
   #   isodict[bestletters]+=1
   # if i%1024==0:
   #   g.show(str(i) + ": " + str(len(isodict)) )
   #   if i>67200000:
   #     g.setclipstr(str(isodict))
   #     g.exit()
   if bestletters == letters:
     isodict[numneighbors]+=1
   if i%1024==0:
     g.show(str(i) + ": " + str(isodict))
g.setclipstr(str(isodict))
예제 #32
0
import golly as g 

def recipe():
	res = ""
	i = 0
	prev = 0 
	
	while True:
		i += 1
		y = int(128 * i) + 1
		cells = g.getcells([-1500+y, y, 2 * 1500, 3])
		
		if len(cells) == 0:
			break 
		
		x = cells[0]
		y = cells[1]
		cur = x - y 
		
		if g.getcell(x + 2, y) == 0:
			res += "O" + str(cur) + " "
		else:
			res += "E" + str(cur - 1) + " "
		
		prev = cur 
		
	return	res
	
g.setclipstr(recipe())
예제 #33
0
def add_string():
    cells = g.getcells(g.getrect())
    n = len(cells)
    result = ""

    for i in range(0, n, 2):
        result += "[%d, %d, %d]" % (cells[i], cells[i + 1], int(g.getgen()))

        if i < n - 2:
            result += ","

    return (result, n / 2)


res = ""
total = 0

for i in range(120):
    resn, voln = add_string()
    res += resn
    total += voln

    if i < 119:
        res += ","

    g.run(1)

g.setclipstr(res)
g.show(str(total))