Skip to content

Instantly share code, notes, and snippets.

@boxofrox
Created April 14, 2013 20:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save boxofrox/5384111 to your computer and use it in GitHub Desktop.
Save boxofrox/5384111 to your computer and use it in GitHub Desktop.
Simple example demonstrating the definition and use of a simple generator function.
/* generator
*
* takes a chance value, C, an array of objects, and returns a Generator
* function that computes a random value, R. if R < C the Generator returns
* nothing, else the Generator returns a random item from the array of
* objects.
*
* params:
* chance: floating point value between [0,1].
* objs: array of objects to select from.
*/
function generator (chance, objs) {
/* return the Generator!!!!! mwahahahah */
return function () {
if (chance == 0.0 || objs == null) return null;
var rand = Math.random(); // rand is in [0,1)
if (rand < chance) return null;
return objs[Math.floor(rand * objs.length)]; // reuse rand to select random object.
}
}
/* in the Defs file.
*/
var Defs = {};
Defs.tileTypes = {
dirt: {
layer: 4,
displayName: "Dirt",
color: "#654423",
passable: true,
particles: [120, 80, 45],
generate: {
monsters: generator(8.0/100.0, ["bear", "wolf"]);
items: generator(70.0/600.0, ["poorshovel", "bone", "poorspear"]);
envItems: generator(0);
resources: generator(0);
}
}
}
/* somewhere in the game where a random monster may spawn */
var monsterSpawn = Defs.tileTypes[tiles[x][y].type].generate.monsters();
if (monsterSpawn != null) {
/* add monster to tile or wherever a new monster goes */
}
/* repeat for other generated types */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment