rileyjshaw / terra

:space_invader: JS library for simple biological simulations and cellular automata
http://rileyjshaw.com/terra/
MIT License
610 stars 46 forks source link

Add a method to populate a terrarium non-randomly #13

Closed rileyjshaw closed 10 years ago

aychtang commented 10 years ago

I have some approaches on this we could reuse: https://github.com/cheeseen/board.

Although that actually creates the grid and populates it in one function.

rileyjshaw commented 10 years ago

This is awesome!! Thanks for the link, that's a really good idea.

I think that we should call the function makeGrid() instead of populate(), and have it return a grid rather than change the terrarium's grid. It's more consistent with how step() works.

What are your thoughts on the following API: terrarium.makeGridWithDistribution() acts like populate() currently does but returns a grid. terrarium.makeGrid(string) fills the whole level with that creature type terrarium.makeGrid(function(x, y)) acts like board(size, function(i, j)) terrarium.makeGrid([[string]]) allows you to have fine-grained control over what goes into the map terrarium.makeGrid(<anything else>) returns an empty grid of the correct size As before, terrarium.grid = gridObject sets the terrarium's grid to a pre-existing grid object

Usage example:

var terra = require('./terra.min.js');

// create a 4x4 terrarium
var terrarium = new terra.Terrarium(4, 4);
var a = 'a', b = 'b';

// create some creatures
terra.creatureFactory.register({type: a});
terra.creatureFactory.register({type: b});

// fill the terrarium with the 'b' creature type
terrarium.grid = terrarium.makeGrid(b);

// fill the terrarium with a checkerboard pattern
terrarium.grid = terrarium.makeGrid(function (x, y) {
  return (x + y) % 2 ? a : b;
});

// fill the terrarium's left half with 'a', right half with 'b'
terrarium.grid = terrarium.makeGrid([
  [a, a, b, b],
  [a, a, b, b],
  [a, a, b, b],
  [a, a, b, b]
]);

// fill the terrarium randomly with approximately half 'a' and half 'b'
terrarium.grid = terrarium.makeGridWithDistribution([[a, 50], [b, 50]]);
aychtang commented 10 years ago

This seems like a sensible API to me.

The only thing that was ambiguous was whether the makeGridWithDistribution method would ensure a 50/50 split of the cells in random order? Or something else? You could achieve that by creating the grid with the distribution given and then shuffling the cell positions.

Let me know if you would like any help implementing this section of the API.

rileyjshaw commented 10 years ago

@cheeseen thanks for the offer!! Don't worry about the implementation, it's a quick fix and there were a few things I was hoping to change about creature selection any. For now makeGridWithDistribution will return a grid with a distribution approximately equal to that provided, but it's a bit fuzzy. If you want to take a look at how to make it exact (that scrambling solution could work) I'd really appreciate it!