You are previewing Eloquent JavaScript.

Eloquent JavaScript

Cover of Eloquent JavaScript by Marijn Haverbeke Published by No Starch Press

Building an Ecosystem Simulation

In this chapter, we are going to build a virtual terrarium, a tank with insects moving around in it. We will build objects that model the terrarium and the creatures inside it, and we will write methods for those objects to “animate” the creatures and allow them (turn by turn) to live their lives.

Defining the Terrarium

We take a rather simple approach and make the terrarium a two-dimensional grid. On this grid there are a number of bugs. When the terrarium is activated, all the bugs get a chance to take an action, such as moving, which changes the state of the terrarium.

Thus, we chop both time and space into units with a fixed size—squares for space; “turns” for time. This usually makes things easier to model in ...

The best content for your career. Discover unlimited learning on demand for around $1/day.