st0le
7/11/2013 - 7:35 PM

Calc Khan Academy

Calc Khan Academy

var gridWidth = 100;
var drawBlock = function(x,y,txt,color){
    
    fill(color[0], color[1], color[2]);
    rect(x*gridWidth,y*gridWidth,gridWidth,gridWidth);
    fill(0, 0, 0);
    textSize(35);
    if( txt === 10){
        txt = "+";    
    }else if(txt === 11){
        txt = "-";
    }else if(txt === 12){
        txt = "=";
    }
    text(txt,x*gridWidth + gridWidth/3,y*gridWidth+ gridWidth/2);
};
var drawBlocks = function(sx,sy){
    var selectedColor = [255,0,0],nonSelectedColor=[255,255,0];
    var  k = 1;
    for(var j = 0; j < 4; j++){
        for(var i = 0; i < 3; i++,k++){
            if(j === sy && i === sx){
                drawBlock(i,j,k,selectedColor);
            }else{
                drawBlock(i,j,k,nonSelectedColor);
            }
        }
    }
};

var opColor = [0,255,0];
var opA = 0,opB = 0,op;
var opClicked = false;
var draw = function() {
     if(mouseIsPressed && mouseButton === LEFT){
        var sx = (mouseX/gridWidth)|0;
        var sy = (mouseY/gridWidth)|0;
        drawBlocks(sx,sy);
        var k = sy * 3 + sx  + 1;
        if(k === 10){ // + was clicked
            op = "+";
            drawBlock(3,1,"+",opColor);
            opClicked = true;
        }else if(k === 11){ // - was clicked
            op = "-";
            drawBlock(3,1,"-",opColor);
            opClicked = true;
        }else if(k === 12 && opClicked){ // = was clicked
            var result = 0;
            if(op === "+"){
                result = opA + opB;
            }else if(op === "-"){
                result = opA - opB;
            }
            debug(result);
            drawBlock(3,3,result,opColor);
            opClicked = false;
            //opA = opB = 0;
        }else if( k < 10){
            if(opClicked){
                opB = k;
                drawBlock(3,2,opB,opColor);
            }else{
                
                opA = k;
                drawBlock(3,0,opA,opColor);
            }
        }
        
     }else{
         drawBlocks(-1,-1);
     }
};