0

So as a practice for learning perl, I decided to write a simple game of blackjack. I'm using an array for the card values. I want to be able to include jack, king and queen cards in the players card list however I also want to be able to use these cards for adding to 21. First thought I tried to use a variable however this doesn't seem to work.

The array: @cards = (1,2,3,4,5,6,7,8,9,10,$ace ='ace',$jack ='jack', $queen ='queen', $king ='king'); #NOTE: Ace is 11 or 1

    sub PrintPlayersCards
{
    $playerTotal = 0;
    print "PLAYERS CARDS:@playerCurCards\n";
    @cards[$jack] = 10;
    @cards[$queen] = 10;
    @cards[$king] = 10;
    grep {$playerTotal += $_} @playerCurCards;
    print "Your total is :$playerTotal\n";
    @cards[$king] = "King";
    @cards[$queen] = "queen";
    @cards[$jack] = "jack";
}

@playerCurCards is an array which stores the players cards. EG: 3 from the start and king from a hit etc.

7
  • $ace = 'ace' and the other similar will not translate to what you are doing. Why not instead of $ace put 'ace' or 11 ? Commented Dec 6, 2013 at 6:51
  • 2
    Also @cards[..] is incorrect, it should be $cards[..] Commented Dec 6, 2013 at 6:51
  • 2
    For each card, you have at least two pieces of information to store: the card name and its numerical value(s). That calls for something more powerful than a simple array. Maybe a hash, with card names as the hash keys, and numerical values as the hash keys. There are other options as well, but that's a place to start if you're just learning. Commented Dec 6, 2013 at 6:55
  • 1
    Read about Perl arrays perldoc.perl.org/perlintro.html#Arrays Commented Dec 6, 2013 at 6:55
  • 1
    Have you read anything at all about Perl? You seem to be just guessing what might work. Commented Dec 6, 2013 at 9:10

1 Answer 1

2

You could store it in a hash instead:

#!/usr/bin/perl

use strict;
use warnings;


my %cards = ('1'=> '1',
    '2' => '2',
    '3' => '3',
    '4' => '4',
    '5' => '5',
    '6' => '6',
    '7' => '7',
    '8' => '8',
    '9' => '9',
    '10' => '10',
    'jack' => '10',
    'king' => '10',
    'queen' => '10',
);

sub PrintPlayersCards {
    my $playerTotal = 0;
    my @hand = @_;
    print "PLAYERS CARD:\n";
    print "\t$_\n" foreach @hand;
    grep {$playerTotal += $cards{$_}} @hand;
    print "Your total is: $playerTotal\n";
}

#this is just to test it
my @playerCurCards = ('1', 'queen', 'king');
PrintPlayersCards(@playerCurCards);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.