This is a demo of the
ipythonblocks module available at https://github.com/jiffyclub/ipythonblocks.
ipythonblocks provides a
BlockGrid object whose representation is an HTML table. Individual table cells are represented by
Block objects that have
.blue attributes by which the color of that cell can be specified.
ipythonblocks is a teaching tool that allows students to experiment with Python flow control concepts and immediately see the effects of their code represented in a colorful, attractive way.
BlockGrid objects can be indexed and sliced like 2D NumPy arrays making them good practice for learning how to access arrays.
from ipythonblocks import BlockGrid
grid = BlockGrid(10, 10, fill=(123, 234, 123))
BlockGrid objects support iteration for quick access to individual blocks.
.col attributes (zero-based) to help track where in the grid you are. The individual color channels on each
Block can be modified directly.
for block in grid: if block.row % 2 == 0 and block.col % 3 == 0: block.red = 0 block.green = 0 block.blue = 0 grid
BlockGrid objects have
.width attributes to facilitate loops over the grid. Individual
Blocks can be accessed via Python- or NumPy-like indexing.
for r in range(grid.height): for c in range(grid.width): sq = grid[r, c] sq.red = 100 if r % 2 == 0: sq.green = 15 else: sq.green = 255 if c % 2 == 0: sq.blue = 15 else: sq.blue = 255
BlockGrid.show() method can also be used to display the grid or individual blocks.
BlockGrid returns a new
BlockGrid object that is a view of the original, much like NumPy arrays.
sub_grid = grid[:, 5] sub_grid.show()
for block in sub_grid: block.red = 255
Slicing can be used with iteration to work on a sub-grid. The
Block.set_colors method can be used to update all the colors at once.
for block in grid[2:6, 2:4]: block.set_colors(245, 178, 34) grid
Like NumPy arrays, the
BlockGrid.copy() method can be used to get a completely independent copy of the grid or slice.
sub_copy = grid[3:-3, 3:-3].copy() sub_copy.show()
sub_copy[:] = (0, 0, 0) sub_copy.show()
Blocks can also be modified by assigning RGB tuples. This type of assignment can be used on individual blocks, or on slices to change many blocks at once.
grid = (0, 0, 0) grid.show()
grid[:, 5] = (255, 0, 0) grid.show()
grid[-3:, -3:] = (0, 124, 124) grid.show()
grid[1, 1] = (255, 255, 255) grid.show()
grid[:, :] = (123, 234, 123) grid.show()
The displayed size of blocks (in pixels) can be controlled with the
block_size keyword, allowing some flexibility in how many blocks can comfortably fit on the screen.
grid = BlockGrid(50, 50, block_size=5) grid
The block display size can be modified at any time by changing the
grid.block_size = 2 grid
And the grid lines between individual cells can be toggled by setting the
grid.lines_on = False grid