Work the Shell - Recognizing Blackjacks

Win or lose, we're almost done with our shell scripted Blackjack game.

Last month, we finally wrangled the issue of Aces being worth either one or 11 by recognizing the value of what I call lazy coding—trying to solve the specific situation rather than creating an elegant and sophisticated general solution. I've since talked with some programmers and found that many don't agree with my philosophy. Indeed, one chap basically said I was completely wrong, especially if the code's to be published—as this column obviously is—and that I should always be putting in maximal effort to present exemplary, elegant solutions to any problems encountered.

But what if, I countered, that would make a program two times longer? Or four times longer? He looked at me blankly and asked, “Since when does the length of a program matter when you're trying to solve a problem or model a particular behavior?” It's a fair question, but I have to think that's where all of our code bloat comes from—where no programs can be simple, efficient and streamlined, and everything does everything else, including word processors that can send e-mail, e-mail programs that can do rudimentary page layout, text editors that can convert ASCII to HTML, Web browsers that, well, seem to include just about every feature up to and including KitchenSink.app.

And, don't get me started on the Emacs versus vi philosophy either, okay? Let's just say that an editor that can replace your OS kernel might just be a wee bit over-implemented for the vast majority of users.

The real cost of all this complexity, however, isn't the length of the code. After all, gigs of disk space are dirt cheap nowadays, and even RAM seems to be not much more than a decent meal. The cost is in the complexity itself—in the fact that large, complex systems are harder to work with, harder to debug and harder to make bulletproof than simple systems. You need but look at the challenges Microsoft is facing as it tries to ship its new Windows OS, Vista, before spring 2010.

So, what does this all have to do with shell script programming? I suggest that this discussion is pivotal to all programming tasks, actually, and that if you can't figure out a simple and manageable solution within the world of shell scripting, it might well be time to move to a more sophisticated development environment. Early on in this column, I joked about eventually rewriting the popular game Doom as a shell script, but of course, it's the complexity that would kill us, even if we might well be able to hammer our square peg into the round hole of shell scripting.

And So, Back to Vegas

Let's get back to our Blackjack game and see where we are vis-�vis complexity, length and functionality. My suspicion is that we're going to be able to wrap up this project by the end of the next column, because it's really all the mechanics that we can create as a script; the game itself is always doomed to be a primitive command-line interface, because, well, it's a shell script. Could we layer an interface with Tk or some other graphical toolkit? Sure, but then, would you really want the underlying code base to be a shell script?

Our code is now getting into the category of seriously long shell scripts, weighing in at 177 lines. That's actually beyond my usual cutoff of 150 lines maximum for a script, so we definitely need to wrap this up before it gets too much longer anyway.

The missing piece we'll deal with in this column is to test for a dealer blackjack and player blackjack situation. If you are dealt an Ace and a ten-point card (a ten or a face card) you have a blackjack. If the dealer has a blackjack, the game ends and the player loses. If the player gets a blackjack on the deal, the game ends and the dealer loses (without being able to get additional cards, because a 21-point hand that involves more than two cards does not tie a player's blackjack). If you have the extraordinary situation of both the player and dealer having a blackjack, it's a “push” or tie, just as it is in any other situation where both player and dealer have the same point value in their hands.

The key spot where we need to modify the code to test for blackjacks is where the hands are dealt, and we might as well deal both hands before adding the additional test. Here's the hand-dealing code:

player[1]=${newdeck[1]}
player[2]=${newdeck[3]}
nextplayercard=3        # player starts with two cards

dealer[1]=${newdeck[2]}
dealer[2]=${newdeck[4]}
nextdealercard=3        # dealer also has two cards

To see whether either hand is a blackjack quickly, we'll use the handValue function:

handValue ${newdeck[1]} ${newdeck[3]}

Recall that because you can't return values in functions, handValue simply sets the global variable $handvalue to the numeric value of the hand. This means the test is straightforward:

# test for dealer or player blackjack

handValue ${player[1]} ${player[2]}
playerhandvalue=$handvalue
handValue ${dealer[1]} ${dealer[2]}
dealerhandvalue=$handvalue

echo ""

if [ $playerhandvalue -eq 21 -a $dealerhandvalue -eq 21 ] ; then
  echo "Extraordinary! Both the dealer and player were dealt a blackjack!"
  echo "Unfortunately, this means you didn't win: it's a push (or tie)."
  echo ""
  exit 0
fi

if [ $dealerhandvalue -eq 21 ] ; then
  echo "Darn it! Dealer pulled a blackjack out of his hat. You lose."
  echo ""
  exit 0
elif [ $playerhandvalue -eq 21 ] ; then
  echo "NICE! You got a blackjack and won the game. Payout would be 3:2!"
  echo ""
  exit 0
fi

You can see that I simply create playerhandvalue and dealerhandvalue for these numeric tests, and then check whether both are 21, the dealer is 21 and the player is 21. That's all there is to it.

To test the new code, simply slip in either or both of the following lines right before the handValue call above:

player[1]=1 ; player[2]=11
dealer[1]=1 ; dealer[2]=12

Then you can, um, stack the deck and create the specific test situations you desire.

______________________

Dave Taylor has been hacking shell scripts for over thirty years. Really. He's the author of the popular "Wicked Cool Shell Scripts" and can be found on Twitter as @DaveTaylor and more generally at www.DaveTaylorOnline.com.

White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState