Skip to content

Instantly share code, notes, and snippets.

@isaacs
Forked from anonymous/file.js
Created September 8, 2009 05:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save isaacs/182743 to your computer and use it in GitHub Desktop.
Save isaacs/182743 to your computer and use it in GitHub Desktop.
// more lines, ever-so-slightly faster search, though.
function checkValidMove (xo, pos, state) {
// invalid move.
if (state[pos[0]][pos[1]] !== '') return false;
state[pos[0]][pos[1]] = xo;
// check row
for (var i = 0, col = 0; i < 3; i ++) if (state[pos[0]][i] === xo) col ++;
if (col === 3) return "a winner is you";
// check col
for (var i = 0, row = 0; i < 3; i ++) if (state[i][pos[1]] === xo) row ++;
if (row === 3) return "a winner is you";
// check \
if (pos[0] === pos[1]) for (var i = 0, diag = 0; i < 3; i ++) if (state[i][i] === xo) diag ++;
if (diag === 3) return "a winner is you";
// check /
if (pos[0] === 2-pos[1]) for (var i = 0, diag = 0; i < 3; i ++) if (state[i][2-i] === xo) diag ++;
if (diag === 3) return "a winner is you";
return "no winner for you!";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment