|
| 1 | +# Example module for Online Python Tutor |
| 2 | +# Philip Guo |
| 3 | +# 2013-08-03 |
| 4 | + |
| 5 | +# To get the Online Python Tutor backend to import this custom module, |
| 6 | +# add its filename ('htmlexample_module') to the CUSTOM_MODULE_IMPORTS |
| 7 | +# tuple in pg_logger.py |
| 8 | + |
| 9 | +# To see an example of this module at work, write the following code in |
| 10 | +# http://pythontutor.com/visualize.html |
| 11 | +''' |
| 12 | +from htmlexample_module import ColorTable |
| 13 | +
|
| 14 | +t = ColorTable(3, 4) |
| 15 | +
|
| 16 | +t.set_color(0, 0, 'red') |
| 17 | +t.render_HTML() |
| 18 | +
|
| 19 | +t.set_color(1, 1, 'green') |
| 20 | +t.render_HTML() |
| 21 | +
|
| 22 | +t.set_color(2, 2, 'blue') |
| 23 | +t.render_HTML() |
| 24 | +
|
| 25 | +for i in range(3): |
| 26 | + for j in range(4): |
| 27 | + t.set_color(i, j, 'gray') |
| 28 | + t.render_HTML() |
| 29 | +''' |
| 30 | + |
| 31 | + |
| 32 | +# defines a simple table where you can set colors for individual rows and columns |
| 33 | +class ColorTable: |
| 34 | + def __init__(self, num_rows, num_columns): |
| 35 | + self.num_rows = num_rows |
| 36 | + self.num_columns = num_columns |
| 37 | + |
| 38 | + # create a 2D matrix of empty strings |
| 39 | + self.table = [] |
| 40 | + for i in range(self.num_rows): |
| 41 | + new_lst = ['' for e in range(self.num_columns)] |
| 42 | + self.table.append(new_lst) |
| 43 | + |
| 44 | + |
| 45 | + # color must be a legal HTML color string |
| 46 | + def set_color(self, row, column, color): |
| 47 | + assert 0 <= row < self.num_rows |
| 48 | + assert 0 <= column < self.num_columns |
| 49 | + self.table[row][column] = color |
| 50 | + |
| 51 | + |
| 52 | + # call this function whenever you want to render this table in HTML |
| 53 | + def render_HTML(self): |
| 54 | + # incrementally build up an HTML table string |
| 55 | + html_string = '<table>' |
| 56 | + |
| 57 | + for i in range(self.num_rows): |
| 58 | + html_string += '<tr>' |
| 59 | + for j in range(self.num_columns): |
| 60 | + color = self.table[i][j] |
| 61 | + if not color: |
| 62 | + color = "white" |
| 63 | + html_string += '''<td style="width: 30px; height: 30px; border: 1px solid black; |
| 64 | + background-color: %s;"></td>''' % color |
| 65 | + html_string += '</tr>' |
| 66 | + |
| 67 | + html_string += '</table>' |
| 68 | + |
| 69 | + # then call the magic setHTML function |
| 70 | + setHTML(html_string) |
| 71 | + |
0 commit comments