2d-board
Simple array wrapper for 2-dimensional grid-based games
Usage
Basic Usage
// Get and set cellsvar cell = x y ;board;board; // Set out-of-bounds behavior for step functionsboard; // Step through cellsvar next = boardrightcell;
Advanced Usage
// Get and set cols and rowsboard;board;board;board; // Get and set entire boardboardcolsx;boardcolsx vals;boardrowsy;boardrowsy vals; // Merge boardsboard1colsboard2cols;
Documentation
Create a new 3 * 2 board:
var createBoard = ;var board = ;
Cell Operations
var cell = 0 0 ;board; // Set cell at (0, 0) to 'X'var val = board; // Get cell at (0, 0)console; // 'X'
Step Functions
Given the board:
A B C
D E F
G H I
Step across cols and rows:
var cell = 1 1 ; // 'E'var next = board; // 'E' -> 'B'if next !== null cell = next; // Check for OOBelse /* Handle it */
Step functions are up
, down
, left
, right
, and they return null
if out of bounds.
You can set the oob flag to define out-of-bounds behavior:
// A B C// D E F// G H I board;var cell = 3 0 ; // 'F'var next = boardrightcell; // 'F' -> 'D' board;var cell = 2 0 ; // 'F'var next = boardrightcell; // 'F' -> 'G'
The available options are:
"OOB_NULL"
to return null on oob (default)"OOB_STICK"
to return the same coordinates on oob"OOB_SAME"
to wrap to the same row or col on oob"OOB_NEXT"
to wrap to the next row or col on oob
Row and Column Operations
To set an entire row or column:
var row0 = 0 1 2 ;var row1 = 3 4 5 ;var col1 = 'A' 'B' ;board;board;board;
This yields the board:
0 A 2
3 B 5
To get an entire row or col:
var row = board;var col = board;console; // [ 0, 'A', 2 ]console; // [ 2, 5 ]
Board Operations
To set the entire board:
var vals = 0 1 2 3 4 5 ;boardrowsvals; // Fill the board in rows var vals = 0 3 1 4 2 5 ;boardcolsvals; // Fill the board in cols
The two operations above yield the same board:
0 1 2
3 4 5
To get the entire board:
var rows = boardrows; // Retrieve all rowsvar cols = boardcols; // Retrieve all colsconsole; // [[ 0, 1, 2 ], [ 3, 4, 5 ]]console; // [[ 0, 3 ], [ 1, 4 ], [ 2, 5 ]]
Features & Notes
- Permissive set methods. Handles any given array up to capacity, ignoring the rest.
var board = ;board; // Yields the board:// 0 1 2// 3 and 4 are ignored.
- Undefined values are skipped.
// A B C// D E F// G H I board; // Yields the board:// A B C// # E #// G H I
- As usual, array contents can be objects. Types can be mixed.
var item = 'number': 4 'elements': 123 'abc' ;var row = 789 item 'xyz' ;var board = ;board;
- Due to the internal representation of the array, references to rows are more efficient than references to cols.
// Assume a board with equal rows and cols, and homogeneous elements // This is more efficientvar row = board; // This is less efficientvar col = board;
Future Developments
- Custom comparator function for board merging
- Hashmap for board representation, instead of using array