Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Let's play poker

by reisinge (Hermit)
on Jun 09, 2016 at 07:50 UTC ( [id://1165207]=CUFP: print w/replies, xml ) Need Help??

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.

There is not such thing as best practice unless you specify the context. -- brian d foy

Replies are listed 'Best First'.
Re: Let's play poker
by Eily (Monsignor) on Jun 09, 2016 at 09:53 UTC

    Your code is already nearly ready for objects. The "secret" to perl's basic OOP is that the function bless will tell perl that any function call using the syntax $object->method(arg1, arg2...) must be replaced by Package::method($object, arg1, arg2);, where Package can be seen as the type of the object (called class), and is the second argument to bless. Actually if perl can't find the function in the Package/class of the object, it can search in other "parent" classes, but you don't need that here.

    When you are creating your first object, you don't have one to call $object->method(), so instead of using the syntax $object->new() you can write my $object = Package->new(), where the string "Package" is the first argument to the call, so that you can use it with bless.

    You start with a package declaration:
    package Deck; # at the top of the file
    Then your sub deck already works well to create one, so to turn it into new, you have to rename it (obviously), fetch the package name in the arguments, and bless the reference (make it an object of type/class "Deck"):

    my $class = shift; # at the top of the function return bless \@deck, $class; # at the bottom
    Now you can create your deck with my $deck = Deck->new();

    I told you that $object->method(args...) is turned into method($object, args). So your function deal can already be used in an OO way, simply turn deal($deck, $cards, $hands); into $deck->($cards, $hands);

    Now List::Util::shuffle(list) works on a list, not a reference to an array, so a little modification is required since $deck->shuffle() will be turned into shuffle($deck);. Below is one way you could write that. I have written it so that list context (eg: @shuffled = $deck->shuffle()) will return a new list and leave $deck as is, but scalar or void context (eg: ; $deck->shuffle();) will shuffle $deck itself.

    use List::util; # use the module but do not import shuffle # ... sub shuffle { my $deck = shift; my $out = wantarray ? [] : $deck; @$out = List::Util::shuffle(@$deck); return wantarray ? @$out : $out; }
    Note that since the deck itself is returned in scalar context, you can call other methods on it. So $deck->shuffle()->deal($hands, $cards); would work. Or even Deck->new()->shuffle()->deal(); (Though right now this is a bit useless because shuffle is called again in deal).

    Edit: for writing code like $object->(ARG1 => value, ARG2 => value); you can start your function with my ($obj, %params) = @_; and use $params{ARG1} and $params{ARG2};

    Edit2: s/the secret to \KOOP/perl's basic OOP/

      Eily, that's a cool hint :-)! Here goes the OOP version (2 files - the module and the script):

      # Deck.pm package Deck; use 5.014; use warnings; use charnames ':full'; use List::Util; sub new { my $class = shift; 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 bless \@deck, $class; } sub shuffle { my $deck = shift; # list context (eg: @shuffled = $deck->shuffle()) will return a n +ew list # and leave $deck as is, but scalar or void context (eg: ; # $deck->shuffle();) will shuffle $deck itself my $out = wantarray ? [] : $deck; @$out = List::Util::shuffle(@$deck); return wantarray ? @$out : $out; } sub deal { my $deck = shift; my $args = shift; my $n_cards = $args->{cards} // 5; my $hands = $args->{hands} // 1; for (1 .. $hands) { my @hand; for (1 .. $n_cards) { die "no more cards in deck ...\n" unless @$deck; push @hand, shift @$deck; } binmode STDOUT, ':utf8'; say(join " ", @hand); } } 1; # ocards use 5.014; use warnings; use Deck; 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; my $deck = Deck->new(); $deck->shuffle(); $deck->deal({cards => $cards, hands => $hands}); __END__ =head1 NAME ocards - deal cards from deck of 52 cards (OOP version of cards) =head1 SYNOPSIS ocards [options] options: -h, -?, --help brief help message --hands N number of hands to deal [1] --cards N cards per hand [5] =cut

      EDIT: Fixed my $hands = $args->{hands} instead of my $hands = $args->{cards}. Eily has sharp eyes, huh ... ;-)

      The best optimization strategy is to steal from what smarter people have already done. -- brian d foy
Re: Let's play poker
by stevieb (Canon) on Jun 09, 2016 at 22:55 UTC

    Nice post, ++

    I, too, wrote a card game (war) a few years ago after a short stretch of not coding that was part of a 'how to perl references' series, to get back in the game. My coding style has changed quite a bit since then and I now use github for my code store, but I digress.

    Notice how we took nearly the exact same approach (but reverse) to compile the deck :)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: CUFP [id://1165207]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (5)
As of 2024-04-23 06:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found