def PlaceReadingHeads(hwssRecipe): g.new("") g.setrule("LifeHistoryNoMark") if directionType == "B": for y in xrange(-3 * len(hwssRecipe), 1): MakeBackwardSalvo(step, 0, distBack * y, step * len(hwssRecipe) + 100, y == 0, y == 0) MakeBackwardRecipe(step, 0, 0, hwssRecipe) else: helixD = -step * len(hwssRecipe) - 1000 while helixD % 7500 != 0: helixD -= 1 for y in xrange(0, 3 * len(hwssRecipe) + 1): MakeForwardSalvo(step, 0, distForward * y, helixD, y == 0, y == 0) MakeForwardRecipe(helixD, step, 0, 0, hwssRecipe) cells = [] for i in xrange(fenseY, -helixD + 201): cells.append(240) cells.append(i + helixD) cells.append(6) g.putcells(cells)
def rule_boring(): explode = 0 die = 0 num_trial = 8 for i in range(num_trial): g.new("") g.select([0, 0, 32, 32]) g.randfill(50) g.run(16) if int(g.getpop()) == 0: die += 1 continue r = g.getrect() if r[2] > 60 and r[3] > 60: explode += 1 continue return -1 if explode == num_trial: return 0 if die == num_trial: return 1 return -1
def slideshow(): oldalgo = g.getalgo() oldrule = g.getrule() message = "Hit space to continue or escape to exit the slide show..." g.show(message) for root, dirs, files in os.walk(g.getdir("app") + "Patterns"): for name in files: if name.startswith("."): # ignore hidden files (like .DS_Store on Mac) pass else: g.new("") g.setalgo("QuickLife") # nicer to start from this algo fullname = join(root, name) g.open(fullname, False) # don't add file to Open/Run Recent submenu g.update() if name.endswith(".lua") or name.endswith(".py"): # reshow message in case it was changed by script g.show(message) while True: event = g.getevent() if event == "key space none": break g.doevent(event) # allow keyboard/mouse interaction sleep(0.01) # avoid hogging cpu # if all patterns have been displayed then restore original algo and rule # (don't do this if user hits escape in case they want to explore pattern) g.new("untitled") g.setalgo(oldalgo) g.setrule(oldrule)
def GunArea(cells, curGunPeriod): maxBox = [] minpop = -100000 for i in xrange(0, curGunPeriod, 4): g.new(str(i)) g.putcells(g.evolve(cells, i)) g.setbase(8) g.setstep(3) g.step() g.step() edgeGlider = EdgeGlider() while PerformDelete(edgeGlider, curGunPeriod): edgeGlider = DevolveGlider(edgeGlider, curGunPeriod) for j in xrange(0, 4): if g.getpop() > minpop: maxpop = g.getpop() maxpopgun = g.getcells(g.getrect()) maxBox = AppendBox(maxBox, g.getrect()) g.run(1) return [BoxValue(maxBox), maxpopgun, maxBox]
def GunArea(cells, curGunPeriod): maxBox = [10000, 10000, -1000, -1000] for i in xrange(0, curGunPeriod, 4): g.new(str(i)) g.putcells(g.evolve(cells, i)) g.setbase(8) g.setstep(3) g.step() g.step() g.step() g.step() edgeGlider = EdgeGlider() while PerformDelete(edgeGlider, curGunPeriod): edgeGlider = DevolveGlider(edgeGlider, curGunPeriod) for j in xrange(0, 4): maxBox = AppendBox(maxBox, g.getrect()) g.run(1) if i == 0: somegun = g.getcells(g.getrect()) return [BoxValue(maxBox), somegun, maxBox]
def PlaceRecipeList(recipes): if len(recipes) == 0: return g.new("") dx = 0 recipes.sort(key=lambda f: str(f[3])) curF = str(recipes[0][3]) f = open(destinationPath + str(len(recipes)) + curF + ".txt",'w') for res in recipes: recipe = res[0] x1 = res[1] y1 = res[2] slL = res[3] g.putcells(blck, dx, 0) d = 0 for r in recipe: g.putcells(gld, 40 + d * 256 + dx, 40 + r + d * 256) d += 1 dx += 256 if curF != str(slL): f.close() curF = str(slL) f = open(destinationPath + str(len(recipes)) + curF + ".txt",'w') f.write("{0},{1}:".format(x1, y1) + str(recipe).strip("]").strip("[") + "\n")
def SaveForwardSalvoData(dir): g.new("") MakeBackwardSalvo(step, 0, 0, 0, True, True) rectB = g.getrect() g.new("") MakeForwardSalvo(step, 0, 0, 0, True, True) rectF = g.getrect() g.run(3) forwardRecipe = FindWssByDirection(True, distForward) forwardRecipe.reverse() fRecipe = [] dx = rectB[0] - (rectF[0] + rectF[2]) - 100 dx = int(dx / 8) * 8 for i in xrange(0, len(forwardRecipe)): x, y, d = forwardRecipe[i] fRecipe.append((x + dx, y + 1, d)) pickle.dump( fRecipe, open(path.join(dir, str(step) + "_ForwardSalvoAuto.pkl"), "wb"))
def slideshow (): oldalgo = g.getalgo() oldrule = g.getrule() message = "Hit space to continue or escape to exit the slide show..." g.show(message) for root, dirs, files in os.walk(g.getdir("app") + "Patterns"): for name in files: if name.startswith("."): # ignore hidden files (like .DS_Store on Mac) pass else: fullname = join(root, name) g.open(fullname, False) # don't add file to Open/Run Recent submenu g.update() if name.endswith(".pl") or name.endswith(".py"): # reshow message in case it was changed by script g.show(message) while True: event = g.getevent() if event == "key space none": break g.doevent(event) # allow keyboard/mouse interaction sleep(0.01) # avoid hogging cpu if "CVS" in dirs: dirs.remove("CVS") # don't visit CVS directories # if all patterns have been displayed then restore original algo and rule # (don't do this if user hits escape in case they want to explore pattern) g.new("untitled") g.setalgo(oldalgo) g.setrule(oldrule)
def GunPlacer(gunCollection): g.new("") for i in xrange(0, len(gunCollection)): g.putcells(gunCollection[i], 0, 0); PlaceNumber(i + 14, -150, i * 650)
def make(blocks): g.new("circuit") for block in blocks: fname = "blocks/{}.mc".format(block[0]) paste(g, fname, *transfo(block[1], block[2])) g.fit() g.save("circuit.mc", "mc")
def randtopo(num, low, high): hashlist = [] topolist = [] arealist = [] i = 0 while i < num: size = random.choice(range(low, high + 1)) area = size * size sel = [size, size, size, size] g.new('') randfill(sel, (1 + random.randrange(area)) * int(100 / area)) if g.empty(): continue h = g.hash(g.getrect()) if h in hashlist: continue else: hashlist.append(h) pbox = g.getrect() actarea = pbox[2] * pbox[3] clist = g.getcells(g.getrect()) g.store(clist, dir + 'topo_area%i_hash%i' % (actarea, h)) clist.insert(0, pbox[2]) #prepare for tiling clist.insert(1, pbox[3]) topolist.append(clist) arealist.append(actarea) i = i + 1 continue return [topolist, hashlist, arealist]
def PrepareList(cells): g.new("") g.putcells(cells) cells = g.getcells(g.getrect()) g.new("") g.putcells(cells, -cells[0], -cells[1]) c = g.getcells(g.getrect()) result = [] for i in xrange(0, len(c), 2): x = c[i] y = c[i + 1] for dx in xrange(-1, 2): for dy in xrange(-1, 2): val = g.getcell(x + dx, y + dy) if (x + dx, y + dy, val) in result: continue result.append((x + dx, y + dy, val)) random.shuffle(result) return result
def PrepareList(cells): g.new("") g.putcells(cells) cells = g.getcells(g.getrect()) g.new("") g.putcells(cells, -cells[0], -cells[1]) c = g.getcells(g.getrect()) result = [] for i in xrange(0, len(c), 2): x = c[i] y = c[i + 1] for dx in xrange(-1,2): for dy in xrange(-1, 2): val = g.getcell(x + dx, y + dy) if (x + dx, y + dy, val) in result: continue result.append((x + dx, y + dy, val)) random.shuffle(result) return result
def SnakeReader(let): g.new("") g.setrule("LifeHistory") cl = let2cells[let][0] g.putcells(cl) emptyline = True dir = 1 rect = g.getrect() y0 = 0 h = rect[1] + rect[3] + 2 l = rect[0] + rect[2] + 3 x0 = rect[0] - 1 y = y0 x = x0 code = "" while True: y += dir if y < y0: if emptyline == True: code += "Y+;" break dir = 1 y += dir code += "Y+;" x += 1 emptyline = True elif y >= y0 + h: dir = -1 y += dir code += "Y+;" x += 1 emptyline = True else: if dir == -1: code += "X-;" else: code += "X+;" if g.getcell(x, y) != 0: code += "SET;" emptyline = False if x >= x0 + l: break for i in range(h): code = code.replace("X+;Y+;X-;", "Y+;") code = code.replace("X-;Y+;X+;", "Y+;") return code
def makerecipe(background, gliderlist): g.new("Recipe") g.putcells(background) offset = max(background[1::2]) + 4 for glider, delta in gliderlist: clist, lane = glider g.putcells(clist, (lane + 1) // 2 + offset, offset) offset += delta
def EvolveRecipe(recipe): g.new("") g.setstep(3) g.putcells(blck) for r in recipe: g.putcells(gld, 40, 40 + r) g.step() g.step()
def main(): apgcode = canonise() if not apgcode: g.warn( 'Failed to detect periodic behaviour after {} generations.'.format( MAXPERIOD)) # 2G collisions if apgcode in twoGcols: cols = twoGcols[apgcode] else: cols = [] # 3G and 4G collisions for cFile in compFiles: with open(cFile) as cF: found_code = False for l in cF: line = l.strip() if not found_code: if line == apgcode: found_code = True continue elif '>' in line: in_code, gstr, _ = line.split(">") if in_code: g.warn( 'Non-empty starting target in glider collision - Not implemented' ) else: cols.append(gstr) else: break Ncols = len(cols) if Ncols: try: cols = [reconstruct(col) for col in cols] except Exception: g.note(str(cols)) g.new("solutions") g.show("{} collisions found".format(Ncols)) g.setname(apgcode) if Ncols <= 20: N = 5 else: N = math.ceil(math.sqrt(Ncols)) + 1 offset = 100 for i, col in enumerate(cols): g.putcells(col, int((i % N) * offset), int((i // N) * offset)) g.fit() else: g.note( "No glider collisions found for constellation {}. Better luck next time" .format(apgcode))
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
def trygliders(ginfo): gdistance = ginfo / 4 phase = ginfo % 4 bstatus = boxstatus pstatus = popstatus for num in xrange(8): tlist = form(celllist, num) rect = boxform(fullrect, num) g.new('') g.putcells(tlist) gx = rect[0] - 3 - gdistance gy = rect[1] - 3 - gdistance for w in xrange(rect[2] + 5): g.new('') g.putcells(tlist) g.putcells(glider[phase], gx + w, gy) g.fit() g.update() for gen in xrange(1000): g.run(1) if int(g.getpop()) <= 2: g.new('') g.show("Found clean glider destruction.") status = 0, num, phase, [gx + w, gy] putcells_and_fit(result(celllist, status)) g.exit() box = g.getrect()[2:] # Checking the bounding box size and population against the current lowest found. if reduce(mul, box) < reduce(mul, bstatus[0]): bstatus = (box, num, phase, [gx + w, gy]) pop = int(g.getpop()) if pop < pstatus[0]: pstatus = (pop, num, phase, [gx + w, gy]) # Show results if the user presses certain keys event = g.getevent() if event.startswith("key x"): g.new('') put_result_pair(celllist, bstatus, pstatus) g.select(g.getrect()) g.copy() g.select([]) g.note( "Minimum bounding box and population collisions copied to clipboard." ) if event.startswith("key q"): g.new('') g.show("Search stopped.") put_result_pair(celllist, bstatus, pstatus) g.fit() g.exit() g.show( "Searching for a 1-glider destruction... press <x> to copy minimum bounding box and population results to clipboard; press <q> to quit. Stats: minimum bounding box %dx%d, minimum population %d" % (bstatus[0][0], bstatus[0][1], pstatus[0])) return bstatus, pstatus
def find_best_selection(): r = g.getrect() all = g.getcells(r) sep = 1 # - run the pattern for 4096 ticks, get the new settled pattern # - try XORing new pattern with original pattern for every possible offset up to 512 # - one of the offsets should give the lowest total population # (will probably decrease the population instead of increasing it, # unless what is being built is a prolific puffer or gun or some such) bestscore, bestsep = len(all), -1 # = population * 2 allplus4096 = g.evolve(all, 4096) g.addlayer() while sep <= 512: g.show("Finding stage spacing -- testing " + str(sep)) g.new("sep=" + str(sep)) g.putcells(all) g.putcells(allplus4096, sep, 0, 1, 0, 0, 1, "xor") score = int(g.getpop()) if bestscore > score: bestscore, bestsep = score, sep sep += 1 g.dellayer() sep = bestsep g.show("found separation: " + str(sep)) bestblockscore, bestoffset = -999999, -1 for offset in range(sep): g.select([r[0] - offset, r[1], sep, r[3]]) g.update() blockscore = 0 for blockx in range(r[0] - offset, r[0] + r[2], sep): g.select([blockx, r[1], sep, r[3]]) blockrect = g.getselrect() block = g.getcells(blockrect) if len( block ) == 0: # ran into empty block, this must not be the right separation g.exit("Invalid pattern format found at separation = " + str(sep) + ": selected block is empty.") g.shrink(1) shrunkblockrect = g.getselrect() leftdiff = shrunkblockrect[0] - blockrect[0] rightdiff = (blockrect[0] + blockrect[2]) - (shrunkblockrect[0] + shrunkblockrect[2]) blockscore += leftdiff + rightdiff if leftdiff < 10: blockscore -= (10 - leftdiff)**2 if rightdiff < 10: blockscore -= (10 - rightdiff)**2 if blockscore > bestblockscore: bestblockscore, bestoffset = blockscore, offset g.select([r[0] - bestoffset, r[1], r[2] + offset, r[3]]) return sep
def SaveForwardSalvoData(): g.new("") MakeForwardSalvo(step, 0, 0, 0, True, True) g.run(3) forwardRecipe = FindWssByDirection(True, 750) forwardRecipe.reverse() fRecipe = [] for i in xrange(0, len(forwardRecipe)): x, y, d = forwardRecipe[i] fRecipe.append((x - 400, y + 1, d)) pickle.dump(fRecipe, open(path.join(dir, str(step) + "_ForwardSalvo.pkl"), "wb"))
def PlaceReadingHeads(hwssRecipe): global fenseX g.new("") g.setrule("LifeHistoryNoMark") if directionType == "B": dist = int(1.5 * len(hwssRecipe) / speed) for y in xrange(-dist, 1): MakeBackwardSalvo(step, 0, distBack * y, step * len(hwssRecipe) + 100, y == 0, y == 0) MakeBackwardRecipe(step, 0, 0, hwssRecipe) rect = g.getrect() cells = [] for i in xrange(1200, step * len(hwssRecipe) + 1501): cells.append(rect[0] - 50) cells.append(i) cells.append(6) g.putcells(cells) g.putcells(cells, rect[0] - 1000, 0) else: helixD = CalcHelix(hwssRecipe) dist = int(1.5 * len(hwssRecipe) / speed) for y in xrange(0, dist + 1): MakeForwardSalvo(step, 0, distForward * y, helixD, y == 0, y == 0) MakeForwardRecipe(helixD, step, 0, 0, hwssRecipe) rect = g.getrect() cells = [] fenseX = rect[0] + rect[2] + 50 for i in xrange(fenseY, -helixD + 201): cells.append(rect[0] + rect[2] + 50) cells.append(i + helixD) cells.append(6) g.putcells(cells)
def PlaceReadingHeads(hwssRecipe): g.new("") if directionType == "B": for y in xrange(-3 * len(hwssRecipe), 1): MakeBackwardSalvo(step, 0, distBack * y, step * len(hwssRecipe) + 100, y == 0, y == 0) MakeBackwardRecipe(step, 0, 0, hwssRecipe) else: for y in xrange(0, 3 * len(hwssRecipe) + 1): MakeForwardSalvo(step, 0, distForward * y, -step * len(hwssRecipe) - 100, y == 0, y == 0) MakeForwardRecipe(step, 0, 0, hwssRecipe)
def PlaceReadingHeads(hwssRecipe): global fenseX g.new("") g.setrule("LifeHistoryNoMark") if directionType == "B": dist = int(1.5 * len(hwssRecipe) / speed) for y in xrange(-dist, 1): MakeBackwardSalvo(step, 0, distBack * y, step * len(hwssRecipe) + 100, y == 0, y == 0) MakeBackwardRecipe(step, 0, 0, hwssRecipe) rect = g.getrect() cells = [] for i in xrange(1200, step * len(hwssRecipe) + 1501): cells.append(rect[0]-50) cells.append(i) cells.append(6) g.putcells(cells) g.putcells(cells, rect[0]-1000, 0) else: helixD = CalcHelix(hwssRecipe) dist = int(1.5 * len(hwssRecipe) / speed) for y in xrange(0, dist + 1): MakeForwardSalvo(step, 0, distForward * y, helixD, y == 0, y == 0) MakeForwardRecipe(helixD, step, 0, 0, hwssRecipe) rect = g.getrect() cells = [] fenseX = rect[0] + rect[2] + 50 for i in xrange(fenseY, -helixD + 201): cells.append(rect[0] + rect[2] + 50) cells.append(i + helixD) cells.append(6) g.putcells(cells)
def LeftMost(recipe): g.new("") g.setstep(3) g.putcells(block_cells) for r in recipe: #g.putcells(glider_cells, 80, 80 + r ) g.putcells(glider_cells, 80, 80 + 2 - r ) g.step() g.step() rect = g.getrect() return rect[0]
def Validate(recipe): g.new("") g.setstep(3) g.putcells(block_cells) for r in recipe: g.putcells(glider_cells, 120, 120 + r) #g.putcells(glider_cells, 80, 80 + 2 - r ) g.step() g.step() rect = g.getrect() return rect
def LeftMost(recipe): g.new("") g.setstep(3) g.putcells(block_cells) for r in recipe: #g.putcells(glider_cells, 80, 80 + r ) g.putcells(glider_cells, 80, 80 + 2 - r) g.step() g.step() rect = g.getrect() return rect[0]
def EvolveRecipe(recipe): g.new("") g.setstep(3) g.putcells(blck) minx = g.getrect()[0] for r in recipe: g.putcells(gld, 40, 40 + r) g.step() g.step() if minx > g.getrect()[0]: minx > g.getrect()[0] return minx
def CalculateLane(cells): g.new("") g.putcells(cells) cells = g.getcells(g.getrect()) g.new("") g.putcells(cells, -cells[0], -cells[1]) minx = 1000 maxx = -1000 for i in xrange(0, 4): rect = g.getrect() minx = min(minx, rect[0]) maxx = max(maxx, rect[0] + rect[2]) g.run(1) return (minx, maxx)
def better_randfill(): g.new('') g.select([-10, -10, GRID_SIZE[0], GRID_SIZE[1]]) g.randfill(random.randrange(50)) g.select([]) g.autoupdate(True) cnt = 0 for x in range(0, GENS): cnt += 1 if not g.empty(): g.run(1) if is_static(): break time.sleep(0.05) else: break if cnt % 10 == 0: g.fit()
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 find_all_glider_idx(mask): idxs = extract_indexes(mask) idxs.sort(key=lambda idx: (1.01 * gliders_in[idx][0] + gliders_in[idx][1])) copy_idxs = idxs[:] for edge_i in enum_shooters(mask): reaction_cells = shoot_defs[edge_i][4] stable_cells = shoot_defs[edge_i][5] for g_i in list(copy_idxs): g.new("") for g_j in idxs: x, y, idx = gliders_in[g_j] if g_j == g_i: g.putcells(g.evolve(reaction_cells, idx), x, y) else: g.putcells(g.evolve(gld, idx), x - 128, y + 128) g.setbase(8) g.setstep(3) g.step() x, y, _ = gliders_in[g_i] # test if the pattern consists of the stable cells plus the # necessary gliders and nothing else g.putcells(stable_cells, x, y, 1, 0, 0, 1, "xor") if int(g.getpop()) != 5 * len(idxs): continue for g_j in idxs: x, y, idx = gliders_in[g_j] g.putcells(g.evolve(gld, idx), x, y, 1, 0, 0, 1, "xor") if g.empty(): copy_idxs.remove(g_i) yield g_i,edge_i
def add_shooter(cost, inserter_cells, left_g, right_g=[], flip=True): global shoot_defs g.new('') g.putcells(inserter_cells) g.putcells(left_g) g.putcells(right_g) g.run(2048) reaction_cells = g.getcells([-150,-150,300,300]) g.run(512) if not all(g.getcell(x, y) for x, y in gld_pairs): g.fit() g.update() assert(False) stable_cells = set(zip(reaction_cells[::2], reaction_cells[1::2])) for _ in range(4): g.run(1) for i in range(0, len(reaction_cells), 2): tup = reaction_cells[i], reaction_cells[i+1] if tup in stable_cells and not g.getcell(*tup): stable_cells.remove(tup) stable_cells2 = [] for x, y in stable_cells: stable_cells2.append(x) stable_cells2.append(y) stable_cells = stable_cells2 tup = (cost, inserter_cells, left_g, right_g, reaction_cells, stable_cells) shoot_defs.append(tup) if flip: shoot_defs.append((cost, f(inserter_cells), f(right_g), f(left_g), f(reaction_cells), f(stable_cells)))
def construct(self): g.new('') g.setrule("LifeHistory") events = sorted(self.timeline, reverse=True) time = -240 * 20 nextrow = time + 240 top_y = 0 for y in range(60): g.setcell(self.left, y, 6) g.setcell(self.right, y, 6) rephasing = [0] * len(self.columns) while events: if events[-1][0] < nextrow: t, c = events.pop() g.run(t-time) time = t x, y, excess = self.columns[c] #place bhep, reflecting in the odd columns g.putcells(self.b_hep, x + (c%2), rephasing[c] + y, -1 if (c%2) else 1) #add blocks to absorb excess gliders for i in range(excess): g.putcells(self.absorber, x + (c%2), rephasing[c] + y - 31 * i, -1 if (c%2) else 1) rephasing[c] += 31 - 9 else: for x, y, _ in self.columns: g.putcells(g.parse("2o$2o!", x, 2*top_y+y)) g.putcells(g.parse("2o$2o!", x, 2*top_y-31+y)) for _ in range(31): top_y -= 1 g.setcell(self.left, top_y, 6) g.setcell(self.right, top_y, 6) g.run(nextrow-time) time = nextrow nextrow += 240
def PerformDelete(glider, gunPeriod): initCells = g.getcells(g.getrect()) for j in xrange(0, len(glider), 2): if g.getcell(glider[j], glider[j + 1]) != 1: return False Erase(glider) rect = g.getrect() cells = g.getcells(rect) g.run(gunPeriod) if str(g.getcells(rect)) == str(cells): g.new("") g.putcells(cells) return True else: g.new("") g.putcells(initCells) return False
def FinadOptimalRecipe(slv, idx): moveTable = slv.SLsMoveTable[idx] bests = [-1, -1] slCount = [1000, 1000] g.setrule("B3/S23") g.setalgo("HashLife") for i in xrange(0, len(moveTable)): g.new("") slv.ApplyRecipeSmart(i, idx) slv.PlaceRecipe() g.setstep(5) g.step() numSL = len(CountSL()) laneID = (moveTable[i][1] + 10000) % 2 if slCount[laneID] > numSL: slCount[laneID] = numSL bests[laneID] = i slv.Reset() g.setrule("LifeHistory") for i in xrange(0, len(bests)): slv.ApplyRecipeSmart(bests[i], idx) slv.PlaceRecipe(i * 100, 0, i == 0) slv.Reset() g.show(str(bests)) #11 - [32, 249] #12 - [138, 123] #13 - [29, 27] #14 - [89, 15] return bests
def explode_dense(): num_trial = 2 for i in range(num_trial): g.new("") g.select([0, 0, 32, 32]) g.randfill(50) g.run(128) total = 0 for i in range(32): total += len(g.getcells([0, 0, 32, 32])) / 2 g.run(32) total /= 32 if total >= 300: return True return False
def SaveForwardSalvoData(dir): g.new("") MakeBackwardSalvo(step, 0, 0, 0, True, True) rectB = g.getrect() g.new("") MakeForwardSalvo(step, 0, 0, 0, True, True) rectF = g.getrect() g.run(3) forwardRecipe = FindWssByDirection(True, distForward) forwardRecipe.reverse() fRecipe = [] dx = rectB[0] - (rectF[0] + rectF[2]) - 100 dx = int(dx / 8) * 8 for i in xrange(0, len(forwardRecipe)): x, y, d = forwardRecipe[i] fRecipe.append((x + dx, y + 1, d)) pickle.dump(fRecipe, open(path.join(dir, str(step) + "_ForwardSalvoAuto.pkl"), "wb"))
def CanApplyRecipe(self, recipe, expected): g.new("") g.setstep(3) g.putcells(blck) g.putcells(self.init) for r in self.recipe: g.putcells(gld, 80, 80 + r) g.step() g.select([self.block0[0], self.block0[1], 2, 2]) g.clear(0) cells = g.getcells(g.getrect()) g.putcells(blck, self.block0[0], self.block0[1]) delta = self.block0[1] - self.block0[0] for r in recipe: g.putcells(gld, 80, 80 + r + delta) g.step() for i in xrange(0, len(cells), 2): x = cells[i] y = cells[i + 1] if g.getcell(x, y) == 0: return False for i in xrange(0, len(expected), 2): x = expected[i] + self.block0[0] y = expected[i + 1] + self.block0[1] if g.getcell(x, y) == 0: return False return True
def getoctohash(clist): ptr = 0 g.new("Octotest" + str(count)) for orientation in [[1, 0, 0, 1], [0, -1, 1, 0], [-1, 0, 0, -1], [0, 1, -1, 0], [-1, 0, 0, 1], [1, 0, 0, -1], [0, 1, 1, 0], [0, -1, -1, 0]]: g.putcells(clist, ptr * 2048, 0, *orientation) ptr += 1 for j in range(8): g.select([2048 * j - 1024, -1024, 2048, 2048]) g.shrink() r = g.getselrect() if r == []: r = [0, 0, 1, 1] pat = g.getcells(r) deltax, deltay = 0, 0 if pat != []: deltax, deltay = -pat[0], -pat[1] if j == 0: minstr = str(g.transform(pat, deltax, deltay)) else: strpat = str(g.transform(pat, deltax, deltay)) if strpat < minstr: minstr = strpat return " " + get9char(minstr)
# To be consistent with the code below, .cells files should be created in a separate pass # -- but we've already had a chance to collect width, height, and RLE from the RLE scan # So we'll just make a .cells files using that info, as soon as a missing .cells is found. # # Notice that this means that .cells files are only created _after_ RLE files are already on the server. # That is, we're not going and looking for RLE information in the RLE namespace, only on the server. # This is suboptimal, because getting the .cells files there will require two bulk uploads instead of one. # On the other hand, doing that in one step needs more code: # TODO: get RLE from raw RLE namespace if we're going to be uploading that # (this will need some fairly serious refactoring, probably moving .cells creation to a separate pass) # pat = g.parse(rleonly) if len( pat ) % 2 == 0: # don't try to make a .cells for a multistate file like RLE:briansbrainp3 g.new(item) g.putcells(pat) r = g.getrect() for y in range(r[3]): for x in range(r[2]): ascii += "O" if g.getcell(x + r[0], y + r[1]) > 0 else "." ascii += "\n" with open(cellsfolder + item + ".cells", "w") as f: f.write(ascii) else: # width and/or height are too big toobigforcells += [item] # remove from the list of articles that could have cells files but don't if item in noplaintextparam: noplaintextparam.pop( item,
bg_col = palette[color] fg_col = palette[state+n_colors] mid = [(f+b)/2 for f,b in zip(fg_col,bg_col)] for x in range(15): for y in range(15): column = (encode(color,state,dir)-1)*15 + rotate4[dir][0][0]*x + \ rotate4[dir][0][1]*y + offset4[dir][0]*14 row = rotate4[dir][1][0]*x + rotate4[dir][1][1]*y + offset4[dir][1]*14 pixels[row][column] = [bg_col,fg_col,eyes,mid][ant15x15[y][x]] for x in range(7): for y in range(7): column = (encode(color,state,dir)-1)*15 + rotate4[dir][0][0]*x + \ rotate4[dir][0][1]*y + offset4[dir][0]*6 row = 15 + rotate4[dir][1][0]*x + rotate4[dir][1][1]*y + offset4[dir][1]*6 pixels[row][column] = [bg_col,fg_col,eyes,mid][ant7x7[y][x]] for color in range(n_colors): bg_col = palette[color] for row in range(15): for column in range(15): pixels[row][(color-1)*15+column] = bg_col for row in range(7): for column in range(7): pixels[15+row][(color-1)*15+column] = bg_col WriteBMP(pixels,golly.getdir('rules')+rule_name+'.icons') # now we can switch to the new rule golly.setrule(rule_name) golly.new(rule_name+' demo') golly.setcell(0,0,n_colors+3) # start with an ant facing west golly.show('Created '+rule_name+'.tree, and selected this rule.')
def FindAllHs(cells, minx): g.new("") g.putcells(cells) rect = g.getrect() min = 10000 max = -10000 for i in xrange(1, len(cells), 2): cx = cells[i - 1] cy = cells[i] dx = 40 - cx cy += dx if cy < min: min = cy if cy > max: max = cy answer = [[],[]] if (min - 9) % 2 != 0: min += 1 for i in xrange(min - 9 - 40, max + 6 - 40, 2): g.new("") g.putcells(cells) g.putcells(gld, 40, 40 + i) g.setstep(3) g.step() g.step() if int(g.getpop()) > 60: continue if int(g.getpop()) == 0: continue if g.getrect()[0] < -120: continue edgeType = HasEdgeShooter(minx) if edgeType != False: answer[0].append([i, 0, 0, [edgeType]]) rect = g.getrect() if rect[2] > 12 or rect[3] > 12: continue s = str(g.getcells(g.getrect())) g.run(2) if s == str(g.getcells(g.getrect())): key = str(rect) + ":" + str(g.getpop()) if not (key in existingKeys): existingDic[key] = [] existingKeys.append(key) if s in existingDic[key]: continue else: existingDic[key].append(s) answer[1].append(i) return answer
slv.PlaceRecipe(i * 100, 0, i == 0) slv.Reset() wssSalvo = SlowSalvoConstructor("C:\\Users\\SimSim314\\Glue\\AllWSS\\7[24].txt", [], []) #PlaceAdjustment(salvo) #FinadOptimalRecipe(salvo, 14) #PlaceAllRecipesForIdx(salvo, 11) #MWSS3SLsEdgeShooter(salvo) #HWSS3SLsEdgeShooter(salvo) #res = [5, -3, 13, 8, -5, -7, -23, -18, 8, -15] #salvo.AppendExternalRecipe(res) #salvo.PlaceRecipe() ''' hwssAdjusted = [[-4, -6, -8, -9, -17, -35, -37, -39, -47, -60, -55, -37, -35, -27, -41, -48, -41, -40, -30, -21, -21, -23, -11, -19, -31, -5, -7, -9, -10, -18, -34, -12, -2, -26, -12, -35, -44, -45, -27, -26, -11, -10, -27], [-4, -6, -8, -9, -17, -35, -37, -39, -47, -60, -55, -37, -35, -27, -41, -48, -41, -40, -30, -21, -21, -23, -11, -19, -31, -5, -7, -9, -10, -18, -34, -21, -31, -18, -6, -12, 11, 7, 5, 3, 0, 8, -1, 0, 0, -10, -27], [-4, -6, -8, -9, -17, -35, -37, -39, -47, -60, -55, -37, -35, -27, -41, -48, -41, -40, -30, -21, -21, -23, -11, -19, -31, -5, -7, -9, -10, -18, -34, -21, -30, -21, -25, -22, -31, -38, -41, -32, -18, -21, -30, -20, -10, -27], [-4, -6, -8, -9, -17, -35, -37, -39, -47, -60, -55, -37, -35, -27, -41, -48, -41, -40, -30, -21, -21, -23, -11, -19, -31, -5, -7, -9, -10, -18, -34, -11, -10, -19, -28, -23, -24, -27, -22, -20, -30, -10, -10, -27], [-4, -6, -8, -9, -17, -35, -37, -39, -47, -60, -55, -37, -35, -27, -41, -48, -41, -40, -30, -21, -21, -23, -11, -19, -31, -5, -7, -9, -10, -18, -34, -12, -2, -34, -4, -13, -22, -22, -20, -25, -13, -9, -10, -27], [-4, -6, -8, -9, -17, -35, -37, -39, -47, -60, -55, -37, -35, -27, -41, -48, -41, -40, -30, -21, -21, -23, -11, -19, -31, -5, -7, -9, -10, -18, -34, -22, -23, -24, -24, -33, -33, -32, -16, -36, -39, -10, -27], [-4, -6, -8, -9, -17, -35, -37, -39, -47, -60, -55, -37, -35, -27, -41, -48, -41, -40, -30, -21, -21, -23, -11, -19, -31, -5, -7, -9, -10, -18, -34, -12, -22, -13, -10, -5, -9, -11, -18, -15, -23, -14, -9, -5, -10, -27], [-4, -6, -8, -9, -17, -35, -37, -39, -47, -60, -55, -37, -35, -27, -41, -48, -41, -40, -30, -21, -21, -23, -11, -19, -31, -5, -7, -9, -10, -18, -34, -11, -10, -20, -10, -19, -11, -25, -28, -19, -20, -10, -27]] hwssAdjusted[6] = [-4, -6, -8, -9, -17, -35, -37, -39, -47, -60, -55, -37, -35, -27, -41, -48, -41, -40, -30, -21, -21, -23, -11, -19, -31, -5, -7, -9, -10, -18, -34, -19, -22, -10, -27] adjustmentrecipes = [[-4, -13, -14, 4, 5], [-4, -6, -8, -11, -3, -12], [-4, -11, -14, -5, 9, 6], [-4, -13, -8, -9, -12, -7], [-4, -13, -13, -11, -16, -4], [-4, -13, -13, -12, 4, -16], [-4, -6, -13, -10, -18, -9], [-4, 4, -10, -13, -4]] hwss = hwssAdjusted[6] tail = [-10, -27] moveRecipes= [[5, 15, -9, 5], [-4, -14, -1, 11, 5, 28], [-4, -13, -4, -8, -5], [6, 7], [5, 15, -17, 13], [-5, -6, -7], [5, -5, 4, 7, 12],[6, 7, -3, 7]] blockMoves= [[30,-1], [-6, 5], [32, 5], [20, 5], [14, 5], [25,5], [10, 5], [20, 5]] destruction = [[-11], [0,0], [-30,-20], [-20,-30, -10], [-9], [-39], [-9, -5], [-20]] cells = [] allRecipes = [] for i in xrange(0, 8): salvo.Reset()
# sanity check to make sure all elbows are distinct elbow_types = set() for elbow in ELBOWS: elbow_type = is_elbow(elbow) assert(elbow_type != False) assert(elbow_type.isupper()) assert(elbow_type not in elbow_types) elbow_types.add(elbow_type) #prof = open("/home/user/life/elbow.stats", "w") #pr = cProfile.Profile() #pr.enable() # do it f = open(OUTFILE, 'w') g.new('') for elbow in ELBOWS: search(elbow) f.close() #pr.disable() #pstats.Stats(pr, stream=prof).sort_stats("cumulative").print_stats() #prof.close()
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: soupfile.write("\n".join(soups))
# add rest of pattern after the center area is filled in # and p184 HWSS guns are in the same phase (3680 = 184 * 40) ONcell = all + CellCenter[3680] if os.access(ONcellFileName, os.W_OK) or not os.access(ONcellFileName, os.F_OK): try: ONcell.save (ONcellFileName, "Metapixel ON cell: Brice Due, Spring 2006") except: g.show("Failed to save file version of ON cell: " + ONcellFileName) os.remove(ONcellFileName) OFFcell += RuleBits ONcell += RuleBits g.autoupdate(True) g.new(layername) g.setalgo("QuickLife") # qlife's setcell is faster for j in xrange(selheight): for i in xrange(selwidth): golly.show("Placing (" + str(i+1) + "," + str(j+1) + ") tile" + " in a " + str(selwidth) + " by " + str(selheight) + " rectangle.") if livecell[i][j]: ONcell.put(2048 * i - 5, 2048 * j - 5) else: OFFcell.put(2048 * i - 5, 2048 * j - 5) g.fit() g.show("") g.setalgo("HashLife") # no point running a metapattern without hashing g.setoption("hyperspeed", False) # avoid going too fast
# Bill Gosper's pure-period p1100 double MWSS gun, circa 1984. import golly as g from glife import * g.new("P1100 gun") g.setalgo("HashLife") g.setrule("B3/S23") # update status bar now so we don't see different colors when # g.show is called g.update() glider = pattern("bo$bbo$3o!") block = pattern("oo$oo!") eater = pattern("oo$bo$bobo$bboo!") bhept = pattern("bbo$boo$oo$boo!") twobits = eater + bhept(8,3) half = twobits + twobits[1](51,0,flip_x) centinal = half + half(0,16,flip_y) passthrough = centinal[1](16,3,rcw) + centinal[19](52,0,rcw) \ + centinal[81](55,51,rccw) + centinal[99](91,54,rccw) # build the source signal -- the most compact set of gliders # from which all other gliders and spaceships can be generated MWSSrecipes = glider(5759,738,rccw) + glider(6325,667,flip_x) \ + glider[3](5824,896,flip_x) + glider[2](5912,1264) \ + glider[2](6135,1261,flip_x) + glider[1](5912,1490,flip_y) \ + glider(6229,4717,flip_x) + glider[1](6229,5029,flip) \ + glider[1](5920,5032,flip_y) + glider(6230,5188,flip) \
def setsimname(self, text): """ Names the simulation that is being displayed :param text: the name to be displayed """ g.new(text)
# lower triangle pixels[row][(encode(color,state,dir)-1)*15+column] = \ [palette[0],bg_color,fg_color][lower[dir][row][column]] # upper triangle pixels[row][(encode(color,state,dir)+total_states-2)*15+column] = \ [palette[0],bg_color,fg_color][lower[2-dir][13-row][column]] # draw the 7x7 icon for row in range(7): for column in range(7): # lower triangle pixels[15+row][(encode(color,state,dir)-1)*15+column] = \ [palette[0],bg_color,fg_color][lower7x7[dir][row][column]] # upper triangle pixels[15+row][(encode(color,state,dir)+total_states-2)*15+column] = \ [palette[0],bg_color,fg_color][lower7x7[2-dir][6-row][column]] ConvertTreeToRule(rule_name, total_states, pixels) else: golly.warn('Too many states!') golly.exit() # -- select the rule -- golly.new(rule_name+'-demo.rle') golly.setalgo('RuleLoader') golly.setrule(rule_name) golly.setcell(0,0,encode(0,0,0)) # start with a single turmite golly.show('Created '+rule_name+'.rule and selected that rule.')
currname = g.getname() currcursor = g.getcursor() currcolors = g.getcolors() currstates = g.numstates() deads, deadr, deadg, deadb = g.getcolors(0) # create histogram in separate layer g.setoption("stacklayers", 0) g.setoption("tilelayers", 0) g.setoption("showlayerbar", 1) if histlayer == -1: histlayer = g.addlayer() else: g.setlayer(histlayer) g.new(histname) g.setcursor(currcursor) # use a Generations rule so we can append extra state for drawing text & lines g.setrule("//" + str(currstates + 1)) extrastate = currstates currcolors.append(extrastate) if (deadr + deadg + deadb) / 3 > 128: # use black if light background currcolors.append(0) currcolors.append(0) currcolors.append(0) else: # use white if dark background currcolors.append(255) currcolors.append(255)
Tail = -speed * (iters - l * 2) + l + 576 GotoLimited(iters, 5) rect = g.getrect() g.select([rect[0], Head - 3 * distBack, rect[2], Tail - Head + 3 * distBack + 1500]) g.clear(1) g.save(path.join(dir, str(step) + "_" + str(period) + "_Back.rle"), "rle", False) #''' #This code synchronize the backward recipes to fit with forward created at 0,0 g.show("synchronize the backward recipes to fit with forward") g.new("") MakeForwardSalvo(step, 0, 0, 0, True, True) forwardRecipe = FindWssByDirection(True, distForward) x0, y0, id = forwardRecipe[0] ConvertToRelative(forwardRecipe, distForward) g.open(path.join(dir, str(step) + "_" + str(period) + "_Back.rle"), False) rect = g.getrect() 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]