abbarnes

Grid Class [codeskulptor]

Dec 12th, 2017
245
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.80 KB | None | 0 0
  1. #Grid class for grids with values in cell at index=2 or (value=False) appended to cell
  2. #http://www.codeskulptor.org/#user43_gRaH4jSVYPihsJ5_0.py
  3. #by Adam Barnes
  4.  
  5. #global directions for traversing
  6. DOWN = (1,0)
  7. UP = (1,0)
  8. RIGHT = (0,1)
  9. LEFT = (0,-1)
  10.  
  11. class grid:
  12.     """
  13.    Grid class of width, height.  May contain values or not.
  14.    """
  15.    
  16.     def __init__(self, width, height, value = True, init_val = 0):
  17.         self._width = width
  18.         self._height = height
  19.         self._value = value
  20.         if not self._value:
  21.             self._grid = [[[h,w] for w in range(width)] for h in range(height) ]
  22.         else:
  23.             self._grid = [[[h,w,init_val] for w in range(width)] for h in range(height) ]
  24.        
  25.     def __str__(self):
  26.         for i in range(self._height):
  27.             print self._grid[i]
  28.         return "Grid is " + str(self._width) + " by " + str(self._height)
  29.    
  30.     def traverse_grid(self, start_row, start_col, direction, num_steps, add_value, debug = False):
  31.         for step in range(num_steps):
  32.             row = start_row + step * direction[0]
  33.             col = start_col + step* direction[1]
  34.             if debug:
  35.                 print "Processing Cell ", (row, col)
  36.             if self._value:
  37.                 self._grid[row][col][-1] += add_value
  38.             else:
  39.                 self._grid[row][col].append(add_value)
  40.             if debug:
  41.                 print "with value ", self._grid[row][col]
  42.    
  43.  
  44.  
  45.  
  46.  
  47. my_grid = grid(4,4)
  48. print my_grid
  49.  
  50. my_grid.traverse_grid(0,3,DOWN, 4,2, True)
  51. print my_grid
  52. my_grid.traverse_grid(0,0,RIGHT,4,3)
  53. print my_grid
  54.  
  55. print
  56. print "---------------------"
  57. print
  58.  
  59. my_grid = grid(4,4,False)
  60. print my_grid
  61.  
  62. my_grid.traverse_grid(0,3,DOWN, 4,2, True)
  63. print my_grid
  64. my_grid.traverse_grid(0,0,RIGHT,4,3)
  65. print my_grid
Advertisement
Add Comment
Please, Sign In to add comment