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 canonise(): p = bijoscar(4) 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) return "x"+prefix+"_"+representation
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 goto(newgen, delay): g.show("goto running, hit escape to abort...") 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) if delay <= 1.0: g.run(1) newgen -= 1 # use fast stepping (thanks to PM 2Ring) for i, d in enumerate(intbase(newgen, 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 >= delay: # time to do an update? oldsecs = newsecs g.update() g.show("")
def bijoscar(maxsteps): initpop = int(g.getpop()) initrect = g.getrect() if (len(initrect) == 0): return 0 inithash = g.hash(initrect) for i in xrange(maxsteps): g.run(1) if (int(g.getpop()) == initpop): prect = g.getrect() phash = g.hash(prect) if (phash == inithash): period = i + 1 if (prect == initrect): return period else: return -period return -1
def bijoscar(maxsteps): initpop = int(g.getpop()) initrect = g.getrect() if (len(initrect) == 0): return 0, None inithash = g.hash(initrect) for i in range(maxsteps): g.run(1) if (int(g.getpop()) == initpop): prect = g.getrect() phash = g.hash(prect) if (phash == inithash): period = i + 1 if (prect == initrect): return period, (0, 0) else: dx = prect[0] - initrect[0] dy = prect[1] - initrect[1] return period, (dx, dy) return -1, None
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 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 goto(newgen, delay): g.show("goto running, hit escape to abort...") 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) if delay <= 1.0: g.run(1) newgen -= 1 # use fast stepping (thanks to PM 2Ring) for i, d in enumerate(intbase(newgen, g.getbase())): if d > 0: g.setstep(i) for j in range(d): if g.empty(): g.show("Pattern is empty.") return g.step() newsecs = time() if newsecs - oldsecs >= delay: # time to do an update? oldsecs = newsecs g.update() g.show("")
def canonise(): p = bijoscar(MAXPERIOD) if p == -1: # In rules with photons the pattern may be periodic, but not in CGoL return "" 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 = "xq" + str(abs(p)) elif (p==1): prefix = "xs" + str(g.getpop()) else: prefix = "xp" + str(p) return prefix + "_" + representation
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 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 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) rule = str.replace(g.getrule(),"/","").lower() webbrowser.open_new("http://catagolue.appspot.com/object?apgcode=x"+prefix+"_"+representation+"&rule="+rule)
def testRule(rulestr): r = g.getrect() if r: g.select(r) g.clear(0) g.putcells(origPatt) g.setrule(rulestr) g.run(stabGen) if g.empty(): return () pop = int(g.getpop()) if (pop < minPop or pop > maxPop): return () r = g.getrect() testPatt = g.transform(g.getcells(r), -r[0], -r[1]) testPop = int(g.getpop()) testRect = g.getrect() stabPatt = list(testPatt) stabPop = testPop for ii in xrange(maxGen): g.run(1) pop = int(g.getpop()) if (pop < minPop or pop > maxPop): break if (pop == testPop): # Test for periodicity r = g.getrect() if testPatt == g.transform(g.getcells(r), -r[0], -r[1]): period = ii + 1 dy, dx = sss.minmaxofabs( (r[0] - testRect[0], r[1] - testRect[1])) if (dx == 0): # Oscillator (reject if low period or bOsc is False) if bOsc and period >= minOscP: return (0, 0, period) elif (period >= minShipP): # Spaceship return (dx, dy, period) elif ((dx + dy / 1.9) / (period * 1.0) > minSpeed and period >= fastShipP): # Fast spaceship return (dx, dy, period) break # Pattern is a low period oscillator or spaceship # Stability check if (ii % stabCheckP == 0): r = g.getrect() # First check for BBox expansion if maxDim > 0 and max(r[2:4]) > maxDim: # Pattern is expanding # XXX Attempt to separate components expanding in different directions break currPatt = g.transform(g.getcells(r), -r[0], -r[1]) if (pop == stabPop and currPatt == stabPatt): # Pattern has stabilised to low period oscillator / spaceship break stabPop = pop stabPatt = list(currPatt) return ()
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 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 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 Placement(self, movementData, idx, attachedPatList, snip): while True: event = g.getevent() if event == "": self.ManageMove(attachedPatList[idx], movementData) elif "click" in event: if "right" in event: movementData.RevertState() idx = (idx + 1) % len(attachedPatList) movementData = self.GetMovementData(attachedPatList, idx) self.ManageMove(attachedPatList[idx], movementData) elif "left" in event: if snip == None: snip = PlacementSnippet(attachedPatList, idx, movementData) self.snippets.append(snip) else: snip.Update(attachedPatList, idx, movementData) movementData.UpdateCellDictionary(self.smarCells, snip.id) return elif "key" in event: if "space" in event: for i in xrange(0, 30): g.run(60) g.update() g.reset() g.update() elif "right" in event: movementData.delta += 1 elif "left" in event: movementData.delta -= 1 elif "delete" in event: movementData.RevertState() g.update() return
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 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 analyse (gogen, glcnt, minpop, maxpop, mingl): if glcnt < mingl: return (False, 0) g.run (gogen) inrect = g.getrect () clean (inrect) endpop = int (g.getpop ()) if endpop < minpop or endpop > maxpop: return (False, 0) rect = g.getrect () if rect == []: return (True, 0) else: addmarkers (inrect) return (True, g.hash (inrect))
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 PeriodCalculator(): g.setbase(8) g.setstep(3) g.step() g.step() cells = g.getrect() rect = g.getrect() cells = g.getcells(rect) for i in xrange(0, 10000): g.run(1) if str(g.getcells(rect)) == str(cells): #g.show(str(i + 1)) #g.reset return i + 1 return -1
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 EdgeGlider(): for i in xrange(0, 4): rect = g.getrect() x0 = rect[0] + rect[2] - 3 y0 = rect[1] + rect[3] - 3 gldFound = True for j in xrange(0, len(gld), 2): if g.getcell(x0 + gld[j], y0 + gld[j + 1]) == 0: gldFound = False break if gldFound: return g.getcells([x0, y0, 3, 3]) g.run(1) return -1
def main( step = 1, start = 0 ): # set dir name from current date d = datetime.datetime.today() dirName = "shiki_%02d-%02d-%02d-%02d" % (d.day, d.hour, d.minute, d.second) # create directory exportDir = "%s/%s" % (dstDir, dirName) if not os.path.exists( exportDir ): os.makedirs( exportDir ) # get bound size = getImageSize( srcPath ) bound = [ -expand, -expand, size[0] + expand * 2, size[1] + expand * 2 ] # loop for f in xrange( repeat ): g.show( "Processing... %d / %d" % (f+1, repeat) ) loadImage( srcPath ) g.run( 1 ) g.update() for i in xrange( interval ): g.run( 1 ) g.update() frame = f * interval + i saveImage( bound, "%s/%s/%s_%06d.png" % (dstDir, dirName, dirName, frame) )
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 EventLoop(): global volume, genspersec nextgen = 0.0 running = True while True: space = False event = g.getevent() if len(event) == 0: sleep(0.005) # don't hog CPU if idle elif event == "key space none": running = False space = True nextgen = 0 elif event == "key return none": running = not running elif event == "key h none": ShowHelp() elif event == "key up none": volume = min(1.0, volume + 0.1) ShowInfo() elif event == "key down none": volume = max(0.0, volume - 0.1) ShowInfo() elif event == "key = none" or event == "key + none": genspersec = min(30, genspersec + 1) ShowInfo() elif event == "key - none": genspersec = max(1, genspersec - 1) ShowInfo() else: g.doevent(event) # might be a keyboard shortcut if (running or space) and time() >= nextgen: g.run(1) if g.empty(): g.exit("The pattern died.") PlaySound() g.update() if not space: nextgen = time() + 1.0 / genspersec
def HasEdgeShooter(minx): rect = g.getrect() y = rect[1] + rect[3] if y < 100: return False g.run(4) rect = g.getrect() if y + 2 == rect[1] + rect[3]: maxX = -10000 maxL = -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 = FindRightMost(curCells) curL = len(curCells) if curx > maxX: maxX = curx if curL > maxL: maxL = curL if minx - 2 > maxL: return 100 * maxL return maxL return False
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 burp(): test_signal=pattern(""" 40bo$41bo$39b3o17$40bo4bo4bo4bo4bo$41bo4bo4bo4bo4bo$39b3o2b3o2b3o2b3o 2b3o3$40bo4bo4bo4bo4bo$41bo4bo4bo4bo4bo$39b3o2b3o2b3o2b3o2b3o3$40bo4bo 4bo4bo4bo$41bo4bo4bo4bo4bo$39b3o2b3o2b3o2b3o2b3o3$40bo4bo4bo4bo4bo$41b o4bo4bo4bo4bo$39b3o2b3o2b3o2b3o2b3o3$bo38bo4bo4bo4bo4bo18bo$2bo38bo4bo 4bo4bo4bo18bo$3o36b3o2b3o2b3o2b3o2b3o16b3o37$40bo$41bo$39b3o!""") prepare_burp() ticks=0 tickstep=5 last_signal=-99999 viewport_speed=16 sel_speed=0.0 delta_sel=0.0 delay=-1.0 run_flag=False ch="" selx=600.0 sely=365.0 place_signal=3 helpstring="""Use ENTER and SPACE to run or halt the pattern; use + and - to change the step size or delay value; use arrow keys and mouse tools to pan and zoom in any pane; T toggles between a tiled view and a single-pane view; S creates another signal fleet near the detection mechanism; R resets the Heisenburp device to its initial state; Q quits out of the script and restores original settings.""" instr="Press H for help. " g.show(instr + str(tickstep)) g.select([selx,sely,50,50]) # keyboard handling while ch<>"q": if place_signal>0: if ticks-last_signal>1846: test_signal.put(-150,60) last_signal=ticks place_signal-=1 if place_signal>0 and run_flag==True: show_status_text("Next signal placement in " \ + str(1847 - ticks + last_signal) + " ticks. " + instr, delay, tickstep) else: show_status_text(instr,delay,tickstep) event = g.getevent() if event.startswith("key"): evt, ch, mods = event.split() else: ch = "" if ch=="r": prepare_burp() ticks=0 last_signal=-99999 viewport_speed=16 sel_speed=0 run_flag=False selx=600.0 sely=365.0 place_signal=3 g.select([selx,sely,50,50]) elif ch=="h": g.note(helpstring) elif ch=="t": g.setoption("tilelayers",1-g.getoption("tilelayers")) elif ch=="=" or ch=="+": if delay>.01: delay/=2 elif delay==.01: delay=-1 else: if tickstep==1: tickstep=3 elif tickstep<250: tickstep=(tickstep-1)*2+1 elif ch=="-" or ch=="_": if delay==-1: if tickstep==1: delay=.01 else: if tickstep==3: tickstep=1 else: tickstep=(tickstep-1)/2+1 else: if delay<1: delay*=2 elif ch=="space": run_flag=False elif ch=="return": run_flag=not run_flag elif ch=="s": place_signal+=1 else: # just pass any other keyboard/mouse event through to Golly g.doevent(event) # generation and selection speed handling if ch=="space" or run_flag==True: g.run(tickstep) currlayer = g.getlayer() if currlayer != 4: # user has switched layer so temporarily change it back # so we only change location of bottom right layer g.check(False) g.setlayer(4) x, y = getposint() oldticks=ticks ticks+=tickstep delta_view=int(ticks/viewport_speed) - int(oldticks/viewport_speed) if delta_view <> 0: # assumes diagonal motion for now setposint(x + delta_view, y + delta_view) sel = g.getselrect() if len(sel)<>0: x, y, w, h = sel if int(selx)<>x: # user changed selection # prepare to move new selection instead (!?!) # -- use floating-point selx, sely to account for fractional speeds selx=x sely=y else: selx+=sel_speed*tickstep sely+=sel_speed*tickstep g.select([selx, sely, w, h]) else: g.select([selx, sely, 50, 50]) if currlayer != 4: g.setlayer(currlayer) g.check(True) # change viewport speed at appropriate times to follow the action if oldticks<4570 and ticks>=4570: sel_speed=.666667 # one-time correction to catch up with the signal at high sim speeds g.select([600+(ticks-4570)*1.5, 365+(ticks-4570)*1.5, w, h]) if selx>2125: sel_speed=0 g.select([2125, sely+2125-selx, w, h]) if oldticks<4750 and ticks>=4750: viewport_speed=1.5 if oldticks<6125 and ticks>=6125: viewport_speed=16 if oldticks>=11995: viewport_speed=99999.9 # stop automatically after the last signal passes through the device if oldticks - last_signal<8705 and ticks - last_signal>=8705: run_flag=False if run_flag==True and delay>0: sleep(delay) g.update()
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)) g.show("Soups successfully saved in {}.".format(soupfilepath))
lines.append(line) res = [] for i in xrange(0, len(splitVals)): res.append(int(splitVals[i])) recipes.append(res) gld = g.parse("3o$o$bo!") block = g.parse("2o$2o!", 0, 0) d = 0 for r in recipes: g.putcells(block, d) for i in xrange(0, len(r)): g.putcells(gld, 200 * (i + 1) + d, 200 * (i + 1) + r[i]) d += 1000 g.run(50000) wssList = pickle.load(open(path.join(g.getdir("data"),"WssData.pkl"),"rb") ) objects = FindObjects(wssList) objects.sort() res = "Gen:50000,Step:200\n" for i in xrange(0, len(objects)): x, y, val = object[i] x -= 1000 * i res += str((x, y)) + ":" + lines[i] + "\n" with open(outputFile, "w") as text_file: text_file.write(res)
genlist.insert(pos, int(g.getgen())) poplist.insert(pos, int(g.getpop())) boxlist.insert(pos, pbox) return False # -------------------------------------------------------------------- def fit_if_not_visible(): # fit pattern in viewport if not empty and not completely visible r = rect(g.getselrect()) if (not r.empty) and (not r.visible()): g.fit() # -------------------------------------------------------------------- g.show("Checking for oscillation... (hit escape to abort)") oldsecs = time() while not oscillating(): g.run(1) newsecs = time() if newsecs - oldsecs >= 1.0: # show pattern every second oldsecs = newsecs fit_if_not_visible() g.update() fit_if_not_visible()
totalperiod = 1 for period in periodlist: totalperiod = lcm(period, totalperiod) longest = [], 0 for soupnum in range(soups): g.new('') g.select([0, 0, 5, 5]) g.randfill(50) currsoup = g.getcells([0, 0, 5, 5]) currpop = g.getpop() sameaslast = 0 totalgens = 0 success = False while totalgens < maxgens: g.run(totalperiod) totalgens += totalperiod if g.getpop() == currpop: sameaslast += 1 else: sameaslast == 0 currpop = g.getpop() if sameaslast == 5: # We assume it's stabilized success = True totalgens -= totalperiod * 5 if totalgens > longest[1]: longest = currsoup, totalgens break if not success: g.new('')
# 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 fit_if_not_visible(): # fit pattern in viewport if not empty and not completely visible r = rect(g.getrect()) if (not r.empty) and (not r.visible()): g.fit() # -------------------------------------------------------------------- g.show("Checking for oscillation... (hit escape to abort)") oldsecs = time() while not oscillating(): g.run(1) newsecs = time() if newsecs - oldsecs >= 1.0: # show pattern every second oldsecs = newsecs fit_if_not_visible() g.update() fit_if_not_visible()
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] 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
def FindAllHs(cells): 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()) > 80 or int(g.getpop()) == 0: continue if g.getrect()[0] < -120: continue rect = g.getrect() if rect[2] > 25 or rect[3] > 25: continue s = str(g.getcells(g.getrect())) g.run(1) if s == str(g.getcells(g.getrect())): key = str(rect) + ":" + str(g.getpop()) SLs = [] if rect[2] < 8 and rect[3] < 8: SLs = CountSL() if len(SLs) == 1: SLs[0].sort(key=lambda r: 100000 * r[1] + r[0]) x1 = SLs[0][0][0] y1 = SLs[0][0][1] for o in xrange(0, len(SLs[0])): SLs[0][o][0] -= x1 SLs[0][o][1] -= y1 answer[0].append([i, x1, y1, SLs[0]]) 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
def main(): g.run(35328)
def quiescent (boundrect, period, clist, el, em, eh, sl, sm, sh, wl, wm ,wh, nl, nm, nh, se, sw, nw, ne): if boundrect == []: boundrect = g.getrect () if boundrect != []: boundrect[0] = boundrect [0] - 1 boundrect[1] = boundrect [1] - 1 boundrect[2] = boundrect [2] + 2 boundrect[3] = boundrect [3] + 2 eastcells = allcells (el + em + eh) clist = clistdiff (clist, eastcells) if clist == []: return (True) if (eastcells != []) and (max (clist[::2]) + (2 * (period + 1)) > min (eastcells[::2])): return (False) southcells = allcells (sl + sm + sh) clist = clistdiff (clist, southcells) if clist == []: return (True) if (southcells != []) and (max (clist[1::2]) + (2 * (period + 1)) > min (southcells[1::2])): return (False) westcells = allcells (wl + wm + wh) clist = clistdiff (clist, westcells) if clist == []: return (True) if (westcells != []) and (min (clist[::2]) - (2 * (period + 1)) < max (westcells[::2])): return (False) northcells = allcells (nl + nm + nh) clist = clistdiff (clist, northcells) if clist == []: return (True) if (northcells != []) and (min (clist[1::2]) - (2 * (period + 1)) < max (northcells[1::2])): return (False) secells = allcells (se) clist = clistdiff (clist, secells) if clist == []: return (True) if (secells != []) and \ (max ([clist [n] + clist [n+1] for n in range (0, len (clist) - 1, 2)]) + (2 * (period + 1)) > \ min ([secells [n] + secells [n+1] for n in range (0, len (secells) - 1, 2)])): return (False) swcells = allcells (sw) clist = clistdiff (clist, swcells) if clist == []: return (True) if (swcells != []) and \ (max ([clist [n+1] - clist [n] for n in range (0, len (clist) - 1, 2)]) + (2 * (period + 1)) > \ min ([swcells [n+1] - swcells [n] for n in range (0, len (swcells) - 1, 2)])): return (False) nwcells = allcells (nw) clist = clistdiff (clist, nwcells) if clist == []: return (True) if (nwcells != []) and \ (min ([clist [n] + clist [n+1] for n in range (0, len (clist) - 1, 2)]) - (2 * (period + 1)) < \ max ([nwcells [n] + nwcells [n+1] for n in range (0, len (nwcells) - 1, 2)])): return (False) necells = allcells (ne) clist = clistdiff (clist, necells) if clist == []: return (True) if (necells != []) and \ (max ([clist [n] - clist [n+1] for n in range (0, len (clist) - 1, 2)]) + (2 * (period + 1)) > \ min ([necells [n] - necells [n+1] for n in range (0, len (necells) - 1, 2)])): return (False) wssmove = period/2 if eastcells != []: for n in range (0, len(eastcells) - 1, 2): eastcells[n] += wssmove if southcells != []: for n in range (1, len(southcells), 2): southcells[n] += wssmove if westcells != []: for n in range (0, len(westcells) - 1, 2): westcells[n] -= wssmove if northcells != []: for n in range (1, len(northcells), 2): northcells[n] -= wssmove glimove = period/4 if secells != []: for n in range (0, len (secells) - 1, 2): secells[n] += glimove secells[n+1] += glimove if swcells != []: for n in range (0, len (swcells) - 1, 2): swcells[n] -= glimove swcells[n+1] += glimove if nwcells != []: for n in range (0, len (nwcells) - 1, 2): nwcells[n] -= glimove nwcells[n+1] -= glimove if necells != []: for n in range (0, len (necells) - 1, 2): necells[n] += glimove necells[n+1] -= glimove g.run (period) boundrect[0] = boundrect [0] - period/2 boundrect[1] = boundrect [1] - period/2 boundrect[2] = boundrect [2] + period boundrect[3] = boundrect [3] + period newclist = g.getcells (boundrect) checkclist = northcells + nwcells + necells + westcells + clist + eastcells + swcells + secells + southcells return (clistssame (newclist, checkclist))
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 runn(n,t): while n>0: g.run(1) g.update() sleep(t) n=n-1
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
def main( step = 1, start = 0 ): global bound, expand g.reset() g.run(otcaDur) # get current Golly states cellWidth = 2048 bound[ 0 ] = bound[0] * cellWidth bound[ 1 ] = bound[1] * cellWidth bound[ 2 ] = bound[2] * cellWidth bound[ 3 ] = bound[3] * cellWidth left = bound[ 0 ] top = bound[ 1 ] width = bound[ 2 ] height = bound[ 3 ] palette = getPalette() cells = g.getcells( [0, 0, 1, 1] ) isMultiStates = len(cells) % 2 == 1 cellW = 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() imgWidth = int( width / ratio ) imgHeight = int ( height / ratio ) boundWidth = ratio / subdiv pb = [0, 0, boundWidth, boundWidth] # pixel bound i = x = y = bx = by = 0 frameCount = 0 step = int(otcaDur / duration) for i in xrange(0, duration): g.show("Processing... %d / %d" % (i+1, duration)) g.run(step) g.update() img = Image.new("RGB", (imgWidth, imgHeight)) for y in xrange(imgHeight): for x in xrange(imgWidth): for by in xrange(0, subdiv, skipBound): for bx in xrange(0, subdiv, skipBound): pb[0] = left + x * ratio + bx * boundWidth pb[1] = top + y * ratio + by * boundWidth cells = g.getcells(pb) if len( cells ) > 0: img.putpixel((x, y), (255, 255, 255)) break else: continue break # save # img.save( "%s/%s_%02dx_%s_%08d.png" % (dstDir, name, ratio, mode, i) ) # img.save( "%s/%s_%02dx_%08d.png" % (dstDir, name, ratio, i) ) img.save("%s/%s_%04d.png" % (dstDir, name, i)) g.show("Done.")
def score_pair(g, seed1, seed2, width_factor, height_factor, \ time_factor, num_trials): """ Put seed1 and seed2 into the Immigration Game g and see which one wins and which one loses. Note that this function does not update the histories of the seeds. """ # # Make copies of the original two seeds, so that the following # manipulations do not change the originals. # s1 = copy.deepcopy(seed1) s2 = copy.deepcopy(seed2) # # Initialize scores # score1 = 0.0 score2 = 0.0 # # Run several trials with different rotations and locations. # for trial in range(num_trials): # # Randomly rotate and flip s1 and s2 # s1 = s1.random_rotate() s2 = s2.random_rotate() # # Switch cells in the second seed (s2) from state 1 (red) to state 2 (blue) # s2.red2blue() # # Rule file is "Immigration.rule" # Set toroidal universe of height yspan and width xspan # Base the s1ze of the universe on the s1zes of the seeds # # g = the Golly universe # [g_width, g_height, g_time] = dimensions(s1, s2, \ width_factor, height_factor, time_factor) # # set algorithm -- "HashLife" or "QuickLife" # g.setalgo("QuickLife") # use "HashLife" or "QuickLife" g.autoupdate(False) # do not update the view unless requested g.new("Immigration") # initialize cells to state 0 g.setrule("Immigration:T" + str(g_width) + "," + str(g_height)) # make a toroid # # Find the min and max of the Golly toroid coordinates # [g_xmin, g_xmax, g_ymin, g_ymax] = get_minmax(g) # # Set magnification for Golly viewer # g.setmag(set_mag(g)) # # Randomly place seed s1 somewhere in the left s1de of the toroid # s1.insert(g, g_xmin, -1, g_ymin, g_ymax) # # Randomly place seed s2 somewhere in the right s1de of the toroid # s2.insert(g, +1, g_xmax, g_ymin, g_ymax) # # Run for a fixed number of generations. # Base the number of generations on the sizes of the seeds. # Note that these are generations ins1de one Game of Life, not # generations in an evolutionary sense. Generations in the # Game of Life correspond to growth and decay of a phenotype, # whereas generations in evolution correspond to the reproduction # of a genotype. # g.run(g_time) # run the Game of Life for g_time time steps g.update() # need to update Golly to get counts # # Count the populations of the two colours. State 1 = red = seed1. # State 2 = blue = seed2. # [count1, count2] = count_pops(g) # if (count1 > count2): score1 = score1 + 1.0 elif (count2 > count1): score2 = score2 + 1.0 else: score1 = score1 + 0.5 score2 = score2 + 0.5 # # # Normalize the scores # score1 = score1 / num_trials score2 = score2 / num_trials # return [score1, score2]
# to change behavior at center, comment out one of the lines below all += eater(6018,5924,rccw) + eater(6037,5943,rccw) # true p1100 gun # all += block(6018,6787) # synch center to recreate original p1100x5 center = block(1081,6791) + block(2731,6791) + block(3831,6791) \ + block(9108,6791) + block(10208,6791) + block(11308,6791) \ + passthrough(8475,6737) + passthrough[39](3365,6737,flip_x) \ + passthrough(9575,6737) + passthrough[39](2265,6737,flip_x) \ + passthrough(10675,6737) + passthrough[39](1715,6737,flip_x) # add asymmetric Equator to mirror-symmetric North and South MWSSrecipes += MWSSrecipes(0,13583,flip_y) all += all(0,13583,flip_y) + center g.putcells(all) g.fit() # Different glider paths are different lengths, so incomplete # glider recipes must be overwritten for a while to prevent disaster. for i in range(46): g.show("Filling glider tracks -- " \ + str(49500 - i*1100) + " ticks left.") g.update() g.putcells(MWSSrecipes) g.run(1100) g.show("") # reset gen count to 0 g.setgen("0")
# g.note(str([basegun+"_special_p" + ("0000"+period)[-5:], (basegun+"_special_p" + ("0000"+period)[-5:] in specialguns)])) if basegun == "fixed" or basegun + "_special_p" + ( "0000" + period)[-5:] in specialguns: if basegun == "fixed": fixedname = "p" + ("0000" + period)[-5:] folder = fixedfolder else: # g.note(basegun) ################# fixedname = basegun + "_special_p" + ("0000" + period)[-5:] + ",0,0,0" folder = specialfolder g.open(os.path.join(folder, fixedname + ".rle")) bb = g.getrect() usebb = 1 g.setrule("LifeHistoryToLife") g.run(1) g.setrule("Life") if basegun == "fixed": g.save(os.path.join(outfolder, fixedname) + "_fixed.rle", "rle") g.show("[fixed]") countfixed += 1 else: g.save( os.path.join(outfolder, "p" + ("0000" + period)[-5:] + "_custom") + ".rle", "rle") countspecial += 1 r = g.getrect() else: datalist = basegun.split("_") if len(datalist) == 2:
def score_pair(g, seed1, seed2, width_factor, height_factor, \ time_factor, num_trials): """ Put seed1 and seed2 into the Immigration Game g and see which one wins and which one loses. Note that this function does not update the histories of the seeds. For updating histories, use update_history(). """ # # Make copies of the original two seeds, so that the following # manipulations do not change the originals. # s1 = copy.deepcopy(seed1) s2 = copy.deepcopy(seed2) # # Check the number of living cells in the seeds. If the number # is zero, it is probably a mistake. The number is initially # set to zero and it should be updated when the seed is filled # with living cells. We could use s1.count_ones() here, but # we're trying to be efficient by counting only once and # storing the count. # assert s1.num_living > 0 assert s2.num_living > 0 # # Initialize scores # score1 = 0.0 score2 = 0.0 # # Run several trials with different rotations and locations. # for trial in range(num_trials): # # Randomly rotate and flip s1 and s2 # s1 = s1.random_rotate() s2 = s2.random_rotate() # # Switch cells in the second seed (s2) from state 1 (red) to state 2 (blue) # s2.red2blue() # # Rule file # rule_name = "Immigration" # # Set toroidal universe of height yspan and width xspan # Base the s1ze of the universe on the s1zes of the seeds # # g = the Golly universe # [g_width, g_height, g_time] = dimensions(s1, s2, \ width_factor, height_factor, time_factor) # # set algorithm -- "HashLife" or "QuickLife" # g.setalgo("QuickLife") # use "HashLife" or "QuickLife" g.autoupdate(False) # do not update the view unless requested g.new(rule_name) # initialize cells to state 0 g.setrule(rule_name + ":T" + str(g_width) + "," + str(g_height)) # make a toroid # # Find the min and max of the Golly toroid coordinates # [g_xmin, g_xmax, g_ymin, g_ymax] = get_minmax(g) # # Set magnification for Golly viewer # g.setmag(set_mag(g)) # # Randomly place seed s1 somewhere in the left s1de of the toroid # s1.insert(g, g_xmin, -1, g_ymin, g_ymax) # # Randomly place seed s2 somewhere in the right s1de of the toroid # s2.insert(g, +1, g_xmax, g_ymin, g_ymax) # # Run for a fixed number of generations. # Base the number of generations on the sizes of the seeds. # Note that these are generations ins1de one Game of Life, not # generations in an evolutionary sense. Generations in the # Game of Life correspond to growth and decay of a phenotype, # whereas generations in evolution correspond to the reproduction # of a genotype. # g.run(g_time) # run the Game of Life for g_time time steps g.update() # need to update Golly to get counts # # Count the populations of the two colours. State 1 = red = seed1. # State 2 = blue = seed2. # [count1, count2] = count_pops(g) # # We need to make an adjustment to these counts. We don't want to # use the total count of living cells; instead we want to use # the increase in the number of living cells over the course of # the contest between the two organisms. The idea here is that # we want to reward seeds according to their growth during the # contest, not according to their initial states. This should # avoid an evolutionary bias towards larger seeds simply due # to size rather than due to functional properties. It should # also encourage efficient use of living cells, as opposed to # simply ignoring useless living cells. # # s1.num_living = initial number of living cells in s1 # s2.num_living = initial number of living cells in s2 # if (s1.num_living < count1): count1 = count1 - s1.num_living else: count1 = 0 # if (s2.num_living < count2): count2 = count2 - s2.num_living else: count2 = 0 # # Now we are ready to determine the winner. # if (count1 > count2): score1 = score1 + 1.0 elif (count2 > count1): score2 = score2 + 1.0 else: score1 = score1 + 0.5 score2 = score2 + 0.5 # # # Normalize the scores # score1 = score1 / num_trials score2 = score2 / num_trials # return [score1, score2]
g.show("Starting....") g.update() g.setstep(6) start_time = time.time() open(RESULTS_FN,"a").write("BOOTING..\n") PATTERN_FN = os.path.join(BASE_RESULTS_PATH, "pattern.dat") results = add_data(PATTERN_FN) open(RESULTS_FN,"a").write(results + "\n") boot_completed = False for x in range(0, 40): g.run(1000000) end_time = time.time() - start_time val_last_ins = g.getcell(-1575, 2049) val_cutoff = g.getcell(-1618, 1618) g.show("Took {} secs state = {}\n".format(end_time, val_last_ins)) g.update() if val_cutoff == 6: open(RESULTS_FN, "a+").write("System booted in {}\n".format(end_time, val_last_ins)) boot_completed = True break elif val_last_ins == 7: open(RESULTS_FN, "a+").write("#{} Bootup signal not sent \n".format(x+1, end_time)) break
def Main(self): g.show("left click on a pattern to change, 'h' for help") gollyMode = False while True: event = g.getevent() if ("key" in event and "return" in event) or (gollyMode and " a " in event): gollyMode = not gollyMode if gollyMode: g.show("In golly mode") g.update() else: g.show("left click on a pattern, right click to finish") g.setrule("B3/S23") g.setalgo("HashLife") g.reset() g.update() continue if gollyMode: if " delete " in event: g.clear(0) if "click" in event and "ctrl" in event and g.getxy() != "": x, y = g.getxy().split() cell = g.getcell(int(x), int(y)) if cell >= 0 and cell <= 1: g.setcell(int(x), int(y), 1 - cell) g.update() if " c " in event and "ctrl" in event and g.getselrect() != []: g.copy() if " v " in event and "ctrl" in event and g.getxy() != "": x, y = g.getxy().split() g.paste(int(x), int(y), "or") if " space " in event: if "ctrl" in event: g.run(10) else: g.run(1) g.doevent(event) continue if "click" in event: if "left" in event: if self.ExistinCircuitHandler() == None: if self.SignalClickHandler(event) == None: g.show("left click on a pattern, h for help") elif "key" in event: if " space " in event: for i in xrange(0, 30): g.run(60) g.update() g.reset() g.update() if " a " in event: if g.getrule() == "Perrier": g.setrule("B3/S23") g.setalgo("HashLife") g.update() else: g.setrule("Perrier") for key in self.smarCells: x, y = key.split(":") g.setcell(int(x), int(y), self.smarCells[key] + 2) gollyMode = True g.show("In golly mode") g.update() if " s " in event: fname = os.path.join(g.getdir("data"), "MetadataManager.json") #self.Save(fname) if " h " in event: noteMessage = "Viewing and Selecting\n\n" noteMessage += "'left click' to chose gun or glider\n" noteMessage += "'a' to see in colors, a to go back \n" noteMessage += "'space' see ahead 1800 generations \n" noteMessage += "'enter' gollyMode, stays in the script \n" noteMessage += "\n Editing Gun \n\n" noteMessage += "'left click' to place\n" noteMessage += "'right click' to switch gun/orientation \n" noteMessage += "'delete' to delete the gun \n" noteMessage += "'left-right arrow' - one step adjustment\n" noteMessage += "\n In Golly Mode \n\n" noteMessage += "'delete' to clear selection\n" noteMessage += "'ctrl' + 'click' to draw \n" noteMessage += "'ctrl' + 'c' to copy selection \n" noteMessage += "'ctrl' + 'v' to paste in mouse location \n" noteMessage += "'space' + to run 1 generation \n" noteMessage += "'ctrl' +'space' to run 10 generations \n" g.note(noteMessage)