17. BlackJack Controls

The beauty of our BlackJack Application is that there is only three ways the user can interact with the game and with so few variables we don’t have to stress that they might try and do something we have no control over. So let’s look at the code required for each of the three buttons:

private void hit_clicked () {
private void stay_clicked () {
private void start_again_clicked () {
    game = new BlackJackGame();

Quite often it’s a good idea to make the contents of your major methods very obvious and move the complexity into other methods. These buttons are the perfect example of that:

  1. When the user clicks the “hit” button we will run a method called “hitMe()” which I will show you soon.
  2. When the user clicks the “stay” button, it’s time for the dealer to have their turn so we run the “dealersTurn()” method. This will require minor changers from the one we’ve copied over from the previous tutorial.
  3. When the user clicks the “start_again” button they simply create a new instance of the BlackJackGame object and run the “startGame()” method.

This new method simply has to give the player a card, show it and check if they’ve busted. In other words:

public void hitMe() {
    if (player.busted() || (player.cardJustAdded() == 4)) {

Notice I’ve also stopped them from having more than five cards in their hand, this is just a restriction incorporated into this game, you can always alter the game to allow for more cards if you want.

You may have also noticed I created another new method that returns the index of the Card that was just added to the Hand, this is a fairly simple method you need to add to the Hand class:

public int cardJustAdded() {
    return (cardsInHand.size() - 1);

By now this type of Java code should be pretty familiar so I won’t explain it, just make sure it makes sense to you including why it’s necessary!

The “dealersTurn()” method is mostly correct but needs a couple of minor changes to suit our application:

public void dealersTurn() {
    while ((dealer.handValue() < 17) &&
           (dealer.cardJustAdded() < 4)) {

Once again, after this much Java you should be able to understand why the changes added were necessary and how it all works.

Leave a Comment

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>