def CreateWssMovementData(recipes, dir): result = [] g.show(str(len(recipes.WssCreator))) for i in xrange(0, len(recipes.WssCreator)): recipes.Reset() recipes.Goto(-23, 1) recipes.AddWss(i) PlaceReadingHeads(recipes.recipe) goto(150000) g.fit() g.update() x, y, res = FindWssByDirection(True, distForward)[0] x += 23 y += -21 y = y % distForward result.append((x, y, res)) pickle.dump(result, open(path.join(dir, str(step) + "_" + str(period) + "_ForwardWssBase.pkl"), "wb")) g.note(str(result))
def showhelp2(): g.note( """While moving the object the following keys can be used: x -- flip object left-right y -- flip object top-bottom > -- rotate object clockwise < -- rotate object anticlockwise h -- show this help escape -- abort and restore the object""")
def showhelp2(): g.note( """While moving the selection the following keys can be used: x -- flip selection left-right y -- flip selection top-bottom > -- rotate selection clockwise < -- rotate selection anticlockwise h -- show this help escape -- abort and restore the selection""")
def main(): # get selection and set to boundary bound = g.getselrect() if len( bound ) == 0: g.note( "No selection." ) g.exit() # get current Golly states left = bound[ 0 ] top = bound[ 1 ] width = bound[ 2 ] height = bound[ 3 ] for y in xrange( 0, height ): for x in xrange( 0, width ): state = g.getcell( left + x, top + y ) g.setcell( height - y - 600, x - 600, state )
def CreateWssMovementData(recipes, dir, isUp = True): result = [] for i in xrange(0, len(recipes.WssCreator)): g.show(str(i)) recipes.Reset() if isUp: recipes.Goto(-23, 1) recipes.AddWss(i) PlaceReadingHeads(recipes.recipe) goto(150000) g.fit() g.update() if isUp: x, y, res = FindWssByDirection(isUp, distForward)[0] x += 23 y += -21 y = y % distForward else: 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) + "_ForwardWssBase.pkl"), "wb")) else: pickle.dump(result, open(path.join(dir, str(step) + "_" + str(period) + "_BackwardWssBase.pkl"), "wb")) g.note(str(result))
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 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)
msg = '%d ships found after testing %d candidate rules out of 2^%d rule space' % ( Nfound, ii, rulespace) msg += ', %d rules/second' % (updateP / (curr_time - start_time)) start_time = curr_time g.show(msg) g.fit() g.setmag(3) g.update() event = g.getevent() if event == "key q none": # Interrupt the search # XXX Save the current state of the Rule generator's seed so that the search can be continued break g.new('') except IOError: g.note('Failed to open results file %s for writing!' % resultsFile) raise except Exception as e: raise finally: g.new('Search result') g.putcells(origPatt) if lastRule: g.setrule(lastRule) g.show('%d ships found after testing %d candidate rules.' % (Nfound, ii)) else: g.setrule(origRule) g.show('No results found after testing %d candidate rules.' % ii)
[startWd, endWd] = getIndices(wd) [startHt, endHt] = getIndices(ht) #formatStr = 'Width: {0} Height: {1}\nStart Pos: ({2},{3})\nEnd Pos:{4},{5}\np,q = {6} {7} ' #golly.note(formatStr.format(wd,ht,startWd,startHt,endWd,endHt,p,q)) # Only search the candidate matrix cells which can contain # the matrix we're searching for candidates = [(x,y) for x in range(startWd,endWd-cols+2) for y in range(startHt,endHt-rows+2)] for (iCol, iRow) in candidates: jCol = 0 jRow = 0 while(golly.getcell(iCol + jCol,iRow + jRow) == searchPatt[jRow][jCol]): if (jCol == cols-1) and (jRow == rows-1): print ' Match = ({0},{1})'.format(iCol,iRow) matches.append((iCol,iRow)) break jCol = jCol + 1 if (jCol > cols - 1): jCol = 0 jRow = jRow + 1 if (jRow > rows - 1): print ' Break = ({0},{1})'.format(iCol,iRow) break ## End of search space, and no match found return [matches, candidates] #golly.note('Vals = {0} {1}'.format(golly.getcell(0,0),golly.getcell(-2,0))) searchPattern = golly.getstring("Define a pattern to search for (enter as a Python list)", "[[1,0],[1,1],[0,0]]", "Enter A Pattern") [results, candidates] = bruteForceSearch(eval(searchPattern)) golly.note('Total Matches: {0}\nTotal Candidate Cells:{1}\n{2}'.format( len(results), len(candidates), results))
f = open(folder + rule_name + '.table','w') # write the initial descriptors and some variables f.write('# Emulation of Margolus neighbourhood for MCell string:\n# %s\n\n'%s) f.write('# (see: http://psoup.math.wisc.edu/mcell/rullex_marg.html )\n') f.write('#\n') f.write('# Rule table produced by convert-MCell-string.py, which can\n') f.write('# convert any MCell Margolus specification into a rule table.\n') f.write('#\n') f.write('n_states:2\nneighborhood:Margolus\nsymmetries:none\n\n') # the 16 cases of the (two-state) Margolus partition are: dot = (0,0,0,0),(1,0,0,0),(0,1,0,0),(1,1,0,0),(0,0,1,0),(1,0,1,0),(0,1,1,0),(1,1,1,0),\ (0,0,0,1),(1,0,0,1),(0,1,0,1),(1,1,0,1),(0,0,1,1),(1,0,1,1),(0,1,1,1),(1,1,1,1) # cell order: 1 2 # 3 4 # (see: http://psoup.math.wisc.edu/mcell/rullex_marg.html ) for i in range(16): if not i==becomes[i]: # (we can skip no-change transitions) f.write(','.join(map(str,dot[i]))+' : '+\ ','.join(map(str,dot[becomes[i]]))+\ ' # '+str(i)+' -> '+str(becomes[i])+'\n') f.close() # tell the user what we wrote, and what to do next g.note('Wrote file: '+folder+rule_name+'.table\n\n\ You can now use emulate-Margolus-table.py to emulate the rule table.')
def log( data ): g.note( json.dumps(data) )
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] cells = g.getcells(g.getrect()) curGunPeriod = PeriodCalculator() if curGunPeriod == -1: note("Failed to find gun period") g.exit("No gun found") edgeGlider = EdgeGlider() if edgeGlider == -1: g.note("Please orient the gun properly") g.exit("No glider found in bottom right corner") valueGun = GunArea(cells, curGunPeriod) g.show("The value = " + str(valueGun[0]) + ", The box = " + str(valueGun[2]) )
if grayscale_icons: deadrgb = (0, 0, 0) draw_icon_boxes(livestates, graystate) draw_icons(iconinfo31, deadrgb) draw_icons(iconinfo15, deadrgb) draw_icons(iconinfo7, deadrgb) # create missing icons by scaling up/down the existing icons if len(iconinfo31) == 0 and len(iconinfo15) > 0: create31x31icons() iconnote += "The 31x31 icons were created by scaling up the 15x15 icons.\n\n" if len(iconinfo15) == 0 and len(iconinfo31) > 0: create_smaller_icons(31, 15) iconnote += "The 15x15 icons were created by scaling down the 31x31 icons.\n\n" if len(iconinfo7) == 0: if len(iconinfo15) > 0: create_smaller_icons(15, 7) iconnote += "The 7x7 icons were created by scaling down the 15x15 icons.\n\n" elif len(iconinfo31) > 0: create_smaller_icons(31, 7) iconnote += "The 7x7 icons were created by scaling down the 31x31 icons.\n\n" g.setoption("showlayerbar", True) g.setoption("showallstates", True) g.setoption("showicons", False) g.fit() g.update() g.note(iconnote + "Edit the icons and then run icon-exporter.py.")
#!/usr/bin/env python2.6 # Q: http://www.hacker.org/challenge/chal.php?id=117 # A: http://www.hacker.org/challenge/chal.php?answer=821%2C319&id=117&go=Submit # Use Golly, a Game of Life simulator. It can be shown that after 1500 generations, the populations are always 116. So only need to search the first 1500 generations to find the max population. import golly as g GENERATION_NUM = 1500 max_population = -1 best_generation = -1 for generation in range(GENERATION_NUM): population = int(g.getpop()) if population > max_population: max_population = population best_generation = generation g.step() g.note('%d,%d' % (best_generation, max_population))
guns = GunsReader() cells = g.getcells(g.getrect()) curGunPeriod = PeriodCalculator() g.show("Calculating Period...") g.update() if curGunPeriod == -1: note("Failed to find gun period") g.exit("No gun found") edgeGlider = EdgeGlider() if edgeGlider == -1: g.note("Please orient the gun properly") g.exit("No glider found in bottom right corner") g.show("searching box for your gun...") g.update() valueGun = GunArea(cells, curGunPeriod) g.show("searching box for known gun...") g.update() dbValue = GunArea(guns[curGunPeriod - 14], curGunPeriod) if dbValue[0] > valueGun[0]:
f = open(folder + rule_name + '.table','w') # write the initial descriptors and some variables f.write('# Emulation of Margolus neighbourhood for MCell string:\n# %s\n\n'%s) f.write('# (see: http://psoup.math.wisc.edu/mcell/rullex_marg.html )\n') f.write('#\n') f.write('# Rule table produced by convert-MCell-string.py, which can\n') f.write('# convert any MCell Margolus specification into a rule table.\n') f.write('#\n') f.write('n_states:2\nneighborhood:Margolus\nsymmetries:none\n\n') # the 16 cases of the (two-state) Margolus partition are: dot = (0,0,0,0),(1,0,0,0),(0,1,0,0),(1,1,0,0),(0,0,1,0),(1,0,1,0),(0,1,1,0),(1,1,1,0),\ (0,0,0,1),(1,0,0,1),(0,1,0,1),(1,1,0,1),(0,0,1,1),(1,0,1,1),(0,1,1,1),(1,1,1,1) # cell order: 1 2 # 3 4 # (see: http://psoup.math.wisc.edu/mcell/rullex_marg.html ) for i in range(16): if not i==becomes[i]: # (we can skip no-change transitions) f.write(','.join(map(str,dot[i]))+' : '+\ ','.join(map(str,dot[becomes[i]]))+\ ' # '+str(i)+' -> '+str(becomes[i])+'\n') f.close() # tell the user what we wrote, and what to do next g.note('Wrote file: '+folder+rule_name+'.table\n\n\ You can now use RuleTableToTree.py to emulate the rule table.')
import KBs import random, re, os # rulestr=golly.getstring('NTCA number',golly.getclipstr()).split('_')[-1]; kb = KBs.kb_2dntca() # alias = golly.getrule() prefix, curr, suffix = KBs.interpret(golly.getrule().split(':')) prefix = 'rev_' rulestr = kb.alias2rulestr(curr) # bitstr = KBs.hex2bin(rulestr,102) # # assert KBs.bin2hex(bitstr)==rulestr # bitlst = list(bitstr) # idx = random.randrange(102) # flip = {'0':'1','1':'0'} # bitlst[idx] = flip[bitlst[idx]] # rulestr = KBs.bin2hex(''.join(bitlst)) alias = kb.rulestr2alias(rulestr) if 1: DIR = golly.getdir('rules') fname = os.path.join(DIR, prefix + alias + '.rule') with open(fname, 'w') as f: print >> f, kb.rulestr2table(rulestr, reverse=1) newrule = '%s%s:%s' % (prefix, alias, suffix) golly.note(newrule) golly.setclipstr(newrule.split(':')[0]) golly.setrule(newrule)
def export_icons(iconsection, rulename): global multi_color_icons if multi_color_icons: # prepend a new @COLORS section with the average colors in each icon iconsection = create_average_colors(iconsection) + iconsection # replace any illegal filename chars with underscores filename = rulename.replace("/","_").replace("\\","_") # we will only create/update a .rule file in the user's rules folder # (ie. we don't modify the supplied Rules folder) rulepath = g.getdir("rules") + filename + ".rule" fileexists = os.path.isfile(rulepath) if fileexists: # .rule file already exists so replace or add @ICONS section rulefile = open(rulepath,"rU") # create a temporary file for writing new rule info temphdl, temppath = mkstemp() tempfile = open(temppath,"w") wroteicons = False skiplines = False for line in rulefile: if line.startswith("@ICONS"): # replace the existing @ICONS section tempfile.write(iconsection) wroteicons = True skiplines = True elif line.startswith("@COLORS") and multi_color_icons: # skip the existing @COLORS section # (iconsection contains a new @COLORS section) skiplines = True elif skiplines and line.startswith("@"): if wroteicons: tempfile.write("\n") skiplines = False if not skiplines: tempfile.write(line) if not wroteicons: # .rule file had no @ICONS section tempfile.write("\n") tempfile.write(iconsection) # close files rulefile.close() tempfile.flush() tempfile.close() os.close(temphdl) # remove original .rule file and rename temporary file os.remove(rulepath) move(temppath, rulepath) else: # .rule file doesn't exist so create it rulefile = open(rulepath,"w") rulefile.write("@RULE " + filename + "\n\n") if not multi_color_icons: # grayscale icons, so check if Rules/filename.rule exists # and if so copy any existing @COLORS section suppliedrule = g.getdir("app") + "Rules/" + filename + ".rule" if os.path.isfile(suppliedrule): colordata = get_color_section(suppliedrule) if len(colordata) > 0: rulefile.write(colordata) rulefile.write(iconsection) rulefile.flush() rulefile.close() # create another layer for displaying the new icons if g.numlayers() < g.maxlayers(): g.addlayer() g.new("icon test") g.setrule(rulename) for i in xrange(g.numstates()-1): g.setcell(i, 0, i+1) g.fit() g.setoption("showicons",True) g.update() if fileexists: g.note("Updated the icon data in " + rulepath) else: g.note("Created " + rulepath)
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 showhelp1(): g.note( """Hit the escape key to abort the script. Note that alt-clicking in the selection allows you to COPY it to another location (the original selection is not deleted).""")
if grayscale_icons: deadrgb = (0,0,0) draw_icon_boxes(livestates, graystate) draw_icons(iconinfo31, deadrgb) draw_icons(iconinfo15, deadrgb) draw_icons(iconinfo7, deadrgb) # create missing icons by scaling up/down the existing icons if len(iconinfo31) == 0 and len(iconinfo15) > 0: create31x31icons() iconnote += "The 31x31 icons were created by scaling up the 15x15 icons.\n\n" if len(iconinfo15) == 0 and len(iconinfo31) > 0: create_smaller_icons(31, 15) iconnote += "The 15x15 icons were created by scaling down the 31x31 icons.\n\n" if len(iconinfo7) == 0: if len(iconinfo15) > 0: create_smaller_icons(15, 7) iconnote += "The 7x7 icons were created by scaling down the 15x15 icons.\n\n" elif len(iconinfo31) > 0: create_smaller_icons(31, 7) iconnote += "The 7x7 icons were created by scaling down the 31x31 icons.\n\n" g.setoption("showlayerbar",True) g.setoption("showallstates",True) g.setoption("showicons",False) g.fit() g.update() g.note(iconnote + "Edit the icons and then run icon-exporter.py.")
def choose_pickles(g): """ Present a GUI to ask the users which folder of pickles they would like to analyze. """ # # Open a dialog window and ask the user to select two folders. # g.note("Analyze Pickles\n\n" + \ "You will be presented with two dialog menus:\n\n" + \ " (1) Select a FOLDER of pickled seeds.\n" + \ " (2) Select a FOLDER for storing the analysis results.\n\n" + \ "The pickles will be analyzed and the results will be stored.\n") # pickle_dir = g.opendialog("Choose a folder of pickled seeds", \ "dir", g.getdir("app")) analysis_dir = g.opendialog("Choose a folder for the analysis", \ "dir", g.getdir("app")) # g.note("Verify Selection\n\n" + \ "The chosen folder of pickled seeds:\n\n" + \ " " + pickle_dir + "\n\n" + \ "The chosen folder for the analysis results:\n\n" + \ " " + analysis_dir + "\n\n" + \ "Exit now if these folders are incorrect.") # # Make a list of the pickles in pickle_dir. # pickle_list = [] for file in os.listdir(pickle_dir): if file.endswith(".bin"): pickle_list.append(file) # # Verify that there are some ".bin" files in the list. # if (len(pickle_list) == 0): g.note("No pickles were found in the directory:\n\n" + \ " " + pickle_dir + "\n\n" + \ "Exiting now.") sys.exit(0) # # Make a hash table that maps pickle names to the last # generation number of the given group of pickles. # pickle_hash = hash_pickles(pickle_list) # # Calculate the size of the smallest group of pickles. # smallest_pickle_size = min(pickle_hash.values()) # # Report the base parts of the pickles and their maximum # values # sorted_pickle_names = sorted(pickle_hash.keys()) pickle_note = "" for pickle_base in sorted_pickle_names: pickle_note = pickle_note + \ pickle_base + " ranges from 0 to " + \ str(pickle_hash[pickle_base]) + "\n" g.note("These pickles were found:\n\n" + pickle_note + "\n" + \ "The analysis will range from 0 to " + \ str(smallest_pickle_size) + "\n\n" + \ "Exit now if this is not what you expected.") # return [pickle_dir, analysis_dir, \ sorted_pickle_names, smallest_pickle_size]
def topopup(self, text): """ Outputs text to a popup in Golly :param text: text to be output """ g.note(text)
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")