Chapter 3: Dominos

JavaScript

var paper = Raphael(0, 0 ,900,900),
    SPACING = 18,
    RADIUS = 4;

var patterns = [
    "",      // 0 dots
    "5",      // 1 dot
    "3-7",      // 2 dots
    "3-5-7",      // 3 dots
    "1-3-7-9",      // 4 dots
    "1-3-5-7-9",      // 5 dots
    "1-2-3-7-8-9"      // 6 dots
];

function make_dot(number) {
    number -= 1;
    if (number < 0 || number > 9) {
        console.log("Invalid number.");
        return null;
    }
    // first, second, or third column
    var x = Math.floor(number / 3);
    // first, second, or third row of that column
    var y = number % 3;
    var dot = paper.circle(x * SPACING + SPACING / 2, y * SPACING + SPACING / 2, RADIUS).attr("fill", "black");    
    return dot;
}

function make_face(dots) {
    if (typeof dots === "string") {
        dots = dots.split("-");
    }
    var tile = paper.set();
    
    //square
    tile.push(paper.rect(0, 0, SPACING * 3, SPACING * 3).attr({ fill: "#FFF"}));
    
    //dots
    for (var c = 0; c < dots.length; c += 1) {
        tile.push(make_dot(dots[c]));
    }
    
    return tile;    
}

function tile(num_dots_top, num_dots_bottom, x, y, a) {
    if (typeof(num_dots_top) === "undefined" || typeof(num_dots_top) === "undefined") {
        console.log("You must supply values for both sides of the tile.");        
        return null;
    }
    
    // positional info. Defaults 
    var pos = { x: x || 0, y: y || 0, a: a || 0 },
        centroid = { x: pos.x + SPACING * 1.5, y: pos.y + SPACING * 3 };
    
    // Raphael objects
    var top = make_face(patterns[num_dots_top]),
        bottom = make_face(patterns[num_dots_bottom]),
        piece = paper.set([top, bottom]);

    // function to place piece at x,y location, rotated to angle a (in degrees)
    var move = function(x, y, a) {
        pos = {x: x, y: y, a: a};
        centroid = { x: pos.x + SPACING * 1.5, y: pos.y + SPACING * 3 };        
        top.transform("T" + x + "," + y + "R" + a + "," + centroid.x + "," + centroid.y);
   ...