Example #1
0
    def __init__(self):
        ### initialize grid, agent, obstacles, etc.,
        self.width = 6
        self.height = 6
        self.grid = BlockGrid(self.height, self.width, fill=(234, 123, 234))

        # decide on obstacle and goal locations
        self.obstacles = [[1, 2], [3, 4], [2, 3],
                          [2, 1]]  # impenetrable obstacle locations
        self.goal = [4, 4]  # goal block
        self.player = [1, 1]  # initial location player

        # enumerate states based on obstacle locations
        self.states = []
        for i in range(self.grid.height):
            for j in range(self.grid.width):
                block = [i, j]
                if block not in self.obstacles and block not in self.goal:
                    self.states.append(str(i) + str(j))

        # initialize Q^* matrix
        self.Q_star = np.zeros((self.grid.width**2 - len(self.obstacles), 5))

        # initialize action choices
        self.action_choices = [[-1, 0], [0, -1], [1, 0], [0, 1], [0, 0]]
Example #2
0
def vizarray(x, cmap=None, scale=None, vmin=None, vmax=None, block_size=None):
    """Visualize a NumPy array using ipythonblocks."""
    if not (x.ndim == 2 or x.ndim == 1):
        raise TypeError('This function only works with 1 or 2 dimensional arrays')
    global _cmap, _scale, _vmin, _vmax, _block_size
    cmap = cmap if cmap is not None else _cmap
    scale = scale if scale is not None else _scale
    vmin = vmin if vmin is not None else _vmin
    vmax = vmax if vmax is not None else _vmax
    block_size = block_size if block_size is not None else _block_size
    base = x.base if x.base is not None else None
    data = x.copy()
    if scale:
        n = colors.Normalize(vmin=vmin, vmax=vmax)
        if base is not None:
            n.autoscale(base)
        data = n(data)
    if data.ndim == 1:
        rows = 1
        cols = data.shape[0]
        bg = BlockGrid(cols, rows, block_size=block_size)
        for col in range(cols):
            bg[0,col] = _value_to_color(data[col], cmap)
    elif data.ndim == 2:
        rows = data.shape[0]
        cols = data.shape[1]
        bg = BlockGrid(cols, rows, block_size=block_size)
        for row in range(rows):
            for col in range(cols):
                bg[row, col] = _value_to_color(data[row, col], cmap)
    return bg
Example #3
0
    def __init__(self, width=5, height=5):
        super(CleanupPuzzleEnvironment, self).__init__()
        self.width = width
        self.height = height

        self.bg_color = (207, 216, 220)
        self.ball_color = (0, 191, 165)
        self.click_color = (244, 67, 54)
        self.grid = BlockGrid(width, height, fill=self.bg_color)
Example #4
0
def swiss_flag(n_rows=10, n_cols=10):
    red = (255, 0, 0)
    white = (255, 255, 255)

    screen = BlockGrid(n_cols, n_rows, fill=(255, 0, 0))
    screen.lines_on = False
    screen[2:8, 4:6] = white
    screen[4:6, 2:8] = white
    return screen
Example #5
0
    def show_as_blocks(self):

        block_size = 100

        grid = BlockGrid(self._number, 1, block_size=block_size)

        for block, color in zip(grid, self._colors):
            block.rgb = color

        grid.show()
Example #6
0
 def __init__(self, width=10, height=10, boundary=True, color={}, display=False):
     """Define all the usual XYEnvironment characteristics,
     but initialise a BlockGrid for GUI too."""
     super().__init__(width, height)
     self.grid = BlockGrid(width, height, fill=(200, 200, 200))
     if display:
         self.grid.show()
         self.visible = True
     else:
         self.visible = False
     self.bounded = boundary
     self.colors = color
Example #7
0
    def get(self, hash_id):
        grid_spec = dbi.get_grid_entry(hash_id, secret=self.secret)
        if not grid_spec:
            self.send_error(404)
            return

        gd = grid_spec['grid_data']
        grid = BlockGrid(gd['width'], gd['height'], lines_on=gd['lines_on'])
        grid._load_simple_grid(gd['blocks'])
        grid_html = grid._repr_html_()

        code_cells = grid_spec['code_cells'] or []
        code_cells = [colorize(c) for c in code_cells]

        self.render('grid.html', grid_html=grid_html, code_cells=code_cells)
