Source

Project: A game of 21

Jason Slusarchuk
Ambitions of a Recovering Salesman

--

One of my recent projects in Launch School was building a game of 21 with the Ruby programming language. Essentially this is just a stripped down version of the popular casino game, Blackjack, played by a human against the dealer (computer).

The requirements were fairly simplistic: there’s no doubling down, splitting or betting. Basically, we’re just looking for the best hand (closest or equal to 21) However, I did opt to spice things up a bit by adding support for up to 4 players (plus the dealer), allowing the user to choose how many decks to play with (up to 4) and by implementing a ‘graphical’ representation of the cards instead of a simple literal format.

21 in action!

Overall, I’m quite happy with how the program turned out. It plays well and I believe I’ve got all the major bugs ironed out. I think I’m most pleased however with how much cleaner and well planned my methods are versus the last program I wrote. As a result, the main game logic is a lot easier to follow.

For example, here is the main game logic and loop for my ‘twenty_one.rb’ program:

Pretty short and concise don’t you think? Now, compare that with the game logic from my previous assignment, a simple game of ‘tic-tac-toe’:

Even though the ‘twenty_one.rb’ program is the more sophisticated of the two in terms of number of features and gameplay complexity, the main game logic for ‘tic_tac_toe.rb’ came in at almost twice the number of lines!

I attribute the improvement to better planning with the ‘twenty_one.rb’ program. While coding up ‘tic_tac_toe.rb’ I was really just making it up as I went along, building the needed methods or flow controls as they became relevant. It seemed like a pretty simple exercise so I didn’t really spend much time reverse engineering the gameplay ahead of time. Well, even with a simple program, what a difference planning makes!

When approaching ‘twenty_one.rb’ I took the time to map out all the possible gameplay scenarios with pseudocode first. This, in turn, made it much easier to plan out my methods. By the time I got to writing out the actual flow of the game, 90% of the work was already done and I was able to simply plug in the components I needed as I went. In fact, after I finished writing the program, I had to go back and remove a few methods that were never even used.

Here’s what my pseudocode looked like:

Overall, I really enjoyed this project and learned a lot. If you have any additional feedback you’d like to offer, or improvements you’d like to suggest, please feel free to share those in the comments below.

Also, if you’d like to read through the complete source code you can find it here on GitHub:

https://github.com/farmerchuk/101-programming-foundations/blob/master/slightly_larger_programs/twenty_one.rb

--

--