Object oriented Terrarium

by Mehmetcan Sinir

JavaScript

// In this chapter we are going to build a virtual terrarium, a tank with insects moving around in it. A two-dimensional grid. On this grid there are a number of bugs. When the terrarium is active, all the bugs get a chance to take an action, such as moving, every half second. 


//an array of strings which represent the walls of the terrarium, and ornamental rocks lying in it, the o's repesent the insects, empty space is empty space.
var thePlan = 
    ["############################",
    "#      #    #      o      ##",
    "#                          #",
    "#          #####           #",
    "##         #   #    ##     #",
    "###           ##     #     #",
    "#           ###      #     #",
    "#   ####                   #",
    "#   ##       o             #",
    "# o  #         o       ### #",
    "#    #                     #",
    "############################"];

//our point constructor
function Point(x, y) {
    this.x = x;
    this.y = y;
}
//add a point with another point and return a new point
Point.prototype.add = function (point) {
    return new Point(this.x + point.x, this.y + point.y);
};

//returns true if two points are equal
Point.prototype.isEqualTo = function (point) {
    return this.x == point.x && this.y == point.y;
};

//data representation, represent the grid, figure out how you will represent the grid values of every point in the grid, the below array represents:
//(x,y) = x + y*width(width of the grid), in this case four;

var grid = ["0,0", "1,0", "2,0", "3,0",
    "0,1", "1,1", "2,1", "3,1"];

//write your grid constructor

function Grid(width, height) {
    this.width = width;
    this.height = height;
    //the cells is an array with length of all cells, with undefined values
    this.cells = new Array(width * height);
}
//when you enter the name of the point, it will return the point's value by using its coordinates
Grid.prototype.valueAt = function (point) {
    return this.cells[point.x + point.y * this.width];
};

//this...