Eloquent JavaScript: Chapter 7 - Electronic Life
Simulate electronic life
by Denise Nepraunig
HTML
<h1>Electronic Life v1</h1>
<!-- http://eloquentjavascript.net/2nd_edition/preview/07_elife.html -->
<div id="simulation">
</div>
CSS
#simulation, h1 {
font-family: "Courier New", Courier, monospace;
font-weight: bold;
text-align: center;
}
h1 {
margin-top: 120px;
}
body {
background-color: black;
color: red;
}
JavaScript
var plan =
[ "############################",
"# # # o ##",
"# #",
"# ##### #",
"## # # ## #",
"### ## # #",
"# ### # #",
"# #### #",
"# ## o #",
"# o # o ### #",
"# # #",
"############################"];
function Vector(x, y) {
this.x = x;
this.y = y;
}
Vector.prototype.plus = function (other) {
return new Vector(this.x + other.x, this.y + other.y);
};
function Grid(width, height) {
this.space = new Array(width * height);
this.width = width;
this.height = height;
}
Grid.prototype.isInside = function (vector) {
return vector.x >= 0 && vector.x < this.width &&
vector.y >= 0 && vector.y < this.height;
};
Grid.prototype.get = function (vector) {
return this.space[vector.x + this.width * vector.y];
};
Grid.prototype.set = function (vector, value) {
this.space[vector.x + this.width * vector.y] = value;
};
var directions = {
"n": new Vector(0, -1),
"ne": new Vector(1, -1),
"e": new Vector(1, 0),
"se": new Vector(1, 1),
"s": new Vector(0, 1),
"sw": new Vector(-1, 1),
"w": new Vector(-1, 0),
"nw": new Vector(-1, -1)
};
function randomElement(array) {
return array[Math.floor(Math.random() * array.length)];
}
function BouncingCritter() {
this.direction = randomElement(Object.keys(directions));
}
BouncingCritter.prototype.act = function (view) {
if (view.look(this.direction) != " ")
//this.direction = view.find(" ") || "s";
...