var grove =require("jsupm_grove");
var sensorModule = require('jsupm_ttp223');
var touch = new sensorModule.TTP223(3);
var LCD = require("jsupm_i2clcd");
var lcd = new LCD.Jhd1313m1(6, 0x3E, 0x62);
var shuffle = function() {return Math.random()-.5};
var t = [0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7];
t.sort(shuffle);
var startTime;
function startTimer(){
startTime = new Date();
}
function getTime(){
var time = new Date();
return time-startTime;
}
function calc(){
var sum = 0;
for(i = 0; i < 16; i++){
for(j = i+1; j < 16; j++){
if(t[i]>t[j]) sum++;
}
}
return sum;
}
var d = calc();
var f3js = require('f3js')
, c = f3js.createContainer()
, x = 10
, y = 10
, width = 100
, height = 105
, thickness = 42
, jw = 7
, jh = 2;
c.x = x;
c.y = y;
var p = c.jrc(0, 0, width, height, jw, jh);
c.add(touch, { x: 80 + 0, y: 80 + 0 });
c.drawRectangle(15, 59, 10, 6);
c.drawRectangle(45, 59, 10, 6);
c.drawRectangle(75, 59, 10, 6);
var ps = p.extrude(45);
ps[0].x = width + 5;
ps[0].y = jh;
ps[1].x = width + 5;
ps[1].y = (thickness + 5) * 2 + jh;
ps[2].x = width + 5;
ps[2].y = thickness + 5 + jh;
ps[3].x = width + 5;
ps[3].y = (thickness + 5) * 3 + jh;
ps[4].x = 0;
ps[4].y = height + 5;
for (var i = 0; i < ps.length; i ++) {
c.add(ps[i]);
}
ps[1].drawRectangle(jh + 5, thickness - jh - 5, height - jh*2 - 10, -10);
function t2s(t){
var s = '';
for(i = 0; i < 16; i++){
s += t[i].toString(16);
}
return s;
}
function display(t){
lcd.setCursor(0, 0);
lcd.write(t2s(t));
lcd.setCursor(1, 0);
lcd.write(('0'+calc()).slice(-2));
}
function arrange(t, b, x){
for(j = 0; j < Math.abs(b); j++){
var i = Math.floor(Math.random()*15);
if((b>0 && t[i]>t[i+1]) || (b<0 && t[i]<t[i+1])){
var tt = t[i+1];
t[i+1] = t[i];
t[i] = tt;
x--;
if(x<=0) return;
}
}
}
function sorted(t){
for(i = 0; i < 15; i++){
if(t[i]>t[i+1]) return false;
}
return true;
}
var idleInterval = false;
var prev = 0;
function startIdle() {
display(t);
idleInterval = setInterval(function() {
var curr = touch.value();
if(curr) curr = 1;
else curr = 0;
console.log(curr.toString());
if (prev == 0 && curr > 0) {
console.log('touched');
console.log(t2s(t));
if(sorted(t)){
var time = getTime();
var score = Math.floor(d/time*10000);
lcd.setCursor(1, 0);
var scoreStr = 'SCORE: ' + score.toString();
console.log(scoreStr);
lcd.write(scoreStr);
clearInterval(idleInterval);
idleInterval = false;
return;
}
arrange(t, 10);
} else {
if(Math.random()<0.3) arrange(t, -1, 1);
}
display(t, 3);
prev = curr;
}, 100);
}
var interval = false, score;
function stopGame() {
if (interval) {
clearInterval(interval);
interval = false;
}
if (!idleInterval) {
startIdle();
}
}
function startGame() {
}
startTimer();
startIdle();
process.on('SIGINT', function() {
if (interval) {
clearInterval(interval);
}
lcd.setColor(255, 255, 255);
process.exit(0);
});