Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -module(bj).
- -export([deck/0,total/1,is_bust/1,is_blackjack/1,compare/2]).
- ranks() -> ["A","2","3","4","5","6","7","8","9","10","J","Q","K"].
- suits() -> [club,spade,heart,diamond].
- deck() -> Cards=[{R,S}||R<-ranks(),S<-suits()], shuffle(Cards).
- shuffle(Deck) ->
- Gt=fun({A,_},{B,_})-> A > B end,
- Cards=[{random:uniform(),Card}||Card<-Deck],
- [Card||{_,Card}<-lists:sort(Gt,Cards)].
- total(Aces_low,Has_ace) when Has_ace -> {Aces_low,Aces_low+10};
- total(Total,_) -> Total.
- total(Ranks) ->
- Total=lists:sum([value(Rank)||Rank<-Ranks]),
- Is_ace=fun(X) -> X =:= "A" end,
- Has_ace=lists:any(Is_ace,Ranks),
- total(Total,Has_ace).
- is_bust({Lo,_}) -> is_bust(Lo);
- is_bust(Total) -> Total > 21.
- best({Lo,Hi}) ->
- Bust=is_bust(Hi),
- if not Bust -> Hi;
- Bust -> best(Lo)
- end;
- best(Total) ->
- Bust=is_bust(Total),
- if not Bust -> Total
- end.
- is_blackjack(["J","A"]) -> true;
- is_blackjack(["A","J"]) -> true;
- is_blackjack(_) -> false.
- compare(Player,Dealer) ->
- Player_total=best(total(Player)),
- Dealer_total=best(total(Dealer)),
- if
- Player_total > Dealer_total -> win;
- Player_total =:= Dealer_total ->
- case {is_blackjack(Player),is_blackjack(Dealer)} of
- {true,false} -> win;
- {false,true} -> lose;
- {_,_} -> push
- end;
- Player_total =< Dealer_total -> lose
- end.
- value(Rank) ->
- Values=lists:zip(ranks(),[1,2,3,4,5,6,7,8,9,10,10,10,10]),
- lists:sum([Score||{Text,Score}<-Values,Text=:=Rank]).
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement