Manandy Software Development --- Board Tile Collection

Board Tile Collection

by Andy Novocin

HTML

<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.0/backbone-min.js"></script>
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.css">
<script src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/js/bootstrap.js"></script>
<script src="http://code.createjs.com/easeljs-0.7.0.min.js"></script>
<script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<div id="messages"></div>

JavaScript

function AdjacencyMatrix(nboxes){
    this.nboxes = nboxes;
    this.adjacencymatrix = new Array(this.nboxes);
    var i, j;
    for(i = 0; i < this.nboxes; i++){
        this.adjacencymatrix[i] = new Array(this.nboxes);
        for(j = 0; j < this.nboxes; j++){
            this.adjacencymatrix[i][j] = 0;
        }
    }
}

AdjacencyMatrix.prototype.getEdge = function(n1,n2){
    return this.adjacencymatrix[n1][n2];
};

AdjacencyMatrix.prototype.setEdge = function(n1, n2, val){
    if(n1 < 0 || n2 < 0 || n1 >= this.nboxes || n2 >= this.nboxes){
        return null;
    }
    this.adjacencymatrix[n1][n2] = val;
    return true;
};

AdjacencyMatrix.prototype.setEdgeSymmetric = function(n1, n2, val){
    var q = this.setEdge(n1,n2,val);
    if(q === null){return null;}
    q = this.setEdge(n2,n1,val);
    if(q === null){return null;}
    return true;
};

var createSquare = function(edgeLength){
    var myMatrix = new AdjacencyMatrix(edgeLength*edgeLength);
    var addNeighbors = function(i,j){
        var deltas = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1,1]];
        _.each(deltas, function(tupe){
            var neighbor = [i + tupe[0], j + tupe[1]];
            if (neighbor[0] >= 0 && neighbor[0] < edgeLength && neighbor[1] >= 0 && neighbor[1] < edgeLength){
                myMatrix.setEdge(neighbor[0]*edgeLength + neighbor[1], i*edgeLength + j, 1);
            }
        });
    };

    _.each(_.range(edgeLength), function(i){
        _.each(_.range(edgeLength), function(j){
            addNeighbors(i,j);
        });
    });
    console.log(myMatrix);
}
                     
createSquare(3);