Created
November 14, 2015 21:03
-
-
Save rafd/9d1b967c691bf158939c to your computer and use it in GitHub Desktop.
tic tac toe bot
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var last = function(arr) { | |
return arr[arr.length - 1]; | |
} | |
var coordinate1 = function(state) { | |
return last(state["history"])["move"][1]; | |
} | |
var firstFromSquare = function(square_arr){ | |
for(var i = 0; i < square_arr.length; i++){ | |
if(square_arr[i] == null){ | |
return i; | |
} | |
} | |
return null; | |
} | |
var firstFromBoard = function(grid) { | |
for(var i = 0; i < grid.length; i++) { | |
for(var j = 0; j < grid[i].length; j++) { | |
if(grid[i][j] == null) { | |
return [i, j]; | |
} | |
} | |
} | |
} | |
var squareWon = function(square) { | |
var opts = [[0, 1, 2], [0, 4, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [2, 4, 6], [3, 4, 5], [6, 7, 8]] | |
var won = false; | |
for(var i = 0; i < opts.length; i++) { | |
var o = opts[i]; | |
if(square[o[0]] != null && square[o[0]] == square[o[1]] && square[o[0]] == square[o[2]]) { | |
return true; | |
} | |
}; | |
return false; | |
} | |
var bot = function(state) { | |
// if we are player one, play [2, 2] | |
if(state["history"].length == 0) { | |
return [2, 2]; | |
} else { | |
var c1 = coordinate1(state); | |
var c2 = firstFromSquare(state["grid"][c1]); | |
if(c2 == null || squareWon(state["grid"][c1])) { | |
return firstFromBoard(state["grid"]); | |
} else { | |
return [c1, c2]; | |
} | |
} | |
} | |
// PASTE ABOVE | |
var arr_to_string = function(arr) { | |
return "["+arr[0]+" "+arr[1]+"]"; | |
} | |
var actual_bot = function(edn_state) { | |
var state = edn_to_json(edn_state); | |
return arr_to_string(bot(state)); | |
} | |
actual_bot; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment