I haven't coded in a while, so I did this small exercise to refresh my programming skills and to have some fun:
#!/usr/bin/env perl use 5.014; use warnings; use autodie; use charnames ':full'; use List::Util 'shuffle'; use Getopt::Long; use Pod::Usage; GetOptions( "h|?|help" => \( my $help ), "hands=i" => \( my $hands ), "cards=i" => \( my $cards ), ) or pod2usage(1); pod2usage( -exitval => 0, -verbose => 2, -noperldoc => 1 ) if $help; deal(deck(), $cards, $hands); sub deck { my $n_cards = 52; my @suit = ( "\N{BLACK HEART SUIT}", "\N{BLACK SPADE SUIT}", "\N{BLACK DIAMOND SUIT}", "\N{BLACK CLUB SUIT}", ); my @rank = ((2 .. 10), qw(J Q K A)); my @deck; my $i = 0; while (@deck < $n_cards) { for my $s (@suit) { for my $r (@rank) { $deck[$i++] = "$r$s"; } } } return \@deck; } sub deal { my $deck = shift; my $n_cards = shift // 5; my $hands = shift // 1; my @shuffled = shuffle(@$deck); binmode STDOUT, ':utf8'; for (1 .. $hands) { my @hand; for (1 .. $n_cards) { die "no more cards in deck ...\n" unless @shuffled; push @hand, shift @shuffled; } say(join " ", @hand); } } __END__ =head1 NAME cards - deal cards from deck of 52 cards =head1 SYNOPSIS cards [options] options: -h, -?, --help brief help message --hands N number of hands to deal [1] --cards N cards per hand [5] =cut
The script is to be seen on GitHub too.
It looks to me it might benefit from OOP, something like:
deck->new(cards => 52); deck->shuffle(); deck->deal(cards => 5, hands => 4);
I have little experience with OOP, so if you have some hints how to get started, just let me know.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Let's play poker
by Eily (Monsignor) on Jun 09, 2016 at 09:53 UTC | |
by reisinge (Hermit) on Jun 09, 2016 at 12:50 UTC | |
|
Re: Let's play poker
by stevieb (Canon) on Jun 09, 2016 at 22:55 UTC |