Skip to content

Instantly share code, notes, and snippets.

@allanesquina
Last active August 29, 2015 14:26
Show Gist options
  • Save allanesquina/a85511f22e844c346909 to your computer and use it in GitHub Desktop.
Save allanesquina/a85511f22e844c346909 to your computer and use it in GitHub Desktop.
// Creating the matrix;
var matrix = [];
for(var i=0; i<3; i++) {
matrix[i] = [0,0,0];
}
function validate() {
// check result row
var row = matrix.map(function (row) {
var result = 0;
row.map(function (val) {
result += val;
});
return result;
}).filter(function (val) {
return val === 3 || val === 12;
});
if(row.length > 0) return row[0];
//check col
function r(matrix, i) {
var result = 0;
matrix.map(function (row) {
result += row[i]
})
return result;
};
var col = matrix.reduce(function (a, n, i) {
a.push(r(matrix, i));
return a;
}, []).filter(function (val) {
return val === 3 || val === 12;
});
if(col.length > 0) return col[0];
// check cross
var cross = matrix.reduce(function (res, row, i) {
return res += row[i];
},0);
if(cross === 3 || cross === 12) return cross;
var cross = matrix.reverse().reduce(function (res, row, i) {
return res += row[i];
},0);
if(cross === 3 || cross === 12) return cross;
return 0;
}
var turns=0;
function turn(row, col, player) {
var val = matrix[row][col];
if(val === 4 || val === 1) return;
matrix[row][col] = player;
switch (validate()) {
case 0:
console.log('no winner')
break;
case 3:
console.log('Player X wins');
break;
case 12:
console.log('Player O wins');
break;
}
}
//Player X = 1
//Player O = 4
//Col
// turn(0, 1, 4)
// turn(0, 2, 1)
// turn(1, 1, 4)
// turn(0, 0, 1)
// turn(2, 1, 4)
//Row
// turn(0, 0, 4)
// turn(1, 0, 1)
// turn(0, 1, 4)
// turn(1, 1, 1)
// turn(0, 2, 4)
//Cross ->
// turn(0, 0, 4)
// turn(1, 0, 1)
// turn(1, 1, 4)
// turn(2, 1, 1)
// turn(2, 2, 4)
//Cross <-
turn(0, 2, 4)
turn(1, 0, 1)
turn(1, 1, 4)
turn(2, 1, 1)
turn(2, 0, 4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment