Created
May 16, 2010 21:27
-
-
Save josephwilk/403180 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| -module(tictactoe). | |
| -export([start/1]). | |
| -import(random). | |
| start(Inputs) -> | |
| Board = lists:nth(1, Inputs), | |
| Piece = whoAmI(Board), | |
| ValidMoves = freeSpaces(Board), | |
| Move = selectBestMove(ValidMoves, Piece, Board), | |
| io:format(integer_to_list(Move)), | |
| erlang:halt(). | |
| selectBestMove(ValidMoves, Piece, Board) -> | |
| WeightedMoves = weightedMoves(Piece, ValidMoves, Board), | |
| lists:nth(1, WeightedMoves) - 1. | |
| weightedMoves(Piece, ValidMoves, Board) -> | |
| lists:map(fun(Move) | |
| %NewBoard = Board[Move] = Piece, | |
| rank(Piece, NewBoard) | |
| end, ValidMoves) | |
| rank(Piece, Board) -> | |
| win(Piece, Board) + blockLoss(Piece, Board) + fork(Piece, Board). | |
| fork(Piece, Board) -> | |
| 0. | |
| win(Piece, Board) -> | |
| if | |
| str(Board, "ooo") =/= 0 -> | |
| 1; | |
| true -> | |
| 0; | |
| end. | |
| blockLoss(Piece, Board) -> | |
| 0. | |
| freeSpaces(Board) -> | |
| AllMoves = lists:seq(1, 9), | |
| lists:filter( | |
| fun(Item) -> | |
| Char = lists:nth(Item, Board), | |
| if | |
| Char =:= $- -> | |
| true; | |
| true -> | |
| false | |
| end | |
| end, AllMoves). | |
| whoAmI(Board) -> | |
| NumO = frequencyCount($o, Board), | |
| NumX = frequencyCount($x, Board), | |
| if | |
| (NumO > NumX) -> | |
| x; | |
| true -> | |
| whoAmI(NumO, NumX) | |
| end. | |
| %This is really my inability to get nested if loops to be syntaxtically correct | |
| whoAmI(NumO, NumX) -> | |
| if | |
| NumO =:= NumX -> | |
| o; | |
| true -> | |
| x | |
| end. | |
| frequencyCount(Char, Board) -> | |
| lists:foldl(fun(X, Sum) -> | |
| if | |
| X =:= Char -> Sum + 1; | |
| true -> Sum + 0 | |
| end | |
| end, 0, Board). | |
| dumpList(List) -> | |
| io:format(lists:map(fun(X) -> integer_to_list(X) end, List)). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment