Skip to content

Instantly share code, notes, and snippets.

@justinobney
Last active August 29, 2015 14:16
Show Gist options
  • Save justinobney/e043b8d43125267c5720 to your computer and use it in GitHub Desktop.
Save justinobney/e043b8d43125267c5720 to your computer and use it in GitHub Desktop.
Simple tic tac toe logic
var winningBoards = [
genWinningColBoard(0),
genWinningColBoard(1),
genWinningColBoard(2),
genWinningRowBoard(0),
genWinningRowBoard(1),
genWinningRowBoard(2),
getDiagonalBoard(3),
getDiagonalBoard(3, true)
];
function getDiagonalBoard(size, invert){
var board = [];
var holder;
var test = invert ? invertTest : regTest;
if(size % 2 === 0){
throw new Error("Boards size must be a odd number")
}
for(var row = 0;row<size;row++){
holder = [];
for(var col = 0;col<size;col++){
var val = test(row,col, size) ? 1 : 0;
holder.push(val);
}
board.push(holder.slice())
}
return board
function regTest(row,col,size){
return row === col
}
function invertTest(row,col,size){
return col === size - row- 1;
}
}
function genWinningRowBoard(rowIdx){
return [0,1,2].map(function(idx){
var val = idx == rowIdx ? 1 : 0;
return [val, val, val]
});
}
function genWinningColBoard(colIdx){
return [0,1,2].map(function(idx){
var row = [0, 0, 0]
row[colIdx] = 1;
return row
});
}
function checkBoard(input, val){
var converted = input.map(function(row){
return row.map(function(pos){
return pos === val ? 1 : 0
})
})
return winningBoards.map(function(board){
return board.map(function(row, rowIdx){
return row.map(function(pos, posIdx){
return pos === 0 || (pos === 1 && converted[rowIdx][posIdx] === 1);
})
})
}).filter(function(checked){
return checked.toString() === 'true,true,true,true,true,true,true,true,true'
})
}
checkBoard([
[1, 0, null],
[1, 0, 0],
[1, null, 1]
], 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment