gridworld

2D gridworld representation and canvas renderer, intended for experimentation with various game algorithms.

gridworld

This is a small module that provides a representation and canvas renderer for 2D "gridworlds". Its intended use is for experimentation with game and AI algorithms such as pathfinding, line-of-sight, plus any number of grid-based board games.

Here's what it looks like:

Browserify is recommended.

$ npm install gridworld

Create a new GridWorld with a given width and height (specified in terms of grid cells) that will draw onto canvas.

Supported options:

  • cellSize size of each cell in pixels. Default: 32.
  • cellPadding size between each cell in pixels. Default: 1.
  • drawBorder if set, a border will be drawn around the entire world, instead of just between each cell.
  • borderColor default: 'black'.
  • backgroundColor default cell background color. Default: 'white'.
  • resizeCanvas if set, canvas element will be resized to fit world's dimensions, including any specified padding.
  • padding how much space to leave around the rendered world. Can be specified as a single number or as an object with keys top, right, bottom and left. Mostly useful with resizeCanvas option. Default: 0.
  • onclick click handler for cells. See event handling, below.

Example:

var GridWorld = require('gridworld').GridWorld;
var world = new GridWorld(canvas, map[0].length, map.length, {
  padding       : {top: 10, left: 10, right: 10, bottom: 60},
  cellSize      : 32,
  cellSpacing   : 1,
  resizeCanvas  : true,
  drawBorder    : true,
  onclick: function(node) {
    console.log("you clicked on node: " + node);
  }
});

Draws the world on its canvas.

Set the background color of the node at (x,y) to color.

Flag the cell at (x, y) as passable/impassable. A cell's passability does not affect how it is drawn.

Set arbitrary attribute attr on node (x,y) to value.

Iterate over each Manhattan neighbour of node (x,y). Callback receives (x,y) co-ordinate of neighbour as a parameter.

Iterate over each Manhattan neighbour of node. Callback receives neighbour node object as a parameter.

Iterate over each of the world's node objects. Callback receives node object as a parameter.

Function to invoke when user clicks on a node. Receives clicked node as a paremeter.

  • Add event handlers for dragging
  • Allow markers to be overlaid on cells
  • Support optional diagonal neighbours