def testkey(): if results and g.getevent().startswith("key x"): g.setlayer(results_layer) g.select(g.getrect()) g.copy() g.select([]) g.setlayer(work_layer)
def lookforkeys(event, deltax, deltay): global oldcells, selrect, selpatt # look for keys used to flip/rotate selection if event == "key x none" or event == "key y none": # flip floating selection left-right or top-bottom if len(oldcells) > 0: g.clear(0) g.putcells(selpatt, deltax, deltay) if " x " in event: g.flip(0) else: g.flip(1) selpatt = g.transform(g.getcells(selrect), -deltax, -deltay) if len(oldcells) > 0: g.clear(0) g.putcells(oldcells) g.putcells(selpatt, deltax, deltay) g.update() return if event == "key > none" or event == "key < none": # rotate floating selection clockwise or anticlockwise; # because we use g.rotate below we have to use the exact same # calculation (see Selection::Rotate in wxselect.cpp) for rotrect: midx = selrect[0] + int((selrect[2]-1)/2) midy = selrect[1] + int((selrect[3]-1)/2) newleft = midx + selrect[1] - midy newtop = midy + selrect[0] - midx rotrect = [ newleft, newtop, selrect[3], selrect[2] ] if not rectingrid(rotrect): g.warn("Rotation is not allowed if selection would be outside grid.") return g.clear(0) if len(oldcells) > 0: g.putcells(oldcells) oldcells = g.join(oldcells, g.getcells(rotrect)) g.clear(0) g.select(rotrect) g.clear(0) g.select(selrect) g.putcells(selpatt, deltax, deltay) if " > " in event: g.rotate(0) else: g.rotate(1) selrect = g.getselrect() if selrect != rotrect: g.warn("Bug: selrect != rotrect") selpatt = g.transform(g.getcells(selrect), -deltax, -deltay) if len(oldcells) > 0: g.clear(0) g.putcells(oldcells) g.putcells(selpatt, deltax, deltay) g.update() return if event == "key h none": showhelp2() return g.doevent(event)
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 draw(self): xy = [] xz = [] yz = [] proj = [] for (k, v) in self.cur_state.items(): x, y, z = k xy.append(x) xy.append(y) xz.append(x + 128) xz.append(z) yz.append(y) yz.append(z + 128) proj.append(x + y + z + 128) proj.append(-x + y + z + 128) if len(g.getrect()) > 0: g.select(g.getrect()) g.clear(0) g.select([]) g.putcells(xy) g.putcells(xz) g.putcells(yz) g.putcells(proj) g.setpos("64", "64") g.setmag(1) g.update()
def loadtopo(maxnum,step,boxwidth): global pboxlist tile=[] for i in range(step,maxnum+step,step): make_text(str(i)).put(boxwidth*(i-1),0) box.put(boxwidth*(i-1),0) boxsel=[boxwidth*(i-1)+1,1,38,38] g.select(boxsel) g.shrink() if g.getselrect()==boxsel: continue else: sel=g.getselrect() pbox=g.getselrect() clist=g.getcells(pbox) for i in range(int(len(clist)/3)): clist[3*i] = clist[3*i]-sel[0] clist[3*i+1] = clist[3*i+1]-sel[1] clist.insert(0,sel[2]) clist.insert(1,sel[3]) tile.append(clist) pboxlist.append(pbox) return tile
def paste(g, fichier, x, y): g.addlayer() g.open(fichier) g.select([-1000, -1000, 2000, 2000]) g.copy() g.dellayer() g.paste(x - 1000, y - 1000, 'or')
def draw(self, addstr = ""): xy = [] xz = [] yz = [] proj = [] for (k, v) in self.cur_state.items(): x, y, z = k xy.append(x) xy.append(y) xz.append(x + 128) xz.append(z) yz.append(y) yz.append(z + 128) proj.append(x + y + z + 128) proj.append(- x + y + z + 128) if len(g.getrect()) > 0: g.select(g.getrect()) g.clear(0) g.select([]) g.putcells(xy) g.putcells(xz) g.putcells(yz) g.putcells(proj) g.setpos("64", "64") g.setmag(1) g.show("Size: {0}, (w, d, h): {1}".format(self.get_pop(), str(self.get_wdh())) + addstr) g.update()
def clearlayer(): r = g.getrect() if r: g.select(r) g.clear(0) if withB0: # Needed with B0 rules to ensure pattern runs correctly g.setgen('0')
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 add_data(PATTERN_FN): g.select([-2753, 891, 1092, 1397]) g.clear(0) g.select([]) input_str = open(PATTERN_FN, "r").read() firstbreak = input_str.find("\n") if firstbreak == -1: g.show("Error, no newlines found, invalid format") g.exit() info_line = input_str[0:firstbreak] input_str = input_str[firstbreak:] #x = 1581, y = 1396, rule = Varlife dataptrn = re.compile( br'x = (?P<xval>[0-9]{1,4}), y = (?P<yval>[0-9]{1,4}), rule = .*') match = dataptrn.match(info_line) xval = 0 yval = 0 if (match): xval = int(match.group("xval"), 10) yval = int(match.group("yval"), 10) else: g.show("ERROR invalid format {}".format(info_line)) g.exit() ipat = pattern(input_str) minbox = getminbox(ipat) if max(xval, minbox.x) > 1200: g.show("ERROR inserted cell area too wide, max width is 1090") g.exit() if max(yval, minbox.y) > 1397: g.show("ERROR inserted cell area too tall, max height is 1397") g.exit() startx = -1661 - xval starty = 891 #blankptrn.put(startx, starty) g.show( "width={}, height={} startx={}, starty={}, xval={}, yval={}, bytes={}". format(minbox.wd, minbox.height, startx, starty, xval, yval, len(input_str))) ipat.put(startx, starty) g.save("/tmp/output.mc", "rle", False) return "Pattern load data: width={}, height={} startx={}, starty={}, xval={}, yval={}, bytes={}".format( minbox.wd, minbox.height, startx, starty, xval, yval, len(input_str))
def select_rectangle_for_borders(self, startx, starty, width, height): """ Selects the grid to have a border set around it :param startx: Starting x position of the grid :param starty: Starting y position of the grid :param width: Width of the grid :param height: Height of the grid """ g.select([startx, starty, width, height])
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 GunsReader(): result = [] for i in xrange(0, 10000): cells = g.getcells([0, i * 650, 500, 550]) if len(cells) == 0: return result g.select([-200, i * 650 - 10, 800, 550]) g.clear(0) result.append(cells)
def shrink(): global d if g.empty(): return g.select(g.getrect()) d=int(10000*float(g.getpop())/(int(g.getselrect()[2])*int(g.getselrect()[3]))) while d<100: bbox=g.getselrect() bbox[0]=bbox[0]+1 bbox[1]=bbox[1]+1 bbox[2]=bbox[2]-2 bbox[3]=bbox[3]-2 g.select(bbox) g.shrink() d=int(10000*float(g.getpop())/(int(g.getselrect()[2])*int(g.getselrect()[3])))
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 write(asm): binary = translateAll(asm) g.open("computer.mc") g.duplicate() g.setname("programmed", 0) g.movelayer(1, 0) g.dellayer() g.select([-25950, 1890, 450, 240]) g.cut() for i in range(len(binary)): for j in range(21): if int(binary[i][j]): g.select([-23639+i*600+j*300, 2159+i*600-j*300, 450, 240]) g.clear(0) g.paste(-23639+i*600+j*300, 2159+i*600-j*300, "or")
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 loadtopo(): for i in range(step, max + step, step): make_text(str(i)).put(boxwidth * (i - 1), 0) box.put(boxwidth * (i - 1), 0) boxsel = [boxwidth * (i - 1) + 1, 1, 38, 38] g.select(boxsel) g.shrink() if g.getselrect() == boxsel: continue else: clist = g.getcells(g.getselrect()) sel = g.getselrect() for i in range(int(len(clist) / 3)): clist[3 * i] = clist[3 * i] - sel[0] clist[3 * i + 1] = clist[3 * i + 1] - sel[1] clist.insert(0, sel[2]) clist.insert(1, sel[3]) tile.append(clist) return tile
def canon5Sship(ship, maxgen=2000): minpop, rulestr, dx, dy, period, shiprle = ship shipPatt = g.parse(shiprle) # Transform ship to canonical direction if abs(dx) >= abs(dy): a, b, c, d = sign(dx), 0, 0, sign(dy) else: a, b, c, d = 0, sign(dy), sign(dx), 0 dy, dx = minmaxofabs((dx, dy)) shipPatt = g.transform(shipPatt, 0, 0, a, b, c, d) # Clear the layer and place the ship r = g.getrect() if r: g.select(r) g.clear(0) g.putcells(shipPatt) shiprle = giveRLE(g.getcells(g.getrect())) g.setrule(rulestr) # Determine the minimal isotropic rule setminisorule(period) return minpop, g.getrule(), dx, dy, period, shiprle
def tileit(clist,tilewd): global inc,pbox cliplist=clist # g.select([boxsel[0]-20,boxsel[1]-20,20,20]) # g.clear(0) # make_text(str(posi)).put(boxsel[0]-20,boxsel[1]) pbox = rect( [0, 0] + cliplist[0 : 2] ) wd=tilewd*pbox.wd ht=tilewd*pbox.ht boxsel=[-int(wd/2),-int(wd/2),wd,ht] g.select(boxsel) selrect = rect( g.getselrect() ) inc=2 cliplist[0 : 2] = [] # remove wd,ht p = pattern( cliplist ) if len(cliplist) & 1 == 1: inc = 3 # multi-state? g.clear(inside) if len(cliplist) > 0: # tile selrect with p, clipping right & bottom edges if necessary y = selrect.top while y <= selrect.bottom: bottom = y + pbox.height - 1 x = selrect.left while x <= selrect.right: right = x + pbox.width - 1 if (right <= selrect.right) and (bottom <= selrect.bottom): p.put(x, y) else: clip_rb( p(x, y), selrect.right, selrect.bottom ).put() x += pbox.width y += pbox.height if not selrect.visible(): g.fitsel()
def setupT(dhead, binaryStr, dx, dy): setupR(dhead, dx, dy) setupR(len(binaryStr) - 1 - dhead, dx + 310, dy - 506) setupR(dhead * 16, dx + 130, dy - 3286) setupR(dhead * 16, dx - 1113, dy - 2062) if len(binaryStr) == 0: return x = dx + 142 y = dy - 3305 g.select([x, y, 3, 3]) g.clear(0) for i in range(len(binaryStr)): if binaryStr[i] == '0': g.putcells(boat, x, y) else: g.putcells(boat, x - 3, y - 3) x -= 16 y -= 16
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 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 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)
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
rawentry2 = g.getstring( "What is the maximum number of generations to run each soup?") rawentry3 = g.getstring("How many soups do you want to test?") periodlist = map(int, rawentry1.split(',')) maxgens = int(rawentry2) soups = int(rawentry3) 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:
def CreateWssMovementData(recipes, dir, isUp = True): result = [] for i in xrange(0, len(recipes.WssCreator)): recipes.Reset() if isUp: recipes.Goto(-23, 1) recipes.AddWss(i) PlaceReadingHeads(recipes.recipe) if isUp: gen = period * (len(recipes.recipe) + 10) while gen % (2 * distForward) != 0: gen += 1 goto(gen) g.fit() g.update() rect = g.getrect() g.select([rect[0], -6 * distBack, rect[2], 7 * distBack]) g.clear(1) x, y, res = FindWssByDirection(isUp, distForward)[0] x += 23 y += -21 y = y % distForward else: gen = period * (len(recipes.recipe) + 10) while gen % (2 * distBack) != 0: gen += 1 goto(gen) g.fit() g.update() rect = g.getrect() helixy = CalcHelix(recipes.recipe) g.select([rect[0], helixy - distBack, rect[2], 7 * distBack]) g.clear(1) x, y, res = FindWssByDirection(isUp, distBack)[0] y = y % distBack result.append((x, y, res)) if isUp: pickle.dump(result, open(path.join(dir, str(step) + "_" + str(period) + "_ForwardWssBaseAuto.pkl"), "wb")) else: pickle.dump(result, open(path.join(dir, str(step) + "_" + str(period) + "_BackwardWssBaseAuto.pkl"), "wb")) recipes.Reset()
def moveselection(): global oldcells, selrect, selpatt # wait for 1st click in selection while True: event = g.getevent() if event.startswith("click"): # event is a string like "click 10 20 left none" evt, xstr, ystr, butt, mods = event.split() x = int(xstr) y = int(ystr) if cellinrect(x, y, selrect): oldmouse = xstr + ' ' + ystr firstx = x firsty = y xoffset = firstx - selrect[0] yoffset = firsty - selrect[1] if mods == "alt": # don't delete pattern in selection oldcells = g.getcells(selrect) break elif event == "key h none": showhelp1() else: g.doevent(event) # wait for 2nd click while moving selection g.show("Move mouse and click again..." + helpmsg) gotclick = False while not gotclick: event = g.getevent() if event.startswith("click"): evt, x, y, butt, mods = event.split() mousepos = x+' '+y gotclick = True else: if len(event) > 0: lookforkeys(event, x - firstx, y - firsty) # update xoffset,yoffset in case selection was rotated xoffset = x - selrect[0] yoffset = y - selrect[1] mousepos = g.getxy() if len(mousepos) > 0 and mousepos != oldmouse: # mouse has moved, so move selection rect and pattern g.clear(0) if len(oldcells) > 0: g.putcells(oldcells) xstr, ystr = mousepos.split() x = int(xstr) y = int(ystr) selrect[0] = x - xoffset selrect[1] = y - yoffset if g.getwidth() > 0: # ensure selrect doesn't move beyond left/right edge of grid if selrect[0] < gridl: selrect[0] = gridl x = selrect[0] + xoffset elif selrect[0] + selrect[2] - 1 > gridr: selrect[0] = gridr + 1 - selrect[2] x = selrect[0] + xoffset if g.getheight() > 0: # ensure selrect doesn't move beyond top/bottom edge of grid if selrect[1] < gridt: selrect[1] = gridt y = selrect[1] + yoffset elif selrect[1] + selrect[3] - 1 > gridb: selrect[1] = gridb + 1 - selrect[3] y = selrect[1] + yoffset g.select(selrect) oldcells = g.getcells(selrect) g.putcells(selpatt, x - firstx, y - firsty) oldmouse = mousepos g.update()
g.update() # ------------------------------------------------------------------------------ selrect = g.getselrect() if len(selrect) == 0: g.exit("There is no selection.") selpatt = g.getcells(selrect) # remember initial selection in case user aborts script firstrect = g.getselrect() firstpatt = g.getcells(selrect) g.show("Click anywhere in selection, move mouse and click again..." + helpmsg) oldcursor = g.getcursor() g.setcursor("Move") oldcells = [] try: aborted = True moveselection() aborted = False finally: g.setcursor(oldcursor) if aborted: g.clear(0) if len(oldcells) > 0: g.putcells(oldcells) g.putcells(firstpatt) g.select(firstrect) else: g.show(" ")
def __init__(self): try: g.show('setting up test') testSize = 100 #this is the size of one side of the square testing area g.select([-testSize/2,-testSize/2,testSize,testSize]) #clear the canvas g.clear(1) g.clear(0) g.randfill(50) g.update() g.show('stressTest started') startTime = time() lg_envmt = lifegenes_environment() endTime = time() logging.debug('\tsetup t\t=\t\t'+str(endTime-startTime)) g.update() startTime = time() lg_envmt.drawColor() endTime = time() logging.debug('\tcolorDraw t\t=\t' + str( endTime - startTime)) g.update() startTime = time() lg_envmt.cellMotions() endTime = time() logging.debug('\tmovement t\t=\t' + str( endTime - startTime)) g.update() startTime = time() lg_envmt.drawColor() endTime = time() logging.debug('\tcolor update t \t= ' + str( endTime - startTime)) g.update() g.step() startTime = time() lg_envmt.update() endTime = time() logging.debug('\tevolve update t\t= ' + str( endTime - startTime)) startTime = time() lg_envmt.cellMotions() endTime = time() logging.debug('\tmovement t\t=\t' + str( endTime - startTime)) g.update() startTime = time() lg_envmt.drawColor() endTime = time() logging.debug('\tcolor update t\t= ' + str( endTime - startTime)) g.update() g.update() g.show('test complete') finally: logging.info('cycling halted from external source (probably golly)')
def CreateWssMovementData(recipes, dir, isUp=True): result = [] for i in xrange(0, len(recipes.WssCreator)): recipes.Reset() if isUp: recipes.Goto(-23, 1) recipes.AddWss(i) PlaceReadingHeads(recipes.recipe) if isUp: gen = period * (len(recipes.recipe) + 10) while gen % (2 * distForward) != 0: gen += 1 goto(gen) g.fit() g.update() rect = g.getrect() g.select([rect[0], -6 * distBack, rect[2], 7 * distBack]) g.clear(1) x, y, res = FindWssByDirection(isUp, distForward)[0] x += 23 y += -21 y = y % distForward else: gen = period * (len(recipes.recipe) + 10) while gen % (2 * distBack) != 0: gen += 1 goto(gen) g.fit() g.update() rect = g.getrect() helixy = CalcHelix(recipes.recipe) g.select([rect[0], helixy - distBack, rect[2], 7 * distBack]) g.clear(1) x, y, res = FindWssByDirection(isUp, distBack)[0] y = y % distBack result.append((x, y, res)) if isUp: pickle.dump( result, open( path.join( dir, str(step) + "_" + str(period) + "_ForwardWssBaseAuto.pkl"), "wb")) else: pickle.dump( result, open( path.join( dir, str(step) + "_" + str(period) + "_BackwardWssBaseAuto.pkl"), "wb")) recipes.Reset()
halfbreeder = pattern("2bo$bo$2o3b2o$obo3b2o$bo3b2o$5bo!",0,1) breeder=halfbreeder + halfbreeder(0,14,flip_y) hwss=pattern("2b2o$o4bo$6bo$o5bo$b6o!") mwss=pattern("2bo$o3bo$5bo$o4bo$b5o!") lwss=pattern("o2bo$4bo$o3bo$b4o!",0,1) glider=pattern("b2o$obo$2bo!",0,1) breederpuffer = breeder(15,-45) + hwss(16,-30) + hwss(16,-46,flip_y)\ + hwss(5,-54) + hwss(5,-22,flip_y) breederrake11 = breederpuffer(71,37) + lwss(66,20,flip_y)\ + mwss(51,12,flip_y) + mwss(51,-14) breederrake00 = breederrake11 + mwss(-9,10,flip_y) + mwss(-9,-12) breederrake01 = breederrake11 + mwss(-9,-12) breederrake10 = breederrake11 + mwss(-9,10,flip_y) g.new("breeder.life") g.select([400,50,600,350]) g.fitsel() g.select(getminbox(breederrake11(314,242))) pause(.5) breederrake11.put(314,242) pause(.5) g.select(getminbox(breederrake11(312,201,flip_y))) runn(4,.01) breederrake11.put(312,201,flip_y) pause(.5) g.select(getminbox(breederrake00(368,286))) runn(101,.01) breederrake00.put(368,286) pause(.5) g.select(getminbox(breederrake10(359,158,flip_y))) runn(33,.01)
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))
def main (): g.update () g.check (False) path = g.getstring ("Output directory:") files = glob.glob (os.path.join (path, "*.out")) mingls = g.getstring ("Min number of gliders at accept:") if mingls == "": mingl = 0 minpop = 0 maxpop = 1024 else: mingl = int (mingls) minpops = g.getstring ("Min population except catalyzers:") if minpops == "": minpop = 0 maxpop = 1024 else: minpop = int (minpops) maxpop = int (g.getstring ("Max population except catalyzers:")) if g.getname () != "catbellman_temp": g.addlayer () hashdir = {} catlist = [] catix = 0 g.new ("catbellman_temp") g.setrule ("LifeBellman") for fix, filename in enumerate (files): patt = g.getrect () if patt != []: g.select (patt) g.clear (0) g.setgen ("0") with open(filename, 'r') as f: filetext = f.read () if fix % 16 == 0: g.show ("Analysing " + str (fix) + "/" + str (len (files))) (gogen, glcnt) = convbellman (filetext, 0, 0) if gogen == -1: gogen = 128 (use, hash) = analyse (gogen, glcnt, minpop, maxpop, mingl) if use: if not hash in hashdir: catlist.append ([]) hashdir [hash] = catix catix += 1 cat = hashdir [hash] catlist [cat].append (filetext) g.new ("catbellman_temp") g.setrule ("LifeBellman") fix = 0 y = 0 for cat in catlist: x = 96 * (len (cat) - 1) for filetext in cat: convbellman (filetext, x, y) x -= 96 fix += 1 if fix % 32 == 0: g.show ("Rendering " + str (fix) + "/" + str (len (files))) g.fit () g.check (True) g.update () g.check (False) y += 96 g.show ("Done") g.fit () g.setstep (-1) g.check (True)
g.update() if g.getcell(signal[0], signal[1]) == 1: done = 1 g.run(finaladjustment) g.run(100 * iperiod / subperiod) if subperiod > 1 and outputmatch(output) != 1: countdown = subperiod g.setgen("0") while countdown >= 0: countdown -= 1 g.run(iperiod / subperiod) if outputmatch(output) == 1: break if outputmatch(output) != 1: g.exit("Looks like something went wrong at period " + period \ + ". Output is not showing up after any reasonable number of subperiod cycles.") g.select(r) g.clear(1) g.select([]) g.setgen("0") g.show("Done! " + os.path.join(outfolder, str(period))) g.putcells(fixedbb) g.putcells(movablebb, iadjustment * dx, iadjustment * dy) g.save( os.path.join( outfolder, "p" + str(iperiod + 100000)[1:] + "_" + basegun + ".rle"), "rle") countbuilt += 1 #check we get the expected size if usebb == 1:
if g.getrule() != 'LifeHistory': g.exit('The rule should be in LifeHistory.') # Get catalyst in various positions if g.getselrect() != []: g.shrink() pattern = g.getcells(r) patrlelist = [] translist =[(1,0,0,1), (1,0,0,-1), (-1,0,0,1), (-1,0,0,-1), (0,1,1,0), (0,-1,1,0), (0,1,-1,0), (0,-1,-1,0)] # Get unique transformed patterns for trans in translist: g.new('') g.putcells(g.transform(pattern, 0, 0, *trans)) g.select(g.getrect()) g.copy() patrle = ''.join(g.getclipstr().split('\n')[1:]) if patrle not in patrlelist: patrlelist.append(patrle) patrles = '\n'.join(patrlelist) # Save data to file catpath = g.savedialog('Catalyst File', 'all files(*.*)|*', catdir) try: with open(catpath, 'w') as catfile: catfile.write(patrles) g.exit('Catalyst file successfully generated at {}'.format(catpath)) except: if catpath == '': g.setclipstr(patrles)
# Use the current selection to create a toroidal universe. # Author: Andrew Trevorrow ([email protected]), Sept 2010. from glife import inside, outside import golly as g selrect = g.getselrect() if len(selrect) == 0: g.exit("There is no selection.") x = selrect[0] y = selrect[1] wd = selrect[2] ht = selrect[3] selcells = g.getcells(selrect) if not g.empty(): g.clear(inside) g.clear(outside) # get current rule, remove any existing suffix, then add new suffix rule = g.getrule().split(":")[0] g.setrule(rule + ":T" + str(wd) + "," + str(ht)) newx = -int(wd/2) newy = -int(ht/2) selrect[0] = newx selrect[1] = newy g.select(selrect) if len(selcells) > 0: g.putcells(selcells, newx - x, newy - y) g.fitsel()
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()
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
''' setconf2.py clears grid and sets just as specified by configuration conf2 in parameters.py ''' import parameters reload(parameters) from parameters import conf2, nstates from golly import setcell, clear, select, getrect, fit, show if len(getrect()) > 0: select(getrect()) clear(0) for i in range(0,len(conf2),2): c = conf2[i] if i+1 < len(conf2): c += conf2[i+1] * nstates setcell(i//2,0,c) show(str(i)) select([]) fit()
l = len(recipes.recipe) * step iters = int(l / speed + l * 2 + l * (1 + 2 * speed) / (0.5 - speed)) iters = (1 + int(iters / distForward)) * distForward g.show("Iterating Tail to reach " + str(iters) + " iter") g.fit() g.update() #The speed is negative Head = -speed * iters + 576 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)
while i < w: j = 0 while j < h: g.setcell(i, j, update[i][j]) j += 1 i += 1 g.update() return update try: g.new("Conway's Game of life") g.setrule("Life") g.setcolors([1, 255, 255, 255]) g.setcolors([0, 0, 0, 0]) maxsize = 100000 count = 0 width = int( g.getstring("Enter a width for the game of life:", "100") ) height = int( g.getstring("Enter a height for the game of life:", "100") ) g.select([0, 0, width, height]) g.randfill(50) update = [[0 for x in range(width + 1)] for x in range(height + 1)] while count < maxsize: g.show("In main " + str(count)) update = main(width, height, update) count += 1 finally: g.note("Goodbye")