riichi/src/riichi_hand.erl

87 lines
2.4 KiB
Erlang
Raw Normal View History

%% @author Correl Roush <correl@gmail.com>
%%
%% @doc Riichi Mahjong library.
2012-07-03 02:05:05 +00:00
-module(riichi_hand).
2012-07-21 01:09:28 +00:00
-include("../include/riichi.hrl").
2012-07-03 02:05:05 +00:00
-export([find/1,
tiles/1,
head/1,
is_complete/1,
waits/1]).
2012-07-03 02:05:05 +00:00
-spec find
(hand()) -> [hand()];
([tile()]) -> [hand()].
2012-08-01 02:23:46 +00:00
find(#hand{} = Hand) ->
find(lists:sort(tiles(Hand)));
2012-07-21 01:09:28 +00:00
find(Tiles) ->
find(lists:sort(Tiles), #hand{}, []).
2012-07-03 02:05:05 +00:00
-spec find([tile()], hand(), [hand()]) -> [hand()].
2012-07-21 01:09:28 +00:00
find([], Hand, Possible) ->
[Hand|Possible];
2012-07-03 02:05:05 +00:00
2012-07-21 04:09:27 +00:00
find(Tiles, Hand = #hand{tiles=HT, melds=HM}, Possible) ->
2012-07-21 01:09:28 +00:00
case Tiles of
[T, T, T|Rest] ->
2012-07-21 04:09:27 +00:00
find(Rest, Hand#hand{melds=[#meld{type=pon, tiles=[T, T, T]}|HM]}, Possible);
2012-07-21 01:09:28 +00:00
_ ->
[]
end ++
case Tiles of
[T, T|Rest] ->
2012-07-21 04:09:27 +00:00
find(Rest, Hand#hand{melds=[#meld{type=pair, tiles=[T, T]}|HM]}, Possible);
2012-07-21 01:09:28 +00:00
_ ->
[]
end ++
case lists:sort(sets:to_list(sets:from_list(Tiles))) of
[T1 = #tile{value=V1, suit=S}, T2 = #tile{value=V2, suit=S}, T3 = #tile{value=V3, suit=S}|_] when
is_integer(V1) andalso
[V1, V2, V3] =:= [V1, V1 + 1, V1 + 2] ->
2012-07-21 04:09:27 +00:00
find(Tiles -- [T1, T2, T3], Hand#hand{melds=[#meld{type=chii, tiles=[T1, T2, T3]}|HM]}, Possible);
2012-07-21 01:09:28 +00:00
_ ->
[]
end ++
case Tiles of
[T|Rest] ->
find(Rest, Hand#hand{tiles=[T|HT]}, Possible)
end.
2012-07-03 02:05:05 +00:00
-spec tiles(hand()) -> [tile()].
2012-08-01 01:49:51 +00:00
tiles(#hand{tiles=Tiles, melds=Melds}) ->
lists:flatten([TS || #meld{tiles=TS} <- Melds]) ++ Tiles.
-spec head(hand()) -> meld() | none.
2012-08-01 01:49:51 +00:00
head(#hand{melds=Melds}) ->
case [M || M = #meld{type=pair} <- Melds] of
[Pair|_] ->
Pair;
[] ->
none
end.
-spec is_complete(hand()) -> boolean().
is_complete(#hand{tiles=[], melds=Melds}=Hand) ->
2012-07-21 04:09:27 +00:00
Pairs = [M || M <- Melds, M#meld.type =:= pair],
2012-07-21 01:09:28 +00:00
case length(Pairs) of
1 ->
% Four mentsu + 1 pair = 5 sets
2012-07-21 04:09:27 +00:00
length(Melds) =:= 5;
2012-07-21 01:09:28 +00:00
7 ->
% Must be seven *unique* pairs
2012-08-01 02:23:46 +00:00
yaku:chiitoitsu(#game{}, #player{hand=Hand});
2012-07-21 01:09:28 +00:00
_ ->
false
end;
is_complete(#hand{}=Hand) ->
2012-08-01 02:23:46 +00:00
yaku:kokushi_musou(#game{}, #player{hand=Hand}).
-spec waits(hand()) -> [tile()].
2012-08-01 02:23:46 +00:00
waits(#hand{}=Hand) ->
[T || T <- ?TILES,
0 < length([H || H <- find(tiles(Hand) ++ [T]),
is_complete(H)])].