Advertisement
ptrelford

Blackjack scoring

Apr 9th, 2012
217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Erlang 1.46 KB | None | 0 0
  1. -module(bj).
  2. -export([deck/0,total/1,is_bust/1,is_blackjack/1,compare/2]).
  3.  
  4. ranks() -> ["A","2","3","4","5","6","7","8","9","10","J","Q","K"].
  5. suits() -> [club,spade,heart,diamond].
  6. deck()  -> Cards=[{R,S}||R<-ranks(),S<-suits()], shuffle(Cards).
  7.  
  8. shuffle(Deck) ->
  9.  Gt=fun({A,_},{B,_})-> A > B end,
  10.  Cards=[{random:uniform(),Card}||Card<-Deck],
  11.  [Card||{_,Card}<-lists:sort(Gt,Cards)].
  12.  
  13. total(Aces_low,Has_ace) when Has_ace -> {Aces_low,Aces_low+10};
  14. total(Total,_) -> Total.
  15. total(Ranks) ->
  16.  Total=lists:sum([value(Rank)||Rank<-Ranks]),
  17.  Is_ace=fun(X) -> X =:= "A" end,
  18.  Has_ace=lists:any(Is_ace,Ranks),
  19.  total(Total,Has_ace).
  20.  
  21. is_bust({Lo,_}) -> is_bust(Lo);
  22. is_bust(Total) -> Total > 21.
  23.  
  24. best({Lo,Hi}) ->
  25.  Bust=is_bust(Hi),
  26.  if not Bust -> Hi;
  27.     Bust -> best(Lo)
  28.  end;
  29. best(Total) ->
  30.  Bust=is_bust(Total),
  31.  if not Bust -> Total
  32.  end.
  33.  
  34. is_blackjack(["J","A"]) -> true;
  35. is_blackjack(["A","J"]) -> true;
  36. is_blackjack(_) -> false.
  37.  
  38. compare(Player,Dealer) ->
  39.  Player_total=best(total(Player)),
  40.  Dealer_total=best(total(Dealer)),
  41.  if
  42.     Player_total  >  Dealer_total -> win;
  43.     Player_total =:= Dealer_total ->
  44.       case {is_blackjack(Player),is_blackjack(Dealer)} of
  45.        {true,false} -> win;
  46.        {false,true} -> lose;
  47.        {_,_} -> push
  48.       end;
  49.     Player_total =<  Dealer_total -> lose
  50.  end.
  51.  
  52. value(Rank) ->
  53.  Values=lists:zip(ranks(),[1,2,3,4,5,6,7,8,9,10,10,10,10]),
  54.  lists:sum([Score||{Text,Score}<-Values,Text=:=Rank]).
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement