Created
June 26, 2011 03:47
-
-
Save tafsiri/1047205 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
%3 Write a board that takes a tic-tac-toe board presented as a list or tuple | |
% Return the current state of the game (winner, no winner yet, tie, incomplete) | |
tictactoe(Board) -> | |
[S11, S12, S13, | |
S21, S22, S23, | |
S31, S32, S33] = Board, | |
Rows = [[S11, S12, S13], [S21, S22, S23], [S31, S32, S33]], | |
Cols = [[S11, S21, S31], [S12, S22, S32], [S13, S23, S33]], | |
Diag = [[S11, S22, S33], [S13, S22, S31]], | |
Lines = lists:append([Rows, Cols, Diag]), | |
%look for winners | |
HasWinner = fun(Line) -> | |
case same(Line) of | |
{true, x} -> io:format("Winner is X~n"), true; %print and return true | |
{true, o} -> io:format("Winner is O~n"), true; | |
{_, _} -> nil, false | |
end | |
end, | |
Winners = lists:dropwhile(fun(Line) -> HasWinner(Line) == false end, Lines), | |
case Winners of | |
[] -> | |
%look for space to play | |
case lists:any(fun(S) -> e == S end, lists:flatten(Lines)) of | |
true -> io:format("No Winner~n"); | |
false -> io:format("Tie~n") | |
end; | |
_ -> done | |
end. | |
%check if all vals are the same and return true or false | |
%as well as the first val in that list | |
same(List) -> | |
First = lists:nth(1, List), | |
{lists:all(fun(X) -> First == X end, List), First}. | |
%tic-tac-toe driver function | |
tt1() -> | |
B = [x, x, o, | |
o, o, e, | |
x, o, x], | |
tictactoe(B). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment