Exemple #1
0
    def Remove(self, phisSig):

        for i in xrange(0, len(phisSig.signal), 2):
            xs = phisSig.signal[i]
            ys = phisSig.signal[i + 1]

            g.setcell(phisSig.x + xs, phisSig.y + ys, 0)
Exemple #2
0
def rp_plot(input, fill=3):
    m = len(input)
    for i in range(m):
        for j in range(m):
            d = norm(input[i], input[j])
            if d <= dmax:
                g.setcell(i, -j, fill)
	def Remove(self, phisSig):
		
		for i in xrange(0, len(phisSig.signal), 2):
			xs = phisSig.signal[i]
			ys = phisSig.signal[i + 1] 
			
			g.setcell(phisSig.x + xs, phisSig.y + ys, 0)
Exemple #4
0
def draw_icons(iconinfo, transparent):
    global colorstate
    if len(iconinfo) == 0: return
    width = iconinfo[0]
    height = iconinfo[1]
    num_colors = iconinfo[2]
    chars_per_pixel = iconinfo[3]
    colordict = iconinfo[4]
    pos = 5
    numicons = height/width
    for i in xrange(numicons):
        x = i*32
        y = 0
        if width == 15: y = 32
        if width == 7: y = 48
        for row in xrange(width):
            pxls = iconinfo[pos]
            pos += 1
            for col in xrange(width):
                offset = col*chars_per_pixel
                key = pxls[offset : offset + chars_per_pixel]
                if not key in colordict:
                    g.exit("Unexpected key in icon data: " + key)
                rgb = colordict[key]
                if rgb != transparent:
                    g.setcell(x+col, y+row, colorstate[rgb])
Exemple #5
0
def create_smaller_icons(big, small):
    # scale down the big x big bitmaps into small x small bitmaps
    # using a simple sampling algorithm
    global iconinfo15, iconinfo31
    if big == 15:
        numicons = iconinfo15[1] / 15
        ybig = 32
    else:
        # big = 31
        numicons = iconinfo31[1] / 31
        ybig = 0
    if small == 7:
        y = 48
    else:
        # small = 15
        y = 32
    sample = big / small
    offset = sample / 2
    for i in xrange(numicons):
        x = i*32
        for row in xrange(small):
            for col in xrange(small):
                state = g.getcell(x + offset + col*sample, ybig + offset + row*sample)
                if state > 0:
                    g.setcell(x+col, y+row, state)
Exemple #6
0
def GetObjectByClick(event):   
   
   x = int(event.split()[1])
   y = int(event.split()[2]) 
   
   found = False
   
   for i in [0, -1, 1, -2, 2]:
      for j in [0, -1, 1]:
         if found:
            break
            
         o =  IsObjectExists(objectArray, x + i, y + j)
         
         if o != None:
            g.show("found!")
            
            for k in xrange(0, len(o[0]), 2):
               dx = o[0][k]
               dy = o[0][k + 1]
               
               g.setcell(x + i + dx, y + j + dy, 0)
               
            found = True

            g.update()
            
            
   if    found:
      return o
   else :
      return None
Exemple #7
0
 def update_golly(self):
     invgcells = {v: k for (k, v) in self.gcells.iteritems()}
     for (v, c) in self.known_states.iteritems():
         if v in invgcells:
             (x, y) = invgcells[v]
             g.setcell(x, y, c)
     g.update()
Exemple #8
0
def create_smaller_icons(big, small):
    # scale down the big x big bitmaps into small x small bitmaps
    # using a simple sampling algorithm
    global iconinfo15, iconinfo31
    if big == 15:
        numicons = iconinfo15[1] // 15
        ybig = 32
    else:
        # big = 31
        numicons = iconinfo31[1] // 31
        ybig = 0
    if small == 7:
        y = 48
    else:
        # small = 15
        y = 32
    sample = big // small
    offset = sample // 2
    for i in range(numicons):
        x = i * 32
        for row in range(small):
            for col in range(small):
                state = g.getcell(x + offset + col * sample,
                                  ybig + offset + row * sample)
                if state > 0:
                    g.setcell(x + col, y + row, state)
Exemple #9
0
def draw_icons(iconinfo, transparent):
    global colorstate
    if len(iconinfo) == 0: return
    width = iconinfo[0]
    height = iconinfo[1]
    num_colors = iconinfo[2]
    chars_per_pixel = iconinfo[3]
    colordict = iconinfo[4]
    pos = 5
    numicons = height // width
    for i in range(numicons):
        x = i * 32
        y = 0
        if width == 15: y = 32
        if width == 7: y = 48
        for row in range(width):
            pxls = iconinfo[pos]
            pos += 1
            for col in range(width):
                offset = col * chars_per_pixel
                key = pxls[offset:offset + chars_per_pixel]
                if not key in colordict:
                    g.exit("Unexpected key in icon data: " + key)
                rgb = colordict[key]
                if rgb != transparent:
                    g.setcell(x + col, y + row, colorstate[rgb])
 def cellchange(self, x, y, state):
     """
     Sets the color of the specific cell
     :param x: the x location of the cell
     :param y: the y location of the cell
     :param state: the color state that the cell is in
     """
     g.setcell(x, y, state)
def checkneighbor(x, y):
   # first check if x,y is outside bounded grid
   if g.getwidth() > 0 and (x < gridl or x > gridr): return
   if g.getheight() > 0 and (y < gridt or y > gridb): return
   if g.getcell(x, y) == 0: return
   # no need for next test because we kill cell after adding it to ncells
   # if (x, y) in ncells: return False
   ncells.append( (x, y, g.getcell(x,y)) )
   g.setcell(x, y, 0)
def checkneighbor(x, y):
    # first check if x,y is outside bounded grid
    if g.getwidth() > 0 and (x < gridl or x > gridr): return
    if g.getheight() > 0 and (y < gridt or y > gridb): return
    if g.getcell(x, y) == 0: return
    # no need for next test because we kill cell after adding it to ncells
    # if (x, y) in ncells: return False
    ncells.append( (x, y, g.getcell(x,y)) )
    g.setcell(x, y, 0)
Exemple #13
0
def randfill_mash(rectcoords, amt):
    newstate = g.getoption("drawingstate")
    for i in range(rectcoords[0], rectcoords[0] + rectcoords[2]):
        for j in range(rectcoords[1], rectcoords[1] + rectcoords[3]):
            if (100 * random.random() < amt):
                g.setcell(i, j, dict_fill[rule][g.getcell(i, j)])
            else:
                # g.setcell(i, j, 0)
                continue
Exemple #14
0
def write_data_bits(s):
    x = data_tape_x
    for c in s:
        if c == '1':
            bit = 1
        else:
            bit = 0
        g.setcell(x, data_tape_y, bit)
        x += 1
Exemple #15
0
def randfill(rectcoords, amt, amt2=100, secondary_state=1):
    statelist = [g.getoption("drawingstate"), secondary_state]
    for i in range(rectcoords[0], rectcoords[0] + rectcoords[2]):
        for j in range(rectcoords[1], rectcoords[1] + rectcoords[3]):
            if (100 * random.random() < amt):
                newstate = (100 * random.random() > amt2)
                g.setcell(i, j, statelist[newstate])
            else:
                # g.setcell(i, j, 0)
                continue
Exemple #16
0
def write_byte_at(addr, write_byte):
    if addr <= QFTASM_REGAREA_MAX_ADDRESS:
        addr = addr
    elif addr >= RAM_SIZE - RAM_NEGATIVE_BUFFER_SIZE:
        addr = RAM_SIZE - addr + QFTASM_REGAREA_MAX_ADDRESS
    elif addr > QFTASM_REGAREA_MAX_ADDRESS:
        addr = addr + RAM_NEGATIVE_BUFFER_SIZE
    b_binary = "{:016b}".format(write_byte)
    for i_bit, bit in enumerate(b_binary):
        for x_offset in range(2):
            g.setcell(p_init[0] + i_bit * delta_x + x_offset, p_init[1] + addr * delta_y, d_bit2state[int(bit)])
def main(step=1, start=0):

    img = Image.open(srcPath)
    size = img.size

    for y in xrange(0, size[1]):
        for x in xrange(0, size[0]):

            c = img.getpixel((x, y))

            state = 1 if c[0] > 128 else 0
            g.setcell(x, y, state)
def main( step = 1, start = 0 ):
	
	img = Image.open( srcPath )
	size = img.size

	for y in xrange( 0, size[1] ):
		for x in xrange( 0, size[0] ):

			c = img.getpixel( (x, y) )

			state = 1 if c[0] > 128 else 0
			g.setcell( x, y, state )
	def ClearCellDictionary(self, curdict, obejctIdx):
	
		before = len(curdict)
		removeList = [key for key in curdict if curdict[key] == obejctIdx]
		
		for key in removeList:
			x, y = key.split(":")
			g.setcell(int(x), int(y), 0)
			del curdict[key]
		
		after = len(curdict)
		g.show("size change: " + str(before)  + "," + str(after) + "," + str(obejctIdx))
Exemple #20
0
def rp_plot(a,b,fill=fill):
	ma=max(a)
	mb=max(b)
	
	l=range(min(len(a),min(b)))
#	g.note('%i'%min(8,8))
	for i in range(min(len(a),len(b))):
#	for i in range(ma+1):
#		for j in range(mb+1):
#			if i==a[i] and j==b[j]:
		
		g.setcell(a[i],-b[i],fill)
Exemple #21
0
def write_program_bits(s):
    stripe_offset = 6  # the y offset in bits to offset our various striped sections of the program tape
    for (i, c) in enumerate(s):
        if c == '1':
            bit = 1
        else:
            bit = 0

        # The program tape we've been given is one long string of binary, but we want to stripe it into 4 different strings.
        # we'll handle that logic via modular arithmetic here
        x = program_tape_x + i // 4
        y = program_tape_y - (i % 4) * stripe_offset
        g.setcell(x, y, bit)
Exemple #22
0
    def ClearCellDictionary(self, curdict, obejctIdx):

        before = len(curdict)
        removeList = [key for key in curdict if curdict[key] == obejctIdx]

        for key in removeList:
            x, y = key.split(":")
            g.setcell(int(x), int(y), 0)
            del curdict[key]

        after = len(curdict)
        g.show("size change: " + str(before) + "," + str(after) + "," +
               str(obejctIdx))
Exemple #23
0
def draw_line(x1, y1, x2, y2, state=1):
    # draw a line of cells in given state from x1,y1 to x2,y2
    # using Bresenham's algorithm
    g.setcell(x1, y1, state)
    if x1 == x2 and y1 == y2: return

    dx = x2 - x1
    ax = abs(dx) * 2
    sx = 1
    if dx < 0: sx = -1
    dy = y2 - y1
    ay = abs(dy) * 2
    sy = 1
    if dy < 0: sy = -1

    if ax > ay:
        d = ay - (ax / 2)
        while x1 != x2:
            g.setcell(x1, y1, state)
            if d >= 0:
                y1 += sy
                d -= ax
            x1 += sx
            d += ay
    else:
        d = ax - (ay / 2)
        while y1 != y2:
            g.setcell(x1, y1, state)
            if d >= 0:
                x1 += sx
                d -= ay
            y1 += sy
            d += ax

    g.setcell(x2, y2, state)
Exemple #24
0
def is_there(x, y, gl):
   l = len(gl)
   for i in range(1, l, 2):
      xg = gl[i - 1]
      yg = gl[i]
      
      if g.getcell(x + xg, y + yg) == 0:
         return False
   
   for i in range(1, l, 2):
      xg = gl[i - 1]
      yg = gl[i]
      g.setcell(x + xg, y + yg, 0)
   return True
Exemple #25
0
def write_byte_at(addr, write_byte):
    if addr < 11:
        addr = addr
    # elif addr > 32768:
    #     addr = 32768 - addr + 11
    elif addr >= RAM_SIZE - RAM_NEGATIVE_BUFFER_SIZE:
        addr = RAM_SIZE - addr + 10
    elif addr >= 11:
        addr = addr + RAM_NEGATIVE_BUFFER_SIZE
    b_binary = "{:016b}".format(write_byte)
    for i_bit, bit in enumerate(b_binary):
        for x_offset in range(2):
            g.setcell(p_init[0] + i_bit * delta_x + x_offset,
                      p_init[1] + addr * delta_y, d_bit2state[int(bit)])
Exemple #26
0
def draw_line(x1, y1, x2, y2, state = 1):
    # draw a line of cells in given state from x1,y1 to x2,y2
    g.setcell(x1, y1, state)
    if x1 == x2 and y1 == y2: return
    
    dx = x2 - x1
    ax = abs(dx) * 2
    sx = 1
    if dx < 0: sx = -1
    dy = y2 - y1
    ay = abs(dy) * 2
    sy = 1
    if dy < 0: sy = -1
    
    if ax > ay:
        d = ay - (ax / 2)
        while x1 != x2:
            g.setcell(x1, y1, state)
            if d >= 0:
                y1 += sy
                d -= ax
            x1 += sx
            d += ay
    else:
        d = ax - (ay / 2)
        while y1 != y2:
            g.setcell(x1, y1, state)
            if d >= 0:
                x1 += sx
                d -= ay
            y1 += sy
            d += ax
    
    g.setcell(x2, y2, state)
Exemple #27
0
def draw_line(x1, y1, x2, y2):
    g.setcell(x1, y1, 1)
    if x1 == x2 and y1 == y2: return

    dx = x2 - x1
    ax = abs(dx) * 2
    sx = 1
    if dx < 0: sx = -1
    dy = y2 - y1
    ay = abs(dy) * 2
    sy = 1
    if dy < 0: sy = -1

    if ax > ay:
        d = ay - (ax / 2)
        while x1 != x2:
            g.setcell(x1, y1, 1)
            if d >= 0:
                y1 += sy
                d -= ax
            x1 += sx
            d += ay
    else:
        d = ax - (ay / 2)
        while y1 != y2:
            g.setcell(x1, y1, 1)
            if d >= 0:
                x1 += sx
                d -= ay
            y1 += sy
            d += ax

    g.setcell(x2, y2, 1)
def convbellman (text, stx, sty):
	textln = text.split ('\n')
	
	gen = -1
	glcnt = -1
	y = sty;
	for ln in textln:
		if not ln:
			break
		if ln [0] == '#':
			if ln [0:35] == "#C Solution accepted at generation ":
				gen = int (ln [35:])
			elif ln [0:26] == "#C Glider count at accept ":
				glcnt = int (ln [26:])
		else:
			x = stx;
			for c in ln:
				if c == '.':
					g.setcell (x, y, 0)
					x += 1;
				elif c == '?':
					g.setcell (x, y, 5)
					x += 1;
				elif c == '*':
					g.setcell (x, y, 3)
					x += 1;
				elif c == '@':
					g.setcell (x, y, 1)
					x += 1;
			y += 1
	return (gen, glcnt)
Exemple #29
0
def draw_line(x1, y1, x2, y2):
    g.setcell(x1, y1, 1)
    if x1 == x2 and y1 == y2: return

    dx = x2 - x1
    ax = abs(dx) * 2
    sx = 1
    if dx < 0: sx = -1
    dy = y2 - y1
    ay = abs(dy) * 2
    sy = 1
    if dy < 0: sy = -1

    if ax > ay:
        d = ay - (ax / 2)
        while x1 != x2:
            g.setcell(x1, y1, 1)
            if d >= 0:
                y1 += sy
                d -= ax
            x1 += sx
            d += ay
    else:
        d = ax - (ay / 2)
        while y1 != y2:
            g.setcell(x1, y1, 1)
            if d >= 0:
                x1 += sx
                d -= ay
            y1 += sy
            d += ax

    g.setcell(x2, y2, 1)
Exemple #30
0
def loadImage( path ):

	img = Image.open( path )
	size = img.size

	c = None
	state = None

	for y in xrange( 0, size[1] ):
		for x in xrange( 0, size[0] ):

			c = img.getpixel( (x, y) )

			if c[0] > 128:
				g.setcell( x, y, 1 )
	def UpdateState(self, newPat, dx, dy):
		self.under = []
		self.curPat = newPat
		self.dx = dx
		self.dy = dy
		
		for i in xrange(0, len(self.curPat), 2):
		
			if g.getcell(self.curPat[i] + self.dx, self.curPat[i + 1] + self.dy) == 1:
				self.under.append(self.curPat[i] + self.dx)
				self.under.append(self.curPat[i + 1] + self.dy)
				
			g.setcell(self.curPat[i] + self.dx, self.curPat[i + 1] + self.dy, 1)
		
		g.update()
Exemple #32
0
 def insert(self, g, g_xmin, g_xmax, g_ymin, g_ymax):
   """
   Write the seed into the Golly grid at a random location
   within the given bounds.
   g = the Golly universe
   s = a seed
   """
   step = 1
   g_xstart = rand.randrange(g_xmin, g_xmax - self.xspan, step)
   g_ystart = rand.randrange(g_ymin, g_ymax - self.yspan, step)
   for s_x in range(self.xspan):
     for s_y in range(self.yspan):
       g_x = g_xstart + s_x
       g_y = g_ystart + s_y
       s_state = self.cells[s_x][s_y]
       g.setcell(g_x, g_y, s_state)
Exemple #33
0
def draw_dna():
    logging.debug('loading cell pallate')
    pallate = cellPallate()
    pallate.load()

    logging.debug('getting default pallate selection')
    chosenCell = pallate.getUserChoice()
    chosenName = pallate.getSelectedCellName()
    g.show('now drawing with DNA from '+chosenName)
    logging.debug('now drawing with DNA from '+chosenName+'='+str(chosenCell))

    # prepare environment
    env = environment()
    logging.debug('turning on golly even script access')
    event = g.getevent(True)  # turn on golly event script access
    # === let user draw
    g.setcursor("Draw")
    try:    #this try statement is just to ensure the 'finally' block is run
        while True:    # loop until stop button is pressed
            event = g.getevent() # event is a string like "click 10 20 left none"
            if len(event) < 1: # do not try to split empty string
                continue
            else:
                logging.debug('event recieved: "'+event+'"')
                evt, xstr, ystr, butt, mods = event.split()
                if evt=="click" and butt=="left" and mods=="none": # left click
#                    logging.debug('left click detected at '+xstr+','+ystr)
                    x = int(xstr)
                    y = int(ystr)
                    env.cellList.setCell(x,y,cell=cell(x,y,chosenCell.DNA))    #add cell to list
                    g.setcell(x,y,1)    #fill in functional cell
                    env.drawColor()    #update color layer to match
                    g.update()        #update golly display
                    logging.info('cell ('+xstr+','+ystr+') painted with "'+chosenName+'"')
                    g.show('cell painted. press "Esc" to stop drawing')
                else:
                    logging.info('event "'+event+'" not recognized')
    except:    # re-raise any errors encountered
        logging.error('unexpected error: '+sys.exc_info()[0])
        raise
    finally:
        g.getevent(False) # return event handling to golly
        g.show('done drawing '+chosenName+' cells.')
        logging.debug('done drawing '+chosenName+' cells.')
        # === teardown
        env.teardown()
        return
Exemple #34
0
    def UpdateState(self, newPat, dx, dy):
        self.under = []
        self.curPat = newPat
        self.dx = dx
        self.dy = dy

        for i in xrange(0, len(self.curPat), 2):

            if g.getcell(self.curPat[i] + self.dx,
                         self.curPat[i + 1] + self.dy) == 1:
                self.under.append(self.curPat[i] + self.dx)
                self.under.append(self.curPat[i + 1] + self.dy)

            g.setcell(self.curPat[i] + self.dx, self.curPat[i + 1] + self.dy,
                      1)

        g.update()
Exemple #35
0
def getinp(s):
    ###########################
    temp = g.getcell(x, y)
    g.setcell(x, y, 5)
    g.show(s + "Ptr:" + str(ptr) + " x:" + str(x) + " y:" + str(y))
    g.fit()
    g.update()
    g.setcell(x, y, temp)
    # return
    k = g.getevent()
    count = 0
    while k == "":
        sleep(.01)
        k = g.getevent()
        count += 1
    if k == "key q none": g.exit()
    return
Exemple #36
0
def randfill_mash(rectcoords, amt, statemap):
    newstate = g.getoption("drawingstate")
    #	g.note('%s'%statemap)
    for i in range(rectcoords[0], rectcoords[0] + rectcoords[2]):
        for j in range(rectcoords[1], rectcoords[1] + rectcoords[3]):
            if (100 * random.random() < amt):
                try:
                    g.show('processing %i,%i' % (i, j))
                    g.setcell(i, j, statemap[g.getcell(i, j)])
                except:
                    dict_lc = [1] * g.numstates()
                    dict_lc[0] = 0
                    dict_lc[1:3] = [2, 2]
                    g.setcell(i, j, dict_lc[g.getcell(i, j)])
            else:
                # g.setcell(i, j, 0)
                continue
def drawlines():
    global oldline, firstcell
    started = False
    oldmouse = ""
    while True:
        event = g.getevent()
        if event.startswith("click"):
            # event is a string like "click 10 20 left altctrlshift"
            evt, x, y, butt, mods = event.split()
            oldmouse = x + ' ' + y
            if started:
                # draw permanent line from start pos to end pos
                endx = int(x)
                endy = int(y)
                drawline(startx, starty, endx, endy)
                # this is also the start of another line
                startx = endx
                starty = endy
                oldline = []
                firstcell = []
            else:
                # start first line
                startx = int(x)
                starty = int(y)
                firstcell = [startx, starty, g.getcell(startx, starty)]
                g.setcell(startx, starty, drawstate)
                g.update()
                started = True
                g.show(
                    "Click where to end this line (and start another line)...")
        else:
            # event might be "" or "key m none"
            if len(event) > 0: g.doevent(event)
            mousepos = g.getxy()
            if started and len(mousepos) == 0:
                # erase old line if mouse is not over grid
                if len(oldline) > 0:
                    eraseline(oldline)
                    oldline = []
                    g.update()
            elif started and len(mousepos) > 0 and mousepos != oldmouse:
                # mouse has moved, so erase old line (if any) and draw new line
                if len(oldline) > 0: eraseline(oldline)
                x, y = mousepos.split()
                oldline = drawline(startx, starty, int(x), int(y))
                oldmouse = mousepos
Exemple #38
0
def drawlines():
    global oldline, firstcell
    started = False
    oldmouse = ""
    while True:
        event = g.getevent()
        if event.startswith("click"):
            # event is a string like "click 10 20 left altctrlshift"
            evt, x, y, butt, mods = event.split()
            oldmouse = x + ' ' + y
            if started:
                # draw permanent line from start pos to end pos
                endx = int(x)
                endy = int(y)
                drawline(startx, starty, endx, endy)
                # this is also the start of another line
                startx = endx
                starty = endy
                oldline = []
                firstcell = []
            else:
                # start first line
                startx = int(x)
                starty = int(y)
                firstcell = [ startx, starty, g.getcell(startx, starty) ]
                g.setcell(startx, starty, drawstate)
                g.update()
                started = True
                g.show("Click where to end this line (and start another line)...")
        else:
            # event might be "" or "key m none"
            if len(event) > 0: g.doevent(event)
            mousepos = g.getxy()
            if started and len(mousepos) == 0:
                # erase old line if mouse is not over grid
                if len(oldline) > 0:
                    eraseline(oldline)
                    oldline = []
                    g.update()
            elif started and len(mousepos) > 0 and mousepos != oldmouse:
                # mouse has moved, so erase old line (if any) and draw new line
                if len(oldline) > 0: eraseline(oldline)
                x, y = mousepos.split()
                oldline = drawline(startx, starty, int(x), int(y))
                oldmouse = mousepos
Exemple #39
0
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 main(width, height, update):
    w = width
    h = height
    x = 0
    i = 0
    while x < w:
        y = 0
        while y < h:
            update = rules(x, y, update)
            y += 1
        x += 1
    while i < w:
        j = 0
        while j < h:
            g.setcell(i, j, update[i][j])
            j += 1
        i += 1
    g.update()
    return update
Exemple #41
0
def write_program(program):
    global program_tape_x, program_tape_y

    # find all the labels
    labels = [c[:-1] for c in program if c[-1] == ':']

    iCurrentLabel = 0
    for i, c in enumerate(program):
        if 'jump_if_one:' in c:
            write_string(jump_if_one)
            jump = labels.index(c[c.index(':') + 1:]) + 1 - iCurrentLabel
            if jump < 1:
                jump -= 1
            if jump > 1 and program[i + 1][-1] == ':':
                jump -= 1
                # (if next command is a label we don't need to jump so far)
            if jump < 0:
                write_string('0')
            else:
                write_string('1')
            write_string('1' * abs(jump) + '0')
        elif 'goto:' in c:
            write_string(goto)
            jump = labels.index(c[c.index(':') + 1:]) + 1 - iCurrentLabel
            if jump < 1:
                jump -= 1
            if jump > 1 and program[i + 1][-1] == ':':
                jump -= 1
                # (if next command is a label we don't need to jump so far)
            if jump < 0:
                write_string('0')
            else:
                write_string('1')
            write_string('1' * abs(jump) + '0')
        elif c[-1] == ':':
            # a label, make a mark on the marker tape
            g.setcell(program_tape_x - 1, program_tape_y - 6, 1)
            iCurrentLabel += 1
        else:
            # a normal command
            write_string(c)
def write_program(program):
    global program_tape_x, program_tape_y

    # find all the labels
    labels = [c[:-1] for c in program if c[-1]==':']

    iCurrentLabel=0
    for i,c in enumerate(program):
        if 'jump_if_one:' in c:
            write_string(jump_if_one)
            jump = labels.index(c[c.index(':')+1:])+1-iCurrentLabel
            if jump<1:
                jump-=1
            if jump>1 and program[i+1][-1]==':':
                jump -= 1
                # (if next command is a label we don't need to jump so far)
            if jump<0:
                write_string('0')
            else:
                write_string('1')
            write_string('1'*abs(jump)+'0')
        elif 'goto:' in c:
            write_string(goto)
            jump = labels.index(c[c.index(':')+1:])+1-iCurrentLabel
            if jump<1:
                jump-=1
            if jump>1 and program[i+1][-1]==':':
                jump -= 1
                # (if next command is a label we don't need to jump so far)
            if jump<0:
                write_string('0')
            else:
                write_string('1')
            write_string('1'*abs(jump)+'0')
        elif c[-1]==':':
            # a label, make a mark on the marker tape
            g.setcell(program_tape_x-1,program_tape_y-6,1)
            iCurrentLabel+=1
        else:
            # a normal command
            write_string(c)
def write_byte_at(addr, write_byte):
    if addr <= QFTASM_REGAREA_MAX_ADDRESS:
        addr = addr
    elif addr >= RAM_SIZE - RAM_NEGATIVE_BUFFER_SIZE:
        addr = RAM_SIZE - addr + QFTASM_REGAREA_MAX_ADDRESS
    elif addr > QFTASM_REGAREA_MAX_ADDRESS:
        addr = addr + RAM_NEGATIVE_BUFFER_SIZE
    b_binary = "{:016b}".format(write_byte)
    for i_bit, bit in enumerate(b_binary):
        for x_offset in range(2):
            x_offset *= OTCAMP_SIZE
            for x_p, y_p in write_offsets:
                write_x = p_init[0] + i_bit * delta_x + x_offset + x_p
                write_y = p_init[1] + addr * delta_y + y_p
                write_value = int(bit)
                g.setcell(write_x, write_y, write_value)
            for x_p, y_p in write_offsets_inv:
                write_x = p_init[0] + i_bit * delta_x + x_offset + x_p
                write_y = p_init[1] + addr * delta_y + y_p
                write_value = 1 - int(bit)
                g.setcell(write_x, write_y, write_value)
def tile_rom_demultiplexer_body(
        l_binstring,
        d_pattern=d_patterns_rom_demultiplexer["d_pattern_mpx_body"],
        xoffset=0,
        h_repeats=N_BITS_ROM):
    p_init = d_pattern["init"]
    p_init = (p_init[0] + xoffset, p_init[1])
    delta_x, delta_y = d_pattern["delta"]
    # h_repeats, v_repeats = d_pattern["repeats"]
    v_repeats = d_pattern["repeats"][1]
    reverse_bitarray = d_pattern["reverse_bitarray"]
    method = d_pattern["method"] if "method" in d_pattern.keys() else "copy"

    for i_addr, (lineno, _) in enumerate(l_binstring):
        if type(lineno) == int:
            bitarray = ("{:0" + str(h_repeats) + "b}").format(lineno)
        else:
            bitarray = lineno
        if reverse_bitarray:
            bitarray = list(reversed(bitarray))

        for i_bit, bit in enumerate(bitarray):
            if bit == " ":
                continue
            d_pattern[bit].put(p_init[0] + delta_x * i_bit,
                               p_init[1] + i_addr * delta_y,
                               A=(1, 0, 0, 1, method))
            if bit == "-":
                g.setcell(p_init[0] + delta_x * i_bit + 3,
                          p_init[1] + i_addr * delta_y + 8, 0)

    if "footer" in d_pattern.keys():
        d_footer = d_pattern["footer"]
        # Get the offset stored in "init" first, and then overwrite it
        x_offset_footer, y_offset_footer = d_footer["init_init"]
        d_footer["init"] = (p_init[0] + x_offset_footer,
                            p_init[1] + i_addr * delta_y + y_offset_footer)
        tile_pattern(d_footer, h_repeats=h_repeats)
def getobject(x, y):
   object = []
   ncells.append( (x, y, g.getcell(x,y)) )
   g.setcell(x, y, 0)
   while len(ncells) > 0:
      # remove cell from end of ncells and append to object
      x, y, s = ncells.pop()
      object.append(x)
      object.append(y)
      object.append(s)
      # add any live neighbors to ncells
      checkneighbor(x  , y+1)
      checkneighbor(x  , y-1)
      checkneighbor(x+1, y  )
      checkneighbor(x-1, y  )
      checkneighbor(x+1, y+1)
      checkneighbor(x+1, y-1)
      checkneighbor(x-1, y+1)
      checkneighbor(x-1, y-1)
   # append padding int if necessary
   if len(object) > 0 and (len(object) & 1) == 0: object.append(0)
   g.putcells(object)
   return object
Exemple #46
0
def drawline(x1, y1, x2, y2):
    # draw a line of cells from x1,y1 to x2,y2 using Bresenham's algorithm;
    # we also return the old cells in the line so we can erase line later
    oldcells = []
    # note that x1,y1 has already been drawn
    # oldcells.append( (x1, y1, g.getcell(x1, y1)) )
    # g.setcell(x1, y1, drawstate)
    if x1 == x2 and y1 == y2:
        g.update()
        return oldcells

    dx = x2 - x1
    ax = abs(dx) * 2
    sx = 1
    if dx < 0: sx = -1
    dy = y2 - y1
    ay = abs(dy) * 2
    sy = 1
    if dy < 0: sy = -1

    if ax > ay:
        d = ay - (ax / 2)
        while x1 != x2:
            oldcells.append( (x1, y1, g.getcell(x1, y1)) )
            g.setcell(x1, y1, drawstate)
            if d >= 0:
                y1 += sy
                d -= ax
            x1 += sx
            d += ay
    else:
        d = ax - (ay / 2)
        while y1 != y2:
            oldcells.append( (x1, y1, g.getcell(x1, y1)) )
            g.setcell(x1, y1, drawstate)
            if d >= 0:
                x1 += sx
                d -= ay
            y1 += sy
            d += ax

    oldcells.append( (x2, y2, g.getcell(x2, y2)) )
    g.setcell(x2, y2, drawstate)
    g.update()
    return oldcells
def putcells(outfile, dxy):
	dx, dy = dxy
	tileCount = -1
	maxTileX = -1
	maxTileY = -1

	with open(outfile, "r") as data:
		for line in data:
			
			if tileCount >= 0:
				
				chars = list(line)
				
				for x in xrange(0, len(chars)):
					ch = chars[x]
					
					if ch == '@':
						g.setcell(dx + tileDX + x, dy + tileCount + tileDY, 1)
					if ch == '*':
						g.setcell(dx + tileDX + x, dy + tileCount + tileDY, 3)
					if ch == '?':
						g.setcell(dx + tileDX + x, dy + tileCount + tileDY, 5)
					
						
				tileCount += 1
			
			if line.startswith("#S"):
				continue 
			
			if line.startswith("#P"):
				vals = line.split()
				tileDX = int(vals[1])
				tileDY = int(vals[2])
				tileCount = 0
				
				if tileDX > maxTileX:
					maxTileX = tileDX
				
				if tileDY > maxTileY:
					maxTileY = tileDY
				
	return (maxTileX, maxTileY)
Exemple #48
0
                        # lower triangle
                        pixels[row][(encode(color,state,dir)-1)*15+column] = \
                            [palette[0],bg_color,fg_color][lower[dir][row][column]]
                        # upper triangle
                        pixels[row][(encode(color,state,dir)+total_states-2)*15+column] = \
                            [palette[0],bg_color,fg_color][lower[2-dir][13-row][column]]
                # draw the 7x7 icon
                for row in range(7):
                    for column in range(7):
                        # lower triangle
                        pixels[15+row][(encode(color,state,dir)-1)*15+column] = \
                            [palette[0],bg_color,fg_color][lower7x7[dir][row][column]]
                        # upper triangle
                        pixels[15+row][(encode(color,state,dir)+total_states-2)*15+column] = \
                            [palette[0],bg_color,fg_color][lower7x7[2-dir][6-row][column]]

    ConvertTreeToRule(rule_name, total_states, pixels)

else:

    golly.warn('Too many states!')
    golly.exit()

# -- select the rule --

golly.new(rule_name+'-demo.rle')
golly.setalgo('RuleLoader')
golly.setrule(rule_name)
golly.setcell(0,0,encode(0,0,0)) # start with a single turmite
golly.show('Created '+rule_name+'.rule and selected that rule.')
Exemple #49
0
            bg_col = palette[color]
            fg_col = palette[state+n_colors]
            mid = [(f+b)/2 for f,b in zip(fg_col,bg_col)]
            for x in range(15):
                for y in range(15):
                    column = (encode(color,state,dir)-1)*15 + rotate4[dir][0][0]*x + \
                        rotate4[dir][0][1]*y + offset4[dir][0]*14
                    row = rotate4[dir][1][0]*x + rotate4[dir][1][1]*y + offset4[dir][1]*14
                    pixels[row][column] = [bg_col,fg_col,eyes,mid][ant15x15[y][x]]
            for x in range(7):
                for y in range(7):
                    column = (encode(color,state,dir)-1)*15 + rotate4[dir][0][0]*x + \
                        rotate4[dir][0][1]*y + offset4[dir][0]*6
                    row = 15 + rotate4[dir][1][0]*x + rotate4[dir][1][1]*y + offset4[dir][1]*6
                    pixels[row][column] = [bg_col,fg_col,eyes,mid][ant7x7[y][x]]
for color in range(n_colors):
    bg_col = palette[color]
    for row in range(15):
        for column in range(15):
            pixels[row][(color-1)*15+column] = bg_col
    for row in range(7):
        for column in range(7):
            pixels[15+row][(color-1)*15+column] = bg_col
WriteBMP(pixels,golly.getdir('rules')+rule_name+'.icons')

# now we can switch to the new rule
golly.setrule(rule_name)
golly.new(rule_name+' demo')
golly.setcell(0,0,n_colors+3) # start with an ant facing west
golly.show('Created '+rule_name+'.tree, and selected this rule.')
Exemple #50
0
def eraseline(oldcells):
    for t in oldcells:
        x, y, s = t
        g.setcell(x, y, s)
Exemple #51
0
            if started and len(mousepos) == 0:
                # erase old line if mouse is not over grid
                if len(oldline) > 0:
                    eraseline(oldline)
                    oldline = []
                    g.update()
            elif started and len(mousepos) > 0 and mousepos != oldmouse:
                # mouse has moved, so erase old line (if any) and draw new line
                if len(oldline) > 0: eraseline(oldline)
                x, y = mousepos.split()
                oldline = drawline(startx, starty, int(x), int(y))
                oldmouse = mousepos

# ------------------------------------------------------------------------------

g.show("Click where to start line...")
oldcursor = g.getcursor()
g.setcursor("Draw")
drawstate = g.getoption("drawingstate")
oldline = []
firstcell = []    # pos and state of the 1st cell clicked

try:
    drawlines()
finally:
    g.setcursor(oldcursor)
    if len(oldline) > 0: eraseline(oldline)
    if len(firstcell) > 0:
        x, y, s = firstcell
        g.setcell(x, y, s)
Exemple #52
0
      g.update()

   # also allow keyboard interaction
   g.dokey( g.getkey() )

   for col in xrange(r.left, r.left + r.width):
      if g.getcell(col, row)==1:
         tape += extend*(4+col-r.left) + extend_left + extend*(r.top+r.height-row)
         tape += mark
         tape += retract*(r.top+r.height-row) + retract_left + retract*(4+col-r.left)
      elif g.getcell(col,row)!=0:
	     g.exit('Cells in the selected area must be in states 0 or 1 only.')
	  
# finally we sheath and trigger and retract
tape += extend_left + extend*4 + extend_right + extend
tape += inject_sheath + '1'*50 + inject_trigger
tape += retract*2 + retract_right + retract*4 + retract_left
	
# now write the tape out
x = r.left+r.width+10
y = r.top+r.height+10
g.setcell(x+1,y,2)
for i in tape:
   g.setcell(x,y-1,2)
   g.setcell(x,y,int(i))
   g.setcell(x,y+1,2)
   x-=1



    g.exit("Percentage must be from 0 to 100.")
if minlive < 1 or minlive > maxlive:
    g.exit("Minimum state must be from 1 to " + str(maxlive) + ".")
if len(pmm) > 2:
    if not validint(pmm[2]):
        g.exit("Bad maxstate value: " + pmm[2])
    i = int(pmm[2])
    if i < minlive:
        g.exit("Maximum state must be >= minimum state.")
    if i > maxlive:
        g.exit("Maximum state must be <= " + str(maxlive) + ".")
    maxlive = i
else:
    maxlive = minlive

oldsecs = time()
for row in xrange(r.top, r.top + r.height):
    for col in xrange(r.left, r.left + r.width):
        if randint(0, 99) < perc:
            if minlive == maxlive:
                g.setcell(col, row, minlive)
            else:
                g.setcell(col, row, randint(minlive, maxlive))
        else:
            g.setcell(col, row, 0)
    # if large selection then give some indication of progress
    newsecs = time()
    if newsecs - oldsecs >= 1.0:
        oldsecs = newsecs
        g.update()
Exemple #54
0
# Change the entire pattern from emulated-Margolus states to N-state:

from glife import rect
import golly as g

r = rect( g.getrect() )
if r.empty: g.exit("There is no pattern.")

for row in xrange(r.top, r.top + r.height):
    for col in xrange(r.left, r.left + r.width):
        s = g.getcell(col,row)
        g.setcell(col, row, (s+s%2)/2-1)
Exemple #55
0
def RemoveList(listXY):

   for xy in listXY:
      x = xy[0]
      y = xy[1]
      g.setcell(x, y, 0)
Exemple #56
0
# Invert all cell states in the current selection.
# Author: Andrew Trevorrow ([email protected]), Jun 2006.
# Updated to use exit command, Nov 2006.
# Updated to use numstates command, Jun 2008.

from glife import rect
from time import time
import golly as g

r = rect( g.getselrect() )
if r.empty: g.exit("There is no selection.")

oldsecs = time()
maxstate = g.numstates() - 1

for row in xrange(r.top, r.top + r.height):
   # if large selection then give some indication of progress
   newsecs = time()
   if newsecs - oldsecs >= 1.0:
      oldsecs = newsecs
      g.update()

   # also allow keyboard interaction
   g.dokey( g.getkey() )

   for col in xrange(r.left, r.left + r.width):
      g.setcell(col, row, maxstate - g.getcell(col, row))

if not r.visible(): g.fitsel()