Monte-Carlo Simulation: Blackjack
The main purpose of this project is to give you practice building classes in Java. To do this, we'll simulate a simple version of the card game Blackjack. The objects in a card game include: a Card, a Deck, a Hand, and Game. You'll make a class for each one, connecting them together as appropriate. We'll also start to make use of a few of the many Java library classes.
Tasks
For this assignment you will implement classes to represent a card, a hand, a deck, and the game Blackjack. The result will be a text-based version of the game that runs in the terminal. You are free to make the game more complex as an extension.
The purpose of the assignment is not to create a Blackjack game for people to play, however, but to study the properties of Blackjack, given a particular rule set, when played over many hands. You are using CS to study the properties of a system defined by a set of rules.
More information about Blackjack.
Basic Blackjack Rules
The link above contains an extensive description of the full rules of Blackjack. For this project, you are required to implement only a simplified rule set. You can implement more of the rules as part of project extensions.
There will be only two players in the game: the player and the house. In our simplified rule set, an ace is worth 11 points. In an actual game, an ace can be either 1 or 11. Play should use the following procedure.
- The player and the house should each receive two cards dealt from a deck
- The player should play their entire turn before the dealer.
- The player should calculate the value of their hand (the sum of the card values) and choose whether to take a card (hit) or stop at the current value (stand).
- If the player chooses to hit, then if the new value of their hand is greater than 21, the player loses (busts) and the game is over. If the value is less than 21, the player repeats the process until they stand or bust.
- If the player did not bust, the dealer plays.
- The dealer will continue to take a card (hit) until the value of their hand is 17 or greater.
- If the dealer busts, then the player wins.
- If player and dealer both avoided a bust, then the hand with the highest value wins the game. If both hands are of equal value, then the hand is a tie (push).
When playing Blackjack, the deck is usually not rebuilt and shuffled between each game. Instead, the deck is rebuilt and shuffled when it gets below a certain number of cards. For example, you could implement the rule that when there are fewer than 26 cards (out of 52), then the deck should be rebuilt to 52 cards and shuffled. Therefore, shuffling should not be done every game, but should be an action that is conditioned on the number of cards left in the deck. How often the deck is shuffled will affect game play because it affects the probabilities of certain cards appearing.
The Card Class
Create a java class called Card, which should hold all information unique to the card. For this assignment, it needs to hold only the value of the card, which must be in the range 2-11 (or 1 - 11 if you implement aces with optional values of 1 or 11). The Card class should have the following methods.
public Card(int v)a constructor with the value of the card, possibly doing range checking.public int getValue()return the numeric value of the card.public String toString()return a string that represents the Card object. This will override the default toString method in the Object class.
Write a main method that uses each of the class methods to demonstrate that they work.
The Hand Class
Create a java class called Hand, which should hold a set of cards. You can use an ArrayList (import java.util.ArrayList) to hold the Card objects. The class should have at least the following methods.
public Hand()initialize the ArrayList.public void reset()reset the hand to empty.public void add( Card card )add the card object to the hand.public int size()returns the number of cards in the hand.public Card getCard( int i )returns the card with index i. Cast as appropriate.public int getTotalValue()returns the sum of the values of the cards in the hand.public String toString()returns a String that has the contents of the hand presented in a nice format. Use the Card toString method (implicitly or explicitly) to accomplish this.
Write a main method that uses each of the class methods to demonstrate that they work.
The Deck Class
Create a java class called Deck, which should hold a set of cards and be able to shuffle and deal the cards. You should use an ArrayList to hold the cards. The class should support the following methods.
public Deck()builds a deck of 52 cards, 4 each of cards with values 2-9 and 11, and 16 cards with the value 10. Note, you probably want the constructor to call the build() method, below.public void build()builds a deck of 52 cards, 4 each of cards with values 2-9 and 11, and 16 cards with the value 10.public int size()returns the number of cards in the deck.public Card deal()returns the top card (position zero) and removes it from the deck.public Card pick( int i)(optional) returns the card at position i and removes it from the deck.public void shuffle()shuffles the deck. This method should put the deck in random order. One way to do it is to build a fresh second deck and then make n random picks from it, where n is the size of the deck at the time of the shuffle. Note that the first pick should be in the range [0, n-1], the second pick should be in the range [0, n-2] and so on. You may want to generate a seed for the Random object by using the functionSystem.currentTimeMillis()so that each run of a game is different. You are expected to implement the shuffle method. Please do not use Collection.shuffle().public String toString()returns a String that has the contents of the deck "written" in a nice format (so that you can see the ordering of the card values).
Write a main method that uses each of the class methods to demonstrate that they work.
The Blackjack Class
Create a class called Blackjack that implements a simple version of the card game. The class will need to have fields for a Deck, a Hand for the player, a Hand for the dealer, and a field for the number of cards below which the deck must be reshuffled. The main function for the Blackjack class should implement one complete game.
public Blackjack(int reshuffleCutoff )the constructor should store the reshuffleCutoff and set up a game. You can avoid duplicate code by calling the reset() method.public void reset()should reset the game. Both the player Hand and dealer Hand should start with no cards. If the number of cards in the deck is less than the reshuffle cutoff, then the method should create a fresh (complete), shuffled deck. Otherwise, it should not modify the deck, just clear the player and dealer hands.public void deal()should deal out two cards to both players from the Deck.public boolean playerTurn()have the player draw cards until the total value of the player's hand is equal to or above 16. The method should return false if the player goes over 21 (bust).public boolean dealerTurn()have the dealer draw cards until the total of the dealer's hand is equal to or above 17. The method should return false if the dealer goes over 21.public void setReshuffleCutoff(int cutoff)should assign the new cutoff value to the internal reshuffle cutoff field.public int getReshuffleCutoff()returns the current value of the reshuffle cutoff field.public String toString()returns a String that has represents the state of the game. It may be helpful to show the player and dealer hands as well as their current total value.
Use the main function of your Blackjack class to test the above functions. Make sure they are working properly by dealing two hands and then calling the playerTurn and dealerTurn methods, printing out the game state and making sure the rules are correctly implemented.
Create a method to play a single game.
public int game(boolean verbose)the game method should play a single game of Blackjack following the procedure outlined above. The game method should call the reset method at the start of each game. The game method should return a -1 if the dealer wins, 0 in case of a push (tie), and a 1 if the player wins.If the parameter
verboseis true, then the game method should print out the initial and final hands of the game and a statement about the result (dealer/push/player).
Update your main function so it creates a Blackjack object and then uses it to play three games with verbose being true. Make sure your game method is working correctly. Explain how you did this in your report.
Storing Game Output
Once you have completed the above four classes, generate a printout of three different games. You can send output to a file using the greater than symbol on the command line. For example, the command
java Blackjack > mygames.txt
would play a game and send it to the file mygames.txt.
Simulation
Make one more class called Simulation. This class should have only a main function that executes 1000 games of Blackjack. The code should create and re-use a single Blackjack object. It should keep track of how many games the player wins, how many the dealer wins, and many are pushes. Print out the total in the end both as raw numbers and as percentages.
Extensions
Projects are your opportunity to learn by doing. They are also an opportunity to explore and try out new things. Rather than list out every activity for a project, the defined part of each project will be about 85% of the assignment. You are free to stop there and hand in your work. If you do all of the required tasks and do them well, you will earn a B/B+.
To earn a higher grade, you can undertake one or more extensions. The difficulty and quality of the extension or extensions will determine your final grade for the assignment. Extensions are your opportunity to customize the assignment by doing something of interest to you. Each week we will suggest some things to try, but you are free to choose your own.
A common question is "how much is an extension worth?" The answer to that question depends on the extension, how well it is done, and how far you pushed it. As teachers, we prefer to see one significant extension, done well, where you explore a topic in some depth. But doing 2-3 simpler extensions is also fine, if that's what you want to do. Choose extensions that you find interesting and challenging.
The following are a few suggestions on things you can do as extensions to this assignment. You are free to choose other extensions, and we are happy to discuss ideas with you.
- Create a new method in your Blackjack class called playerTurnInteractive() that uses input from the terminal to control the player's actions. Then create a new class Interactive that lets you play Blackjack on the terminal.
- Add in more of the rules for Blackjack. For example, an Ace (value 11 in the default case above) can have the value 1 or 11, whichever is more advantageous. If you add in the Ace rule, then you will also want to take into account a real Blackjack (2 cards totaling 21) when evaluating the winning hand. A Blackjack beats a 21 with more than 2 cards. See how these rules affect the simulation results.
- Make your game use 6 decks, and reshuffle if only 1 deck is left. Play the game 1000 times, and observe how many games the player wins, how many the dealer wins, and many are pushes. Compare with using only a single deck.
- Run the simulation with different decision rules for the player and see how it affects the outcome percentages over many games (>= 1000).
- Add a type of betting strategy to the simulation and see if the player can win money even while losing more games than winning.
- Try running the simulation with different numbers of games and see how variable the results are. For example, run the simulation using M games (e.g. M = 100) and do this N times (e.g. N = 10). Then calculate the standard deviation of the results. Then you can plot the standard deviation versus the number of games (M) in the simulation to see how the results stabilize as you use a larger number of games.
- For any assignment, a good extension will be to implement a Java class yourself and demonstrate that it has the same functionality as the Java class. For example, you could implement your own ArrayList class for this assignment using basic Java arrays.
- Another good extension for any assignment is to identify in comments when dynamically allocated memory is being "lost." Dynamic memory is any memory created with a
newcommand. Indicate the line of code in which the last reference to an object referencing dynamic memory is removed.
Report
Your intended audience for your report are your peers not in the class, but who have taken a CS course. Your report should explain the core CS concept used, present the results of your program, and discuss the meaning of the results: what did you discover and does it make sense?
Your project report should contain the following elements. Please include a header for each section.
- Abstract
A brief summary of the project, in your own words. This should be no more than a few sentences. Give the reader context and identify the key purpose of the assignment. Each assignment will have both a core CS purpose--usually a new data structure--and an application such as a simulation or analysis.
Writing an effective abstract is an important skill. Consider the following questions while writing it.
- Does it describe the CS concepts of the project (e.g. writing well-organized and efficient code)?
- Does it describe the specific project application?
- Does it describe the data structure you used?
- Does it describe the results of your simulation or analysis?
- Is it concise?
- Are all of the terms well-defined?
- Does it read logically and in the proper order?
- Results
Present your results. Include text output, images, tables, graphs, or qualitative descriptions, as appropriate. Include a discussion as to whether the results make sense and what they mean. This week, be sure to present the percentages for dealer wins, player wins, and ties. Does the house always win (it should)?
- Extensions
Describe any extensions you undertook, including text output, graphs, tables, or images demonstrating those extensions. If you added any modules, functions, or other design components, note their structure and the algorithms you used.
- References/Acknowledgements
A list of people you worked with, including TAs and instructors. Include in that list anyone whose code you may have seen, such as those of friends who have taken the course in a previous semester.
Handin
Here's a checklist of everything you should do when you are finished with a project and are ready to turn it in. Go ahead and follow these steps to turn in your code from today.
+ Create a report and export to pdf
- Create a report in your favorite text editor. For this lab, include a document with your name in it.
- Print to PDF (Windows)
- Open a file in a Windows application.
- Choose "File > Print".
- Choose "Adobe PDF" as the printer in the Print dialog box.
- Click Print. Type a name for your file, and click Save.
- Print to PDF (Mac OS)
- Open a file in a Mac OS application.
- Click the "PDF" button and choose "Save As Adobe PDF".
- Choose the "Adobe PDF Settings" and click "Continue".
- Type a name for your file, and click "Save".
- Export to PDF Google Drive
- Choose "File" > "Download" > "PDF Document (.pdf)"
+ Prepare your project folder
- In Finder, move your lab folder inside your project folder. For example, if you have
Lab01andproject_01folders both on your Desktop, drag theLab01folder insideproject_01.
+ Submit your project on Google Drive
- On Google Drive, locate the folder named with your Colby username that was shared with you earlier.
- Upload the relevant files into the matching project folder. you can ‘drag and drop’ the files into the project folder on Drive. (".class" files are not relevant)
- Note that once the files are copied, Google drive records submission time and any changes made. No further changes are allowed unless you want to make another submission.
Spring 2021