Friday, August 13, 2010

BlackJack Simulator ... with Java !

I've done something border-lining between brilliant and ultimately geeky. I'll prefer, instead, to compare it to the badass Ocean's 11 movies.
I've developed a completely object oriented API for simulating a deck of cards. There is a Deck object, which has a collection of Card objects within it. The deck has some member method operations such as draw(), which returns a Card, or shuffle(), which implements the popular Knuth Shuffle algorithm. There is also a Hand object, so that you can move cards from a deck and into a hand... This API seeks to be your utility for simulating any card game you'd like from your Java code.
If you'd like to see a JavaDoc of the API, you can see it here: http://www.freelance-webs.com/blackjack/doc/. Be warned, though, I didn't do a lot of documenting, and there are actually more objects than I'm eluding to in this blog.
So, I went on building more classes in order to use this API to simulate a BlackJack Game. I developed a configurable application to simulate an entire BlackJack game. You create a new Game object, pass in the number of decks you'd like to play (the game is over when the dealer runs out of enough cards to continue dealing), and pass in a Strategy object.
I designed a Strategy interface that you simply need to implement in order to create a decision engine for whether to hit, stand, etc. I then implemented a Strategy using the EXACT strategy shown here:
Now, there's much more to it than just this (I've probably got about 30 hours into this damn thing), but basically by creating a Game object and passing in my Strategy, I can run an entire blackJack game, simulating a player sitting down at a single deck table and flat-betting 5 dollars, of course altering his/her bet appropriately with splits, double downs, and surrenders. The player then gets up and walks away when the deck is through. The Game object returns a double primitive data type containing how much the player won or lost. If it's a negative number, then that's how much he lost.
So in one line of code you simulate all this. Now:
  • I put that one line of code in a for loop
  • Simulate this entire Game 100,000 times.
  • Average the result to find out how successful the strategy was.
Result: On average, with this strategy, at a single deck table where the dealer stands on soft 17, late surrender is allowed, flat betting $5, the player will walk away $0.20 richer. It's a positive number. It's a winning strategy.
For now, the view is all console output...


My next goal is to slap a rich web application interface on this using PrimeFaces where a user can fill out a grid like the one pictured above, click a big "simulate" button, and find out how much money their strategy wins or loses them after a 10,000 games or so.
Now I've just got to figure out how to make money off this freakin thing.