Last active
December 29, 2015 19:18
-
-
Save odhranroche/7716028 to your computer and use it in GitHub Desktop.
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
// static evaluate function | |
// adapted from http://kartikkukreja.wordpress.com/2013/03/30/heuristic-function-for-tic-tac-toe/ | |
// original author : Kartik Kukreja | |
val wins = Array( Array(0,1,2), Array(3,4,5), Array(6,7,8), | |
Array(0,3,6), Array(1,4,7), Array(2,5,8), | |
Array(0,4,8), Array(2,4,6) ) | |
val heuristic = Array( Array(0, -10, -100, -1000), | |
Array(10, 0, 0 , 0), | |
Array(100, 0, 0, 0), | |
Array(1000, 0, 0, 0) ) | |
// good = positive numbers, bad = negative numbers | |
def evaluatePosition(board:Array[Int], player:Int):Int = { | |
val opponent:Int = player*(-1) | |
var players = 0 | |
var others = 0 | |
var total = 0 | |
for(i <- wins){ | |
players = 0 | |
others = 0 | |
for(j <- i){ | |
if (board(j) == player){ | |
players += 1 | |
}else if(board(j) == opponent){ | |
others += 1 | |
} | |
} | |
total += heuristic(players)(others) | |
} | |
total | |
} | |
// X = -1 max player, O = 1 min player | |
def minmax(board:Array[Int], height:Int, player:Int):Double={ | |
if(height == 0) | |
evaluatePosition(board, player) | |
var alpha = -player * Double.PositiveInfinity; | |
val allBoards = makeAllPossibleMoves(board, player) // array of all child boards | |
for(b <- allBoards){ | |
val score = minmax(b, height-1, -player) | |
alpha = if (player == -1) Math.max(alpha, score) else Math.min(alpha, score) | |
} | |
alpha | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment