# Perl6 solution to Scripting Games #10 (2008)
# Problem statement at http://www.microsoft.com/technet/scriptcenter/funzone/games/games08/aevent10.mspx
# Not counting blank lines or extra lines used for formatting
# the model solution in vbscript took 179 lines, 53 lines to create the deck of cards
# the model perl5 solution took 45 lines (neat code with overloading), 6 lines for the deck
# my perl6 took 30 lines, 1 line for the deck.

# the deck definition shows the power of metaoperators.

use v6;

my %deck = <Ace Two Three Four Five Six Seven Eight Nine Ten Jack Queen King> 
    X~ (" of " X~ <Spades Hearts Diamonds Clubs>) 
    Z (11,2..10,10,10,10 X* 1,1,1,1); 

my $dscore;
my $pscore;
my %dealer;
my %player;
draw %player, %deck, $pscore, 'Player';
draw %dealer, %deck, $dscore, 'Dealer';

repeat {
   draw(%player, %deck, $pscore, 'Player');
} until $pscore >= 21 or prompt("Stay (s) or Hit (other key)? ") ~~ m/:i s /;

given $pscore {
    when $_ > 21 { say "\nOver 21. Sorry, you lose" }
    when $_ == 21 { say "\n21 !!! You win." }
    default {
	repeat {
	    draw(%dealer, %deck, $dscore, 'Dealer');
	} until $pscore <= $dscore;

	say "Dealer is bust" if $dscore > 21;
	say $pscore <= $dscore <= 21 ?? "\nDealer's score >= your score. Sorry you lose." !! "\nYou win"; 
    }
};

sub draw (%hand is rw, %deck is rw, $score is rw, $name) {
    my %card = %deck.pick;
    %deck.delete(keys %card);
    %hand = %hand, %card;
    say "\n$name\'s hand is:";
    for keys %hand { .say };
    $score = [+] values %hand;
    say "Score is $score";
};