Example #8
0
def draw_points(points, color=red):
    screen = BlockGrid(SCREEN_COLS, SCREEN_ROWS, fill=black)
    for p in points:
        r = p[0]
        c = p[1]
        if 0 <= r < screen.height and 0 <= c < screen.width:
            screen[r, c] = color
    return screen
def voirListeVoeu(voeuxClasses):
    nbVoeux = len(voeuxClasses)
    grille = BlockGrid(nbVoeux, 1, fill=(200, 200, 200))
    for i, voeu in enumerate(voeuxClasses):
        typeCandidat = voeu["type"]
        couleur = couleursTypeCandidat[typeCandidat]
        grille[0, i].set_colors(*couleur)
    return grille
 def __init__(self,
              width=10,
              height=10,
              boundary=True,
              color={},
              display=False):
     """Defina todas las características habituales del entorno XY,
     pero inicialice un BlockGrid para GUI también."""
     super().__init__(width, height)
     self.grid = BlockGrid(width, height, fill=(200, 200, 200))
     if display:
         self.grid.show()
         self.visible = True
     else:
         self.visible = False
     self.bounded = boundary
     self.colors = color
Example #11
0
    def dibujaTablero(self,  fichasGanadoras=None):
        """Dibuja  en formato grafico en ipython, el tablero que se le pasa,
        si se le pasa una lista con fichas ganadoras, las resalta en amarillo."""
        grid = BlockGrid(width=self.colmax, height=self.filmax, block_size=25, lines_on=True)

        for fil in range(grid.height):
            for col in range(grid.width):
                if fichasGanadoras and [fil, col] in fichasGanadoras:
                    grid[fil, col] = colors['Yellow']
                    continue
                if self.tablero[fil][col] == 1:
                    grid[fil, col] = colors['Red']
                elif self.tablero[fil][col] == -1:
                    grid[fil, col] = colors['Green']
                else:
                    grid[fil, col] = colors['Black']

        grid.show()
Example #12
0
    def show_as_blocks(self, block_size=100):
        """
        Show colors in the IPython Notebook using ipythonblocks.

        Parameters
        ----------
        block_size : int, optional
            Size of displayed blocks.

        """
        from ipythonblocks import BlockGrid

        grid = BlockGrid(self.number, 1, block_size=block_size)

        for block, color in zip(grid, self.colors):
            block.rgb = color

        grid.show()
Example #13
0
    def show_as_blocks(self, block_size=100):
        """
        Show colors in the IPython Notebook using ipythonblocks.

        Parameters
        ----------
        block_size : int, optional
            Size of displayed blocks.

        """
        from ipythonblocks import BlockGrid

        grid = BlockGrid(self.number, 1, block_size=block_size)

        for block, color in zip(grid, self.colors):
            block.rgb = color

        grid.show()
Example #14
0
    def color_grid(self):
        # remake + recolor grid
        self.grid = BlockGrid(self.width, self.height, fill=(234, 123, 234))

        # color obstacles
        for i in range(len(self.obstacles)):
            self.grid[self.obstacles[i][0], self.obstacles[i][1]].red = 0

        # make and color goal
        self.grid[self.goal[0], self.goal[1]].green = 255
        self.grid[self.goal[0], self.goal[1]].red = 0
        self.grid[self.goal[0], self.goal[1]].blue = 0

        # color player location
        self.grid[self.player[0], self.player[1]].green = 0
        self.grid[self.player[0], self.player[1]].red = 0
        self.grid[self.player[0], self.player[1]].blue = 0

        self.grid.show()
Example #15
0
def boules_vers_grid(boules: Boules) -> BlockGrid:
    n = len(boules)
    grid = BlockGrid(n, 1, fill=(c_blanc))
    for i, boule in enumerate(boules):
        if boule == BLEU:
            grid[0, i].set_colors(*c_bleu)
        elif boule == BLANC:
            grid[0, i].set_colors(*c_blanc)
        elif boule == ROUGE:
            grid[0, i].set_colors(*c_rouge)
    return grid
Example #16
0
def chess_board(n_rows=8, n_cols=8, fg=None, bg=None):
    if not bg:
        bg = colors['black']
    if not fg:
        fg = colors['yellow']

    screen = BlockGrid(n_cols, n_rows, fill=bg)
    for row in range(n_rows):
        for col in range(n_cols):
            if (row + col) % 2 == 0:
                screen[row, col] = fg
    return screen
Example #17
0
 def __init__(self, width=10, height=10, boundary=True, color={}, display=False):
     """Define all the usual XYEnvironment characteristics,
     but initialise a BlockGrid for GUI too."""
     super().__init__(width, height)
     self.grid = BlockGrid(width, height, fill=(200, 200, 200))
     if display:
         self.grid.show()
         self.visible = True
     else:
         self.visible = False
     self.bounded = boundary
     self.colors = color
Example #18
0
class CleanupPuzzleEnvironment(Environment):
    def __init__(self, width=5, height=5):
        super(CleanupPuzzleEnvironment, self).__init__()
        self.width = width
        self.height = height

        self.bg_color = (207, 216, 220)
        self.ball_color = (0, 191, 165)
        self.click_color = (244, 67, 54)
        self.grid = BlockGrid(width, height, fill=self.bg_color)

    def __str__(self):
        world = self.get_world()
        self.draw_grid(world)
        self.grid.show()
        return ''

    def draw_grid(self, world):
        self.grid[:] = self.bg_color
        for x in range(0, len(world)):
            for y in range(0, len(world[x])):
                if len(world[x][y]) and isinstance(world[x][y][0], Ball):
                    self.grid[x, y] = self.ball_color
                elif len(world[x][y]) and isinstance(world[x][y][0], Click):
                    self.grid[x, y] = self.click_color

    def get_world(self):
        '''returns the items in the world'''
        result = []
        for x in range(self.height):
            row = []
            for y in range(self.width):
                row.append(self.list_things_at((x, y)))
            result.append(row)
        return result

    def is_inbounds(self, location):
        '''Checks to make sure that the location is inbounds'''
        x, y = location
        return not (x < 0 or x >= self.height or y < 0 or y >= self.width)
def calcGrid(resList, anchors, rad):
    """
    Makes a visualization using ipython blocks of the locations of each resource in resList in a world. Anchors is a list of tuples
    denoting where to anchor the circles. Rad is and int indicating the radius of the circles.
    """
    world = []
    grid = BlockGrid(args.worldSize, args.worldSize)
    for i in range(args.worldSize):
        world.append([])
        for j in range(args.worldSize):
            world[i].append(set())

    for i in range(args.worldSize):
        for j in range(args.worldSize):
            for k in range(len(anchors)):
                if (dist((i,j), anchors[k])) <= rad-1:
                    world[i][j].add(resList[k][3:-1])
    
    entropy = 0
    niches = {}
    for i in range(args.worldSize):
        for j in range(args.worldSize):
            greenVal = 0.0
            blueVal = 0.0
            redVal = 0.0
            colorDict = {"AND":(255, 0, 0), "OR":(0, 255, 0), "ORN":(0,0,255), "ANDN":(255, 255, 0), "XOR":(255,0,255), "NOR":(0, 255, 255), "NOT":(255, 155, 0), "NAND":(255, 255, 255)}
            for res in world[i][j]:
                redVal += colorDict[res][0]
                greenVal += colorDict[res][1]
                blueVal += colorDict[res][2]
            if len(world[i][j]) > 0:
                redVal/=len(world[i][j])
                greenVal /= len(world[i][j])
                blueVal /= len(world[i][j])
            grid[i,j].red = redVal
            grid[i,j].green = greenVal
            grid[i,j].blue = blueVal
    grid.lines_on = False
    return grid
Example #20
0
def draw_1(color=red):
    screen = BlockGrid(SCREEN_COLS, SCREEN_ROWS, fill=black)
    screen[1, 1] = color
    screen[0, 2] = color
    screen[1, 2] = color
    screen[2, 2] = color
    screen[3, 2] = color
    screen[4, 2] = color
    screen[5, 2] = color
    screen[6, 2] = color
    screen[6, 1] = color
    screen[6, 3] = color
    return screen
def calcNResGrid(resList, anchors, rad):
    """
    Makes a visualization using ipython blocks of the number resources in each location in a world. 
    resList is a list of strings indicating which resources to place in the world.
    Anchors is a list of tuples denoting where to anchor the circles. 
    Rad is an int indicating the radius of the circles.
    """
    world = []
    grid = BlockGrid(args.worldSize, args.worldSize)
    for i in range(args.worldSize):
        world.append([])
        for j in range(args.worldSize):
            world[i].append(0)

    for i in range(args.worldSize):
        for j in range(args.worldSize):
            for k in range(len(anchors)):
                if (dist((i,j), anchors[k])) <= rad-1:
                    world[i][j] += 1
    
    entropy = 0
    niches = {}
    for i in range(args.worldSize):
        for j in range(args.worldSize):
            arr = np.zeros((1,1,3))
            if float(world[i][j]) != 0:
                arr[0,0,0] = (float(world[i][j]/10.0)*.6)
            else:
                arr[0,0,0] = 0
                
            arr[0,0,1] = 1
            arr[0,0,2] = 1
            rgb = matplotlib.colors.hsv_to_rgb(arr)
            grid[i,j].red = rgb[0,0,0]*255
            grid[i,j].green = rgb[0,0,1]*255
            grid[i,j].blue = rgb[0,0,2]*255

    grid.lines_on = False
    return grid
Example #22
0
 def show_selection(self, s_block):
     """Show a coloured table highlighting the selection"""
     grid = BlockGrid(self.ncols,
                      self.nrows,
                      fill=colors['LightGray'],
                      block_size=15)
     if hasattr(s_block, '__array__'):
         # ipython blocks does not support boolean indexing
         rows, cols = np.nonzero(s_block)
         for row, col in zip(rows, cols):
             grid[int(row), int(col)] = colors['LightGreen']
     else:
         grid[s_block] = colors['LightGreen']
     return grid
Example #23
0
class GraphicEnvironment(XYEnvironment):
    def __init__(self, width=10, height=10, boundary=True, color={}, display=False):
        """Define all the usual XYEnvironment characteristics,
        but initialise a BlockGrid for GUI too."""
        super().__init__(width, height)
        self.grid = BlockGrid(width, height, fill=(200, 200, 200))
        if display:
            self.grid.show()
            self.visible = True
        else:
            self.visible = False
        self.bounded = boundary
        self.colors = color

    def get_world(self):
        """Returns all the items in the world in a format
        understandable by the ipythonblocks BlockGrid."""
        result = []
        x_start, y_start = (0, 0)
        x_end, y_end = self.width, self.height
        for x in range(x_start, x_end):
            row = []
            for y in range(y_start, y_end):
                row.append(self.list_things_at([x, y]))
            result.append(row)
        return result

    """
    def run(self, steps=1000, delay=1):
        "" "Run the Environment for given number of time steps,
        but update the GUI too." ""
        for step in range(steps):
            sleep(delay)
            if self.visible:
                self.reveal()
            if self.is_done():
                if self.visible:
                    self.reveal()
                return
            self.step()
        if self.visible:
            self.reveal()
    """

    def run(self, steps=1000, delay=1):
        """Run the Environment for given number of time steps,
        but update the GUI too."""
        for step in range(steps):
            self.update(delay)
            if self.is_done():
                break
            self.step()
        self.update(delay)

    def update(self, delay=1):
        sleep(delay)
        if self.visible:
            self.conceal()
            self.reveal()
        else:
            self.reveal()

    def reveal(self):
        """Display the BlockGrid for this world - the last thing to be added
        at a location defines the location color."""
        self.draw_world()
        self.grid.show()
        self.visible = True

    def draw_world(self):
        self.grid[:] = (200, 200, 200)
        world = self.get_world()
        for x in range(0, len(world)):
            for y in range(0, len(world[x])):
                if len(world[x][y]):
                    self.grid[y, x] = self.colors[world[x][y][-1].__class__.__name__]

    def conceal(self):
        """Hide the BlockGrid for this world"""
        self.visible = False
        display(HTML(''))
Example #24
0
class my_gridworld():
    def __init__(self):
        ### initialize grid, agent, obstacles, etc.,
        self.width = 6
        self.height = 6
        self.grid = BlockGrid(self.height, self.width, fill=(234, 123, 234))

        # decide on obstacle and goal locations
        self.obstacles = [[1, 2], [3, 4], [2, 3],
                          [2, 1]]  # impenetrable obstacle locations
        self.goal = [4, 4]  # goal block
        self.player = [1, 1]  # initial location player

        # enumerate states based on obstacle locations
        self.states = []
        for i in range(self.grid.height):
            for j in range(self.grid.width):
                block = [i, j]
                if block not in self.obstacles and block not in self.goal:
                    self.states.append(str(i) + str(j))

        # initialize Q^* matrix
        self.Q_star = np.zeros((self.grid.width**2 - len(self.obstacles), 5))

        # initialize action choices
        self.action_choices = [[-1, 0], [0, -1], [1, 0], [0, 1], [0, 0]]

    def color_grid(self):
        # remake + recolor grid
        self.grid = BlockGrid(self.width, self.height, fill=(234, 123, 234))

        # color obstacles
        for i in range(len(self.obstacles)):
            self.grid[self.obstacles[i][0], self.obstacles[i][1]].red = 0

        # make and color goal
        self.grid[self.goal[0], self.goal[1]].green = 255
        self.grid[self.goal[0], self.goal[1]].red = 0
        self.grid[self.goal[0], self.goal[1]].blue = 0

        # color player location
        self.grid[self.player[0], self.player[1]].green = 0
        self.grid[self.player[0], self.player[1]].red = 0
        self.grid[self.player[0], self.player[1]].blue = 0

        self.grid.show()

    # make rewards array -
    def make_rewards(self):
        # create reward matrix
        R = -1 * np.ones((5, 5))
        R[goal[0], goal[1]] = 1000
        for i in range(len(obstacles)):
            R[obstacles[i][0], obstacles[i][1]] = 0

    ## Q-learning function
    def qlearn(self, gamma):
        num_episodes = 1000
        num_complete = 0

        # loop over episodes, for each run simulation and update Q
        for n in range(num_episodes):
            # pick random initialization - make sure its not an obstacle or goal
            obstical_free = 0
            loc = 0
            while obstical_free == 0:
                loc = [
                    np.random.randint(self.grid.width),
                    np.random.randint(self.grid.height)
                ]
                if loc not in self.obstacles:
                    obstical_free = 1

            # update Q matrix while loc != goal
            steps = 0
            max_steps = 200
            while steps < max_steps and loc != self.goal:

                # choose action - left = 0, right = 1, up = 2, down = 3, 4 = stay still
                k = np.random.randint(5)
                loc2 = [sum(x) for x in zip(loc, self.action_choices[k])]

                # check that new location within grid boundaries, if trying to go outside boundary -- either way can't move there!  So just place -1 for this location in Q
                if loc2[0] > self.grid.width - 1 or loc2[0] < 0 or loc2[
                        1] > self.grid.height - 1 or loc2[
                            1] < 0 or loc2 in self.obstacles:
                    # don't move location
                    ind_old = self.states.index(str(loc[0]) + str(loc[1]))
                    self.Q_star[ind_old, k] = -1
                else:
                    # we have a valid movement, if new state is goal set reward to 1000, otherwise set it to 0
                    r_k = 0
                    if loc2 == self.goal:
                        r_k = int(1000)

                    # update Q* matrix
                    ind_old = self.states.index(str(loc[0]) + str(loc[1]))
                    ind_new = self.states.index(str(loc2[0]) + str(loc2[1]))
                    self.Q_star[ind_old,
                                k] = r_k + gamma * max(self.Q_star[ind_new, :])

                    # update current location - one we just moved too
                    loc = loc2

                # update counter
                steps += 1
        print 'q-learning process complete'

    # print out
    def show_qmat(self):
        df = pd.DataFrame(self.Q_star,
                          columns=['up', 'down', 'left', 'right', 'still'],
                          index=self.states)
        print df.round(3)

    # animate the player based on completed Q-learning cycle
    def animate_movement(self, loc):
        # show movement based on an initial
        self.player = loc  # initial agent location
        self.color_grid()
        time.sleep(0.3)
        display.clear_output(wait=True)

        # if you chose an invalid starting position, break out and try again
        if loc in self.obstacles or loc == self.goal or loc[
                0] > self.grid.width - 1 or loc[0] < 0 or loc[
                    1] > self.grid.height - 1 or loc[1] < 0:
            print 'initialization is an obstacle or goal, initialize again'
        else:
            # now use the learned Q* matrix to run from any (valid) initial point to the goal
            count = 0
            max_count = self.grid.width * self.grid.height
            while count < max_count:
                # find next state using max Q* value
                ind_old = self.states.index(
                    str(self.player[0]) + str(self.player[1]))

                # find biggest value in Q* and determine block location
                action_ind = np.argmax(self.Q_star[ind_old, :])
                action = self.action_choices[action_ind]

                # move player to new location and recolor
                self.player = [sum(x) for x in zip(self.player, action)]

                # clear current screen for next step
                self.color_grid()
                time.sleep(0.3)
                if self.player == self.goal:
                    break
                display.clear_output(wait=True)
                count += 1
Example #25
0
class GraphicEnvironment(XYEnvironment):
    def __init__(self,
                 width=10,
                 height=10,
                 boundary=True,
                 color={},
                 display=False):
        """define all the usual XYEnvironment characteristics,
        but initialise a BlockGrid for GUI too"""
        super().__init__(width, height)
        self.grid = BlockGrid(width, height, fill=(200, 200, 200))
        if display:
            self.grid.show()
            self.visible = True
        else:
            self.visible = False
        self.bounded = boundary
        self.colors = color

    #def list_things_at(self, location, tclass=Thing): # need to override because locations
    #    """Return all things exactly at a given location."""
    #    return [thing for thing in self.things
    #            if thing.location == location and isinstance(thing, tclass)]

    def get_world(self):
        """Returns all the items in the world in a format
        understandable by the ipythonblocks BlockGrid"""
        result = []
        x_start, y_start = (0, 0)
        x_end, y_end = self.width, self.height
        for x in range(x_start, x_end):
            row = []
            for y in range(y_start, y_end):
                row.append(self.list_things_at([x, y]))
            result.append(row)
        return result

    """def run(self, steps=1000, delay=1):
        "" "Run the Environment for given number of time steps,
        but update the GUI too." ""
        for step in range(steps):
            sleep(delay)
            if self.visible:
                self.reveal()
            if self.is_done():
                if self.visible:
                    self.reveal()
                return
            self.step()
        if self.visible:
            self.reveal()
    """

    def run(self, steps=1000, delay=1):
        """Run the Environment for given number of time steps,
        but update the GUI too."""
        for step in range(steps):
            self.update(delay)
            if self.is_done():
                break
            self.step()
        self.update(delay)

    def update(self, delay=1):
        sleep(delay)
        if self.visible:
            self.conceal()
            self.reveal()
        else:
            self.reveal()

    def reveal(self):
        """display the BlockGrid for this world - the last thing to be added
        at a location defines the location color"""
        #print("Grid={}".format(self.grid))
        self.draw_world()
        #if not self.visible == True:
        #    self.grid.show()
        self.grid.show()
        self.visible == True

    def draw_world(self):
        self.grid[:] = (200, 200, 200)
        world = self.get_world()
        #print("world {}".format(world))
        for x in range(0, len(world)):
            for y in range(0, len(world[x])):
                if len(world[x][y]):
                    self.grid[y, x] = self.colors[world[x][y]
                                                  [-1].__class__.__name__]
                    #print('location: ({}, {}) got color: {}'
                    #.format(y, x, self.colors[world[x][y][-1].__class__.__name__]))

    def conceal(self):
        """hide the BlockGrid for this world"""
        self.visible = False
        display(HTML(''))
Example #26
0
def pBlockGrid2(df, fill=(123, 234, 123), *args, **kwargs):
    (y, x) = df.shape
    b = BlockGrid(x, y, fill=fill, **kwargs)
    return b
Example #27
0
def pBlockGrid(df):
    (y, x) = df.shape
    return BlockGrid(x, y)
class GraphicEnvironment(XYEnvironment):
    def __init__(self,
                 width=10,
                 height=10,
                 boundary=True,
                 color={},
                 display=False):
        """Defina todas las características habituales del entorno XY,
        pero inicialice un BlockGrid para GUI también."""
        super().__init__(width, height)
        self.grid = BlockGrid(width, height, fill=(200, 200, 200))
        if display:
            self.grid.show()
            self.visible = True
        else:
            self.visible = False
        self.bounded = boundary
        self.colors = color

    def get_world(self):
        """Devuelve todos los artículos del mundo en un formato
        comprensible por el bloque de cuadrícula ipythonblocks."""
        result = []
        x_start, y_start = (0, 0)
        x_end, y_end = self.width, self.height
        for x in range(x_start, x_end):
            row = []
            for y in range(y_start, y_end):
                row.append(self.list_things_at([x, y]))
            result.append(row)
        return result

    def run(self, steps=1000, delay=1):
        """Ejecute el entorno durante un número determinado de pasos de tiempo,
        pero actualiza la GUI también."""
        for step in range(steps):
            sleep(delay)
            if self.visible:
                self.reveal()
            if self.is_done():
                if self.visible:
                    self.reveal()
                return
            self.step()
        if self.visible:
            self.reveal()

    """def run(self, steps=1000, delay=1):
        "Ejecute el entorno durante un número determinado de pasos de tiempo,
        pero actualiza la GUI también."
        for step in range(steps):
            self.update(delay)
            if self.is_done():
                break
            self.step()
        self.update(delay)"""

    def update(self, delay=1):
        sleep(delay)
        if self.visible:
            self.conceal()
            self.reveal()
        else:
            self.reveal()

    def reveal(self):
        """Muestre BlockGrid para este mundo: lo último que se agregará
        en una ubicación define el color de la ubicación."""
        self.draw_world()
        self.grid.show()
        self.visible = True

    def draw_world(self):
        self.grid[:] = (200, 200, 200)
        world = self.get_world()
        for x in range(0, len(world)):
            for y in range(0, len(world[x])):
                if len(world[x][y]):
                    self.grid[y, x] = self.colors[world[x][y]
                                                  [-1].__class__.__name__]

    def conceal(self):
        """Ocultar el BlockGrid para este mundo"""
        self.visible = False
        display(HTML(''))
Example #29
0
        avg + (new / 100.0) for avg, new in zip(average_landings, board)
    ]

average_landings = [avg / 10.0 for avg in average_landings]
print('Probability (%) of landing on...')
print('Reading Railroad:\t', average_landings[reading_rr])
print('Pennsylvania Railroad:\t', average_landings[pennsylvania_rr])
print('B. & O. Railroad:\t', average_landings[bo_rr])
print('Short Line Railroad:\t', average_landings[shortline_rr])
print('GO:\t\t\t', average_landings[go])
print('Mediterranean Avenue:\t', average_landings[mediterranean])
print('Boardwalk:\t\t', average_landings[boardwalk])

width = 11
height = 11
grid = BlockGrid(width=width, height=height, fill=(209, 194, 111))

# Set up palette
tups = [(elt, p) for elt, p in zip(range(0, board_squares), average_landings)]
tups.sort(key=lambda x: x[1], reverse=True)
ranks = [(rank, elt[0], elt[1])
         for rank, elt in zip(range(0, board_squares), tups)]
palette = [0] * board_squares
for i in range(0, board_squares):
    idx = ranks[i][1]
    palette[idx] = ranks[i][0] * 6.25

# Paint edges
# Top row
for i in range(0, width):
    colour = palette[20 + i]
Example #30
0
from ipythonblocks import BlockGrid

grid = BlockGrid(10, 10, fill=(123, 234, 123))

grid
Example #31
0
import time

SCREEN_ROWS = 7
SCREEN_COLS = 5

colors = {
    'black': (0, 0, 0),
    'white': (255, 255, 255),
    'red': (255, 0, 0),
    'yellow': (255, 255, 0),
}

black = colors['black']
red = colors['red']

screen = BlockGrid(SCREEN_COLS, SCREEN_ROWS, fill=black)


def erase(screen, color=black):
    screen[:, :] = color


def draw_1(color=red):
    screen = BlockGrid(SCREEN_COLS, SCREEN_ROWS, fill=black)
    screen[1, 1] = color
    screen[0, 2] = color
    screen[1, 2] = color
    screen[2, 2] = color
    screen[3, 2] = color
    screen[4, 2] = color
    screen[5, 2] = color
Example #32
0
class GraphicEnvironment(XYEnvironment):
    def __init__(self,
                 width=10,
                 height=10,
                 boundary=True,
                 color={},
                 display=False):
        """Define all the usual XYEnvironment characteristics,
        but initialise a BlockGrid for GUI too."""
        super().__init__(width, height)
        self.grid = BlockGrid(width, height, fill=(200, 200, 200))
        if display:
            self.grid.show()
            self.visible = True
        else:
            self.visible = False
        self.bounded = boundary
        self.colors = color

    def get_world(self):
        """Returns all the items in the world in a format
        understandable by the ipythonblocks BlockGrid."""
        result = []
        x_start, y_start = (0, 0)
        x_end, y_end = self.width, self.height
        for x in range(x_start, x_end):
            row = []
            for y in range(y_start, y_end):
                row.append(self.list_things_at([x, y]))
            result.append(row)
        return result

    """
    def run(self, steps=1000, delay=1):
        "" "Run the Environment for given number of time steps,
        but update the GUI too." ""
        for step in range(steps):
            sleep(delay)
            if self.visible:
                self.reveal()
            if self.is_done():
                if self.visible:
                    self.reveal()
                return
            self.step()
        if self.visible:
            self.reveal()
    """

    def run(self, steps=1000, delay=1):
        """Run the Environment for given number of time steps,
        but update the GUI too."""
        for step in range(steps):
            self.update(delay)
            if self.is_done():
                break
            self.step()
        self.update(delay)

    def update(self, delay=1):
        sleep(delay)
        if self.visible:
            self.conceal()
            self.reveal()
        else:
            self.reveal()

    def reveal(self):
        """Display the BlockGrid for this world - the last thing to be added
        at a location defines the location color."""
        self.draw_world()
        self.grid.show()
        self.visible = True

    def draw_world(self):
        self.grid[:] = (200, 200, 200)
        world = self.get_world()
        for x in range(0, len(world)):
            for y in range(0, len(world[x])):
                if len(world[x][y]):
                    self.grid[y, x] = self.colors[world[x][y]
                                                  [-1].__class__.__name__]

    def conceal(self):
        """Hide the BlockGrid for this world"""
        self.visible = False
        display(HTML(''))
from PIL import Image
im = Image.open('StarNight.jpg')
im.size

im = im.resize((125, 100), Image.ANTIALIAS)

#Getdata() method gives an iterable sequence of RGB tuples starting at the top left image pixel and going down row by row

imdata = im.getdata()

#organize data structures
import os
import itertools
with open('starry_night.txt', 'w') as f:
    s = [
        '# width height', '{0} {1}'.format(im.size[0],
                                           im.size[1]), '# block size', '4',
        '# initial color', '0 0 0', '# row column red green blue'
    ]
    f.write(os.linesep.join(s) + os.linesep)

    for ((row, col), colors) in zip(
            itertools.product(range(im.size[1]), range(im.size[0])), imdata):
        things = [str(x) for x in (row, col) + colors]
        f.write(' '.join(things + ['\n']))

from ipythonblocks import BlockGrid
grid = BlockGrid(125, 100, block_size=4, lines_on=False)
for block, colors in zip(grid, imdata):
    block.rgb = colors
grid