Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save spamwax/71edecff2f0b2d26c68f to your computer and use it in GitHub Desktop.
Save spamwax/71edecff2f0b2d26c68f to your computer and use it in GitHub Desktop.
Solution to eloquentjavascript exercise second 2nd edition (Chapter 7) eloquent javascript
function Plant() {
this.energy = 3 + Math.random() * 4;
}
Plant.prototype.act = function(context) {
if (this.energy > 19) {
var space = context.find(" ");
if (space)
return {type: "reproduce", direction: space};
}
if (this.energy < 20)
return {type: "grow"};
};
function PlantEater() {
this.energy = 20;
this.direction = randomElement(Object.keys(directions));
this.eatCounter = 1;
}
PlantEater.prototype.act = function(context) {
var space = context.find(" ");
if (this.energy > 40 && space)
return {type: "reproduce", direction: space};
var plant = context.findAll("*");
if (plant.length > 1) {
if (this.eatCounter >= 0) {
this.eatCounter = 0;
return {type: "eat", direction: randomElement(plant)};
} else {
this.eatCounter++;
}
}
if (space) {
var spaces = context.findAll(" ");
if (spaces.indexOf(this.direction) == -1) {
this.direction = space;
}
return {type: "move", direction: this.direction};
} else {
this.direction = "s";
}
};
function Tiger() {
this.energy = 40 + Math.random() * 10;
this.direction = randomElement(Object.keys(directions));
}
Tiger.prototype.act = function (context) {
var space = context.find(" ");
var critter = context.find("O");
if (critter) {
return {type: "eat", direction: critter};
}
if (this.energy > 50 && space) {
return {type: "reproduce", direction: space};
}
if (space) {
var spaces = context.findAll(" ");
if (spaces.indexOf(this.direction) == -1) {
this.direction = space;
}
return {type: "move", direction: this.direction};
} else {
this.direction = "s";
}
}
var legend = {
"#": Wall,
"@": Tiger,
"O": PlantEater,
"*": Plant};
var valley = new LifelikeWorld(
[
"####################################################",
"# #### **** ###",
"# * @ ## ######## OO ##",
"# * ## O O **** *#",
"# ##* ########## *#",
"# ##*** * **** **#",
"#* ** # * *** @ ######### **#",
"#* ** # * # * **#",
"# ## # O # ***@ ######",
"#* @ # # * O # #",
"#* # ###### ** #",
"### **** *** ** #",
"# O @ O #",
"# * ## ## ## ## ### * #",
"# ** # @ * ##### O #",
"## ** O O # # *** *** ### ** #",
"### # ***** ****#",
"####################################################"],
legend
);
console.log(valley.toString());
for (var i = 0; i < 1000; i++) {
valley.turn();
console.log(valley.toString());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment