def goto(newgen): currgen = int(g.getgen()) if newgen < currgen: # try to go back to starting gen (not necessarily 0) and # then forwards to newgen; note that reset() also restores # algorithm and/or rule, so too bad if user changed those # after the starting info was saved; # first save current location and scale midx, midy = g.getpos() mag = g.getmag() g.reset() # restore location and scale g.setpos(midx, midy) g.setmag(mag) # current gen might be > 0 if user loaded a pattern file # that set the gen count currgen = int(g.getgen()) if newgen < currgen: g.error("Can't go back any further; pattern was saved " + "at generation " + str(currgen) + ".") return if newgen == currgen: return oldsecs = time() # before stepping we advance by 1 generation, for two reasons: # 1. if we're at the starting gen then the *current* step size # will be saved (and restored upon Reset/Undo) rather than a # possibly very large step size # 2. it increases the chances the user will see updates and so # get some idea of how long the script will take to finish # (otherwise if the base is 10 and a gen like 1,000,000,000 # is given then only a single step() of 10^9 would be done) g.run(1) currgen += 1 # use fast stepping (thanks to PM 2Ring) oldstep = g.getstep() for i, d in enumerate(intbase(newgen - currgen, g.getbase())): if d > 0: g.setstep(i) for j in xrange(d): if g.empty(): g.show("Pattern is empty.") return g.step() newsecs = time() if newsecs - oldsecs >= 1.0: # do an update every sec oldsecs = newsecs g.update() g.setstep(oldstep)
def envelope (): # draw stacked layers using same location and scale g.setoption("stacklayers", 1) g.show("Hit escape key to stop script...") while True: g.run(1) if g.empty(): g.show("Pattern died out.") break # copy current pattern to envelope layer; # we temporarily disable event checking so thumb scrolling # and other mouse events won't cause confusing changes currpatt = g.getcells(g.getrect()) g.check(0) g.setlayer(envindex) g.putcells(currpatt) g.setlayer(currindex) g.check(1) step = 1 exp = g.getstep() if exp > 0: step = g.getbase()**exp if int(g.getgen()) % step == 0: # display all 3 layers (envelope, start, current) g.update()
def envelope(): # draw stacked layers using same location and scale g.setoption("stacklayers", 1) g.show("Hit escape key to stop script...") while True: g.run(1) if g.empty(): g.show("Pattern died out.") break # copy current pattern to envelope layer; # we temporarily disable event checking so thumb scrolling # and other mouse events won't cause confusing changes currpatt = g.getcells(g.getrect()) g.check(0) g.setlayer(envindex) g.putcells(currpatt) g.setlayer(currindex) g.check(1) step = 1 exp = g.getstep() if exp > 0: step = g.getbase()**exp if int(g.getgen()) % step == 0: # display all 3 layers (envelope, start, current) g.update()
def GotoLimited(gen, power): g.setbase(8) g.setstep(power) while gen > int(g.getgen()) + g.getbase()**power: g.step() g.update() goto(gen)
def HasEdgeShooter(minx): rect = g.getrect() if len(rect) == 0: return -1 y = rect[1] + rect[3] if y < 100: return -1 if rect[2] > 120: return -1 g.run(4) rect = g.getrect() if y + 2 == rect[1] + rect[3]: maxX = -10000 minL = 10000 minY = 10000 for i in xrange(0, 4): g.run(1) rect = g.getrect() curCells = g.getcells([rect[0], rect[1] + rect[3] - 10, rect[2], 11]) curx, cury = FindRightMost(curCells) curL = len(curCells) if curL <= minL: minL = curL if curx > maxX or (curx == maxX and cury < minY): maxX = curx minY = cury parity = (int(g.getgen()) % 4) + ((cury - curx + 1000000)% 2) * 4 if curL == 22: parity += 8 if curL == 26: parity += 16 if minx - 2 > maxX: cells = g.getcells([-100, -100, 200, 200]) for i in xrange(1, len(cells), 2): if cells[i - 1] - 2 < maxX: return -1 return parity return -1
def run_patt(known_cells): global patt_count, meth_count g.new("PlutoniumSearch") g.reset() g.update() patt_count += 1 #patt = g.parse(known_cells + "!") patt = g.parse(known_cells[1:] + "!") #g.note(known_cells[1:] + "!") g.putcells(patt) g.update() hashlist = {} for gene in range(999): if g.empty(): break if g.hash(g.getrect()) in hashlist: p = int(g.getgen()) - hashlist[g.hash(g.getrect())] if not p in boring_periods: g.reset() g.save("p" + str(p) + "_" + str(cnt[p]) + ".rle", "rle") cnt[p] += 1 break else: hashlist[g.hash(g.getrect())] = int(g.getgen()) g.run(1) """ except: # Pattern dies if int(g.getgen()) > min_lifespan: meth_count += 1 newlifespan = int(g.getgen()) g.new("Saving methuselah") g.putcells(patt) try: g.save("diehard-" + str(newlifespan) + ".rle", "rle") except: pass g.update() #max_final_pop = newpop break""" #g.warn(str(hashlist)) g.show(str(patt_count) + "/" + str(2**(bx * by)))
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)
def gt_setup(gen): currgen = int(g.getgen()) # Remove leading '+' or '-' if any, and convert rest to int or long if gen[0] == '+': n = int(gen[1:]) newgen = currgen + n elif gen[0] == '-': n = int(gen[1:]) if currgen > n: newgen = currgen - n else: newgen = 0 else: newgen = int(gen) if newgen < currgen: # try to go back to starting gen (not necessarily 0) and # then forwards to newgen; note that reset() also restores # algorithm and/or rule, so too bad if user changed those # after the starting info was saved; # first save current location and scale midx, midy = g.getpos() mag = g.getmag() g.reset() # restore location and scale g.setpos(midx, midy) g.setmag(mag) # current gen might be > 0 if user loaded a pattern file # that set the gen count currgen = int(g.getgen()) if newgen < currgen: g.error("Can't go back any further; pattern was saved " + "at generation " + str(currgen) + ".") return 0 return newgen - currgen elif newgen > currgen: return newgen - currgen else: return 0
def AdaptiveGoto(hwssRecipe, enablePrinting=True): #g.setrule("LifeHistory") fense50 = g.parse( "F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F!" ) helixD = CalcHelix(hwssRecipe) curgen = -helixD * 2 curgen += 2 * distForward goto(curgen) g.setbase(8) g.setstep(3) delta = 10 lastmaxi = delta idx = 0 for i in hwssRecipe: if enablePrinting and (100 * (idx + 1)) / len(hwssRecipe) != ( 100 * idx) / len(hwssRecipe): percent = (100 * (idx + 1)) / len(hwssRecipe) g.update() g.show("Iterating forward progress " + str(percent) + "%") curgen += 2 * distForward idx += 1 while int(g.getgen()) < curgen: g.step() if i == 'SKIP': continue if i > lastmaxi: g.select([fenseX, helixD + fenseY + lastmaxi - delta, 1, delta]) g.clear(0) lastmaxi += delta #g.update() if i < lastmaxi - delta: g.putcells(fense50, fenseX, helixD + fenseY + lastmaxi - 2 * delta) lastmaxi -= delta
def AdaptiveGoto(hwssRecipe, enablePrinting = True): #g.setrule("LifeHistory") fense50 = g.parse("F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F!") helixD = CalcHelix(hwssRecipe) curgen = -helixD * 2 curgen += 2 * distForward goto(curgen) g.setbase(8) g.setstep(3) delta = 10 lastmaxi = delta idx = 0 for i in hwssRecipe: if enablePrinting and (100 * (idx + 1)) / len(hwssRecipe) != (100 * idx) / len(hwssRecipe): percent = (100 * (idx + 1)) / len(hwssRecipe) g.update() g.show("Iterating forward progress " + str(percent) + "%") curgen += 2 * distForward idx += 1 while int(g.getgen()) < curgen: g.step() if i == 'SKIP': continue if i > lastmaxi: g.select([fenseX, helixD + fenseY + lastmaxi - delta, 1, delta]) g.clear(0) lastmaxi += delta #g.update() if i < lastmaxi - delta: g.putcells(fense50, fenseX, helixD + fenseY + lastmaxi - 2 * delta) lastmaxi -= delta
def AdaptiveGoto(hwssRecipe): #g.setrule("LifeHistory") fense50 = g.parse("F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F$F!") helixD = -step * len(hwssRecipe) - 1000 while helixD % 7500 != 0: helixD -= 1 curgen = -helixD * 2 curgen += 2 * distForward goto(curgen) g.setstep(3) delta = 10 lastmaxi = delta for i in hwssRecipe: curgen += 2 * distForward while int(g.getgen()) < curgen: g.step() if i == 'SKIP': continue if i > lastmaxi: g.select([240, helixD + fenseY + lastmaxi - delta, 1, delta]) g.clear(0) lastmaxi += delta #g.update() if i < lastmaxi - delta: g.putcells(fense50, 240, helixD + fenseY + lastmaxi - 2 * delta) lastmaxi -= delta
def get_pop(numsteps=44100, x=256, y=256): if numsteps < 1: g.exit("numsteps must be greater than 0.") randfill(x, y) poplist = [int(g.getpop())] extinction = sys.maxint rule = g.getrule() oldsecs = time.time() for i in xrange(numsteps - 1): if g.empty(): extinction = int(g.getgen()) break g.step() poplist.append(int(g.getpop())) newsecs = time.time() if newsecs - oldsecs >= 1.0: oldsecs = newsecs g.show("Rule {}, Step {} of {}".format(rule, i + 1, numsteps)) return (poplist, extinction)
import hashlib rule=g.getrule() ruleB=rule.split('/')[0][1:] ruleS=rule.split('/')[1][1:] S=['S'] B=['B'] for i in range(9): if not str(i) in ruleB: S.append(str(8-int(i))) if not str(i) in ruleS: B.append(str(8-int(i))) B=''.join(B) S=''.join(S) gen=int(g.getgen()) rules=['',''] invrule='/'.join([B,S]) if str(0) not in ruleB: tp=rule rule=invrule invrule=tp rules[gen%2]=rule; rules[(gen+1)%2]=invrule; # g.note(rule) #g.setrule(invrule) speed=2 rules=[rule,invrule]
def oscillating(): # return True if the pattern is empty, stable or oscillating # first get current pattern's bounding box csel = g.getselrect() g.shrink() prect = g.getselrect() g.select(csel) pbox = rect(prect) if pbox.empty: g.show("The pattern is empty.") return True # get current pattern and create hash of "normalized" version -- ie. shift # its top left corner to 0,0 -- so we can detect spaceships and knightships ## currpatt = pattern( g.getcells(prect) ) ## h = hash( tuple( currpatt(-pbox.left, -pbox.top) ) ) # use Golly's hash command (3 times faster than above code) h = g.hash(prect) # check if outer-totalistic rule has B0 but not S8 rule = g.getrule().split(":")[0] hasB0notS8 = rule.startswith("B0") and (rule.find("/") > 1) and not rule.endswith("8") # determine where to insert h into hashlist pos = 0 listlen = len(hashlist) while pos < listlen: if h > hashlist[pos]: pos += 1 elif h < hashlist[pos]: # shorten lists and append info below del hashlist[pos:listlen] del genlist[pos:listlen] del poplist[pos:listlen] del boxlist[pos:listlen] break else: # h == hashlist[pos] so pattern is probably oscillating, but just in # case this is a hash collision we also compare pop count and box size if (pbox.wd == boxlist[pos].wd) and \ (pbox.ht == boxlist[pos].ht): # (int(g.getpop()) == poplist[pos]) period = int(g.getgen()) - genlist[pos] if hasB0notS8 and (period % 2 > 0) and (pbox == boxlist[pos]): # ignore this hash value because B0-and-not-S8 rules are # emulated by using different rules for odd and even gens, # so it's possible to have identical patterns at gen G and # gen G+p if p is odd return False if period == 1: if pbox == boxlist[pos]: g.show("The pattern is stable.") else: show_spaceship_speed(1, 0, 0) elif pbox == boxlist[pos]: g.show("Oscillator detected (period = " + str(period) + ")") else: deltax = abs(boxlist[pos].x - pbox.x) deltay = abs(boxlist[pos].y - pbox.y) show_spaceship_speed(period, deltax, deltay) return True else: # look at next matching hash value or insert if no more pos += 1 # store hash/gen/pop/box info at same position in various lists hashlist.insert(pos, h) genlist.insert(pos, int(g.getgen())) poplist.insert(pos, int(g.getpop())) boxlist.insert(pos, pbox) return False
def main(step=1, start=0): global bound, expand, duration # get selection and set to boundary bound = g.getselrect() if duration == None: duration = int(g.getgen()) if isReset: g.reset() if len(bound) == 0: g.note("No selection.") g.exit() # get current Golly states bound[0] -= expand bound[1] -= expand bound[2] += expand * 2 bound[3] += expand * 2 left = bound[0] top = bound[1] width = bound[2] height = bound[3] palette = getPalette() cells = g.getcells(bound) isMultiStates = len(cells) % 2 == 1 cellW = 3 if isMultiStates else 2 # create image and destination directory dstDir = "%s/%s" % (exportDir, name) if not os.path.exists(dstDir): os.makedirs(dstDir) # else: # g.note( "destination folder already exists" ) # g.exit() # log( cells ) for i in xrange(duration): g.show("Processing... %d / %d" % (i + 1, duration)) g.run(1) g.update() cells = g.getcells(bound) # create image img = Image.new("RGB", (width, height)) cellLen = int(floor(len(cells) / cellW) * cellW) for i in xrange(0, cellLen, cellW): x = cells[i] y = cells[i + 1] state = cells[i + 2] if isMultiStates else 1 img.putpixel((x - left, y - top), palette[state]) # save gen = int(g.getgen()) img.save("%s/%s_%08d.png" % (dstDir, name, gen))
def oscillating(): # return True if the pattern is empty, stable or oscillating # first get current pattern's bounding box prect = g.getrect() pbox = rect(prect) if pbox.empty: g.show("The pattern is empty.") return True # get current pattern and create hash of "normalized" version -- ie. shift # its top left corner to 0,0 -- so we can detect spaceships and knightships ## currpatt = pattern( g.getcells(prect) ) ## h = hash( tuple( currpatt(-pbox.left, -pbox.top) ) ) # use Golly's hash command (3 times faster than above code) h = g.hash(prect) # check if outer-totalistic rule has B0 but not S8 rule = g.getrule().split(":")[0] hasB0notS8 = rule.startswith("B0") and (rule.find("/") > 1) and not rule.endswith("8") # determine where to insert h into hashlist pos = 0 listlen = len(hashlist) while pos < listlen: if h > hashlist[pos]: pos += 1 elif h < hashlist[pos]: # shorten lists and append info below del hashlist[pos : listlen] del genlist[pos : listlen] del poplist[pos : listlen] del boxlist[pos : listlen] break else: # h == hashlist[pos] so pattern is probably oscillating, but just in # case this is a hash collision we also compare pop count and box size if (int(g.getpop()) == poplist[pos]) and \ (pbox.wd == boxlist[pos].wd) and \ (pbox.ht == boxlist[pos].ht): period = int(g.getgen()) - genlist[pos] if hasB0notS8 and (period % 2 > 0) and (pbox == boxlist[pos]): # ignore this hash value because B0-and-not-S8 rules are # emulated by using different rules for odd and even gens, # so it's possible to have identical patterns at gen G and # gen G+p if p is odd return False if period == 1: if pbox == boxlist[pos]: g.show("The pattern is stable.") else: show_spaceship_speed(1, 0, 0) elif pbox == boxlist[pos]: g.show("Oscillator detected (period = " + str(period) + ")") else: deltax = abs(boxlist[pos].x - pbox.x) deltay = abs(boxlist[pos].y - pbox.y) show_spaceship_speed(period, deltax, deltay) return True else: # look at next matching hash value or insert if no more pos += 1 # store hash/gen/pop/box info at same position in various lists hashlist.insert(pos, h) genlist.insert(pos, int(g.getgen())) poplist.insert(pos, int(g.getpop())) boxlist.insert(pos, pbox) return False
cells = g.getcells([rect[0], rect[1], rect[2], 4 * distBack]) g.new("") g.putcells(cells) for i in xrange(4): cRecipe = FindWssByDirection(True, distForward) x1, y1, id1 = cRecipe[0] ConvertToRelative(cRecipe, distForward) if str(forwardRecipe) == str(cRecipe): break g.run(1) dgen = int(g.getgen()) cells = g.getcells(g.getrect()) dx = x1 - x0 dy = y1 - y0 g.new("") g.putcells(cells, -dx, -dy) SaveBackwardSalvoData(dir) #''' #This code creates the Head of the caterloopillar recipes.Reset()
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() g.update() g.show("Step %i of %i" % (i + 1, numsteps)) fit_if_not_visible() # save some info before we switch layers
"Red is on the left and blue is on the right.\n" + \ "The file names are in the header of the main window.\n" + \ "Drag this note to a new location if it is blocking your view.\n\n" + \ "Red seed directory: " + head1 + "\n" + \ "Red seed file: " + tail1 + "\n" + \ "Red seed size: {} x {}\n".format(seed1.xspan, seed1.yspan) + \ "Red seed density: {:.4f} ({} ones)\n\n".format(seed1.density(), \ seed1.count_ones()) + \ "Blue seed directory: " + head2 + "\n" + \ "Blue seed file: " + tail2 + "\n" + \ "Blue seed size: {} x {}\n".format(seed2.xspan, seed2.yspan) + \ "Blue seed density: {:.4f} ({} ones)\n\n".format(seed2.density(), \ seed2.count_ones()) + \ "Select OK to begin the competition.\n") # while (int(g.getgen()) < g_time): g.run(1) # run for 1 step without displaying g.update() # now display # [count1, count2] = mfunc.count_pops(g) # see who won if (count1 > count2): result = "Red won! Red: {}. Blue: {}.\n\n".format(count1, count2) elif (count2 > count1): result = "Blue won! Red: {}. Blue: {}.\n\n".format(count1, count2) else: result = "Tie! Red: {}. Blue: {}.\n\n".format(count1, count2) # # Note that s2 is blue, which means it contains twos, not ones. # Thus we use seed2, which is red, for density() and count_ones(). # message = result + \
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() g.update() g.show("Step %i of %i" % (i+1, numsteps)) fit_if_not_visible() # save some info before we switch layers
# para quem enviaremos as msgs OSC END_SERV = '127.0.0.1' PORTA_SERV = 9000 # criamos um cliente OSC e enviamos a mensagem com as céluas cliente = osc.OSCClient() cliente.connect((END_SERV, PORTA_SERV)) # reinicia tudo (pattern, contador de gerações, ...) g.reset() i = 0 while True: # mostramos no status a geração atual g.show("Geração: %s" % (int(g.getgen()) + 1)) # pegamos todas as células do retângulo atual mostrado na tela celulas = g.getcells(g.getrect()) # criamos uma msg OSC e enviamos usando o cliente OSC msg = osc.OSCMessage() msg.setAddress("/golly") msg.append(celulas) cliente.send(msg) # avança N gerações g.run(1) # atualiza desenho g.update() # espera um segundo
# wd=soupwd*pbox.wd # ht=soupwd*pbox.ht # soupsel=[-int(wd/2),-int(ht/2),wd,ht] wd = tilewd * pbox.wd ht = tilewd * pbox.ht boxsel = [-int(wd / 2), -int(wd / 2), wd, ht] randfill_mash(boxsel, density) while not oscillating(): t3 = time() g.run(1) t4 = time() if t4 - t3 > 1: break if int(g.getgen()) > gen_thres: break event = g.getevent() if event.startswith("key"): evt, ch, mods = event.split() if ch == "q": out = 1 break if ch == "n": next = 1 break t2 = time() if not g.getgen() == '0': longlist.append(m.log(int(g.getgen()), 10)) poplist.append(popcount()) timelist.append(t2 - t1)
def main( step = 1, start = 0 ): global bound, expand, duration # get selection and set to boundary bound = g.getselrect() if duration == None: duration = int( g.getgen() ) if isReset: g.reset() if len( bound ) == 0: g.note( "No selection." ) g.exit() # get current Golly states if bound == None: bound[ 0 ] -= expand bound[ 1 ] -= expand bound[ 2 ] += expand * 2 bound[ 3 ] += expand * 2 left = bound[ 0 ] top = bound[ 1 ] width = bound[ 2 ] height = bound[ 3 ] palette = getPalette() cells = g.getcells( bound ) isMultiStates = len(cells) % 2 == 1 cellW = 3 if isMultiStates else 2 # create image and destination directory dstDir = "%s/%s" % (exportDir, name) if not os.path.exists( dstDir ): os.makedirs( dstDir ) # else: # g.note( "destination folder already exists" ) # g.exit() # log( cells ) for i in xrange( duration ): g.show( "Processing... %d / %d" % (i+1, duration) ) g.run( 1 ) g.update() cells = g.getcells( bound ) # create image img = Image.new( "RGB", ( width, height ) ) cellLen = int( floor( len(cells)/cellW ) * cellW ) for i in xrange( 0, cellLen, cellW ): x = cells[ i ] y = cells[ i + 1 ] state = cells[ i + 2 ] if isMultiStates else 1 img.putpixel( (x-left, y-top), palette[state] ) # save gen = int( g.getgen() ) img.save( "%s/%s_%08d.png" % (dstDir, name, gen) )