elif inverse_list != []: for i in notationdict: if not (i[1] in inverse_list) and i.startswith(totalistic_num): result = result + bs + notationdict[i] + ",1" +"\n" else: for i in notationdict: if i.startswith(totalistic_num): result = result + bs + notationdict[i] + ",1" + "\n" 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()
n_neighbors = 4 # order for 4 neighbors is N, W, E, S, C def transition_function ( s ) : return ( s[0] + s[1] + s[2] ) % 5 ''' import golly from glife.RuleTree import * # exec() only works if all lines end with LF, so we need to convert # any Win line endings (CR+LF) or Mac line endings (CR) to LF CR = chr(13) LF = chr(10) try: exec(golly.getclipstr().replace(CR+LF,LF).replace(CR,LF)) MakeRuleTreeFromTransitionFunction( n_states, n_neighbors, transition_function, golly.getdir("rules")+name+".tree" ) # use name.tree to create name.rule (with no icons); # note that if name.rule already exists then we only replace the info in # the @TREE section to avoid clobbering any other info added by the user ConvertTreeToRule(name, n_states, []) golly.setalgo("RuleLoader") golly.setrule(name) golly.show("Created "+golly.getdir("rules")+name+".rule and switched to that rule.") except: import sys import traceback
SRA = Literal("SRA").setParseAction(lambda t: int2binstr(9, length=4)) SRL = Literal("SRL").setParseAction(lambda t: int2binstr(10, length=4)) opcode = MNZ | MLZ | ADD | SUB | AND | OR | XOR | ANT | SL | SRL | SRA lineno = (integer + Literal(".")).setParseAction(lambda t: [int(t[0])]) comment = (Literal(";") + restOfLine).suppress() inst = (lineno + opcode + operand + operand + operand + Optional(comment)).setParseAction(lambda t: [t]) self.program = ZeroOrMore(inst) def parse_string(self, string): return self.program.parseString(string) g.show("Loading code from clipboard...") rawcode = g.getclipstr() g.show("Parsing clipboard...") parser = Parser() parsed = parser.parse_string(rawcode) l_binstring = [] def rev(s): return "".join(reversed(s)) for line in parsed: lineno, opcode, (d_1, n_1), (d_2, n_2), (d_3, n_3) = line
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)
## This script generate an ECA rule and emulate it on a torus of width 200. ## Written by Feng ([email protected]) Feb 2017. import golly alias = golly.getstring('NTCA alias', golly.getclipstr()) ali = alias # rule='0'*102; henseldict = [ 'b0_', 'b1c', 'b1e', 'b2a', 'b2c', 'b3i', 'b2e', 'b3a', 'b2k', 'b3n', 'b3j', 'b4a', 's0_', 's1c', 's1e', 's2a', 's2c', 's3i', 's2e', 's3a', 's2k',
def importNewShips(): newshiptxt = g.getclipstr() status = 'Searching clipboard for new ships ...' Nnew = 0 constructRLE = False errormsg = 'Error: failed to recognise rle pattern. Current pattern string:\n' shiprle = '' global newShipsList for line in newshiptxt.splitlines(): line = line.strip() if constructRLE == False: # Try to import sss format ship newship = sss.parseshipstr(line) if not newship: # Try to import rle format ship if(line[0:4] == 'x = '): # Found beginning of rle formatted pattern if constructRLE == True: g.note(errormsg + rule + shiprle + line) constructRLE = True parts = line.split('=') if len(parts)==4: rulestr = parts[3].strip() elif len(parts)==3: rulestr = 'B3/S23' else: constructRLE = False g.note(errormsg + line) shiprle = '' else: # Try to import sss format ship (just in case rle recognizer is confused) newship = sss.parseshipstr(line) if newship: g.note(errormsg + rule + shiprle + line) # Continue constructing rle pattern string shiprle += line if '!' in line: constructRLE = False newship = (0, rulestr, 0, 0, 0, shiprle) # If ship is in canonical sss format, then analysing it is unnecessary # However, it is worthwhile because not all search scripts analysed # ships consistently. # Need to analyse new ships anyway if importing them from rle. # Only need to canonise if ship is going to be added to collection # For the initial test only need to know minimum population and speed if newship: try: # Ignore ship if rule string does not have Birth and Survival elements # XXX This may miss some ships where the rule string is non-standard and # doesn't reject undesired rules like Generations rulestr = newship[1] if not (rulestr[0] == 'B' and ('/S' in rulestr or '_S' in rulestr)): g.note('Ignoring ship in non-isotropic rule.\n%s' % (newship,)) continue # Ignore B0 ships if "B0" in rulestr: continue minpop, speed, _ = sss.testShip(newship[5], rulestr, MAXGEN) if not speed: g.note('Ship analysis error: speed is empty.\n%s, %s, %s' % (minpop, speed, newship)) continue newShipsList.append( (minpop, rulestr)+speed+(sss.giveRLE(g.getcells(g.getrect())),) ) newship = () Nnew += 1 if (Nnew % 500 == 0): g.show('%s %d ships found.' % (status, Nnew)) except RuntimeError: g.note("Error processing newship, check rule validity:\n" + str(newship)) except: g.note("Error processing newship:\n" + str(newship)) raise status = 'New ships imported, %d ships found. Testing new ships ...' % Nnew g.show(status)
g.exit('The rule should be in LifeHistory.') # 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:
# regex for sss format ships sssFormat = re.compile( r'(\d+), (B[0-9aceijknqrtwyz-]+/S[0-9aceijknqrtwyz-]*), (\d+), (\d+), (\d+), ([0-9ob$]+!)' ) sssPatterns = [] filetypes = "sss Files (*.sss.txt;*.txt)|*.sss.txt;*.txt" sssFile = g.opendialog("Choose spaceship file", filetypes) # Grab a string containing all the sss format patterns if sssFile: with open(sssFile, 'r') as F: sssFileLines = F.readlines() else: sssFileLines = g.getclipstr().splitlines() for line in sssFileLines: m = sssFormat.match(line) if m: # Format: (minpop, 'rulestr', dx, dy, period, 'shiprle') s = m.groups() sssPatterns.append( (int(s[0]), s[1], int(s[2]), int(s[3]), int(s[4]), s[5])) g.new('sss Patterns') g.show('%d patterns imported' % len(sssPatterns)) # For frame rate and timing frameRate = 100 framePeriod = 1.0 / frameRate
n_neighbors = 4 # order for 4 neighbors is N, W, E, S, C def transition_function ( s ) : return ( s[0] + s[1] + s[2] ) % 5 ''' import golly from glife.RuleTree import * # exec() only works if all lines end with LF, so we need to convert # any Win line endings (CR+LF) or Mac line endings (CR) to LF CR = chr(13) LF = chr(10) try: exec(golly.getclipstr().replace(CR + LF, LF).replace(CR, LF)) MakeRuleTreeFromTransitionFunction(n_states, n_neighbors, transition_function, golly.getdir("rules") + name + ".tree") # use name.tree to create name.rule (with no icons); # note that if name.rule already exists then we only replace the info in # the @TREE section to avoid clobbering any other info added by the user ConvertTreeToRule(name, n_states, []) golly.setalgo("RuleLoader") golly.setrule(name) golly.show("Created " + golly.getdir("rules") + name + ".rule and switched to that rule.") except:
import golly import re cliplines = golly.getclipstr().splitlines() data = list(''.join(cliplines[1:])[:-1]) #golly.note(''.join(data)) digitsi = '0123456789.ABCDEFG$' digitso = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_' output = '' while data != list(digitsi[0] * len(data)): dividend = 0 for i in range(len(data)): dividend = dividend * len(digitsi) + digitsi.index(data[i]) data[i] = digitsi[dividend / len(digitso)] dividend = dividend % len(digitso) output += digitso[dividend] # golly.note('{} {}'.format(''.join(data), str(dividend))) #golly.note('https://electroredstoner.github.io/QFT/downloadrle.html?w={}&h={}&d={}'.format(*(re.match('x = (\d+), y = (\d+)', cliplines[0]).groups() + tuple([output[::-1]])))) golly.setclipstr( 'https://electroredstoner.github.io/QFT/downloadrle.html?w={}&h={}&d={}'. format(*(re.match('x = (\d+), y = (\d+)', cliplines[0]).groups() + tuple([output[::-1]])))) golly.show('URL copied to clipboard')
import golly import urllib import re url = urllib.unquote(golly.getclipstr()) try: width = int(re.search(r'"(w|width)":(\d+)', url).group(2)) height = int(re.search(r'"(h|height)":(\d+)', url).group(2)) gridNums = map( int, re.search(r'"(gN|gridNums)":\[(\d+(,\d+)*)\]', url).group(2).split(',')) except AttributeError: golly.exit('Invalid URL given') i = j = 0 rle = 'x = ' + str(width) + ', y = ' + str(height) + ', rule = Varlife\n' grid = [[0] * width for x in range(height)] while gridNums: gridNum = gridNums.pop() blockNum = gridNums.pop() for k in range(blockNum): rle += chr(ord('A') - 1 + gridNum % 4 * 2 + gridNum / 4 % 2) if gridNum % 8 else '.' gridNum = gridNum / 8 i += 1 if i >= width: rle += '$' j += 1 i = 0 golly.setclipstr(rle) golly.show('URL converted successfully')
import golly s = golly.getstring('rules split by ";"', golly.getclipstr()) rs = [x for x in s.split(';') if x] # golly.setrule(rs[0]); L = len(rs) for i in range(100): # golly.run(1) golly.step() golly.setrule(rs[i % L])
# display_ship.py # This script will take a string representing a ship with some additional metadata # and display it in the current layer # It first checks the clipboard for a valid string and then requests input if necessary # There is minimal error checking # ship format: "minPop, rulestr, dx, dy, period, rlestr" import golly as g import sss shipstr = g.getclipstr() ship = sss.parseshipstr(shipstr) if not ship: shipstr = g.getstring('Enter ship string:') ship = sss.parseshipstr(shipstr) if not ship: g.exit('Invalid ship string: ' + shipstr) rulestr = ship[1] shiprle = ship[5] # g.new('') r = g.getrect() if r: g.select(r) g.clear(0) g.select([]) g.setrule(rulestr) g.putcells(g.parse(shiprle)) if not g.visrect(g.getrect()):