var prev_board = []
$(function () {
var init_board = [0, 2, 0, 0, 0, 0, -5, 0, -3, 0, 0, 0, 5, -5, 0, 0, 0, 3, 0, 5, 0, 0, 0, 0, -2, 0];
var red = "#E83D04"
var white = "#E8E077"
var brown = "#4C2E00"
var prev_board = []
var color = white;
// Build pins
for (var i = 0; i < 26; i++) {
if (i < 13 && 0 < i) {
var pos = 'bottom';
} else if (i > 12 && i < 25) {
var pos = 'top';
} else {
var pos = 'bar';
}
if (color == white) {
color = red;
} else {
color = white;
}
if (i == 0 || i == 25) {
color = brown;
}
var div = $("
").addClass("pin").addClass("pin-"+pos).attr('id', 'pin-'+i);
var checkers_div = $("").addClass("checkers").attr('id', 'checkers-'+i);
var checkers_list = $("").addClass("checkers_list").attr('id', 'checkers_list-'+i);
checkers_div.append(checkers_list);
div.append(checkers_div);
$( "#pins" ).append(div);
}
var div = $("").addClass("pin").addClass("pin-26").attr('id', 'pin-26');
var checkers_div = $("").addClass("checkers").attr('id', 'checkers-26');
var checkers_list = $("").addClass("checkers_list").attr('id', 'checkers_list-26');
checkers_div.append(checkers_list);
div.append(checkers_div);
$( "#pins" ).append(div);
convertToPins(init_board);
prev_board = convertToBoard();
$( ".checkers_list" ).sortable({
connectWith: ".checkers_list",
receive: function (event, ui) {
console.log(prev_board);
handleMove();
console.log(prev_board);
}
});
});
function handleMove() {
var board = convertToBoard();
postRequest(board);
prev_board = board;
};
function convertToBoard() {
var board = []
for (var i = 0; i < 26; i++) {
var amount = $( "#checkers_list-"+i ).children('li').length;
if (amount != 0) {
var sign = ($("#checkers_list-"+i+"> li").attr('class').split(' ')[0]);
board.push(sign*amount);
} else {
board.push(0);
}
}
// console.log(board);
return board
}
function convertToPins(board ) {
// We don't want to deal with bars RIGHT now, TODO: Fix this.
for (var i = 1; i < 25; i++) {
for (var amt_at_pin = 0; amt_at_pin < Math.abs(board[i]); amt_at_pin++) {
var sign = Math.sign(board[i]);
if (sign > 0) {
var list_obj = $( "").addClass(Math.sign(board[i]).toString());
} else if (sign < 0) {
var list_obj = $( "").addClass(Math.sign(board[i]).toString());
}
$( '#checkers_list-'+i ).append(list_obj);
}
}
};
function onReceived(data) {
var obj = JSON.stringify(data);
alert(obj);
};
function getRequest() {
$.ajax({
url: 'http://127.0.0.1:5000/get_board',
dataType: 'JSONP',
data: {
format: 'json'
},
type: 'GET',
success: onReceived
});
};
function onPost(data) {
console.log(data);
};
function postRequest(board) {
var data = {'board' : board.toString()}
$.ajax({
type : "POST",
url : "http://127.0.0.1:5000/post_board",
data: JSON.stringify(data),
success: onPost
});
};