1. Computer problem? Tech Support Guy is completely free -- paid for by advertisers and donations. Click here to join today! If you're new to Tech Support Guy, we highly recommend that you visit our Guide for New Members.

Solved: Blackjack - Java 5.0

Discussion in 'Software Development' started by sportscrazy, Jan 25, 2007.

Thread Status:
Not open for further replies.
Advertisement
  1. sportscrazy

    sportscrazy Thread Starter

    Joined:
    Nov 27, 2004
    Messages:
    398
    Hello everyone, I was recently coding a project for my computer science class. I decided to make a blackjack applet. It relied on 2 background class files (deck.class, and card.class), the applets works great but the only problem I'm having is making the aces have 2 values, one and ten and if they go over 21 it should be 1. The code below is the main java file, if you need the other 2 or want to look at the entire thing there is a self-extracting archive available.

    Code:
    /*
     * A U T H O R
     * Ralph Gill
     * [email protected]
     *
     * P U R P O S E
     * Create the game of blackjack using widgets and panels.
     *
     * C R E D I T S
     *
     * E X T R A S
     */
    
    import java.io.*;
    import java.awt.*;
    import javax.swing.*;
    import java.applet.*;
    import java.awt.event.*;
    
    public class Blackjack extends Applet implements ActionListener
    {
        /******************************************************* Global Variables */
        deck d = new deck ();
        int x = 0;
    
        //Textfield to get user's bet
        JTextField userBet = new JTextField (5);
    
        //Setup dealing variables
        card hand2[] = new card [8];
        card hand[] = new card [8];
        int count = 0;
        int count2 = 0;
    
        //Create comment for game
        JLabel gamecomment = new JLabel ("--------- Blackjack ---------");
    
        //Labels for cards
        JLabel dealerHand[] = new JLabel [8];
        JLabel userHand[] = new JLabel [8];
    
        //Setup card panels
        Panel dealerCard = new Panel (new GridLayout (1, 8, 4, 2));
        Panel userCard = new Panel (new GridLayout (1, 8, 4, 2));
    
        //User's bank money
        int userBank = 500;
        JLabel bank = new JLabel ("Your Bank: $" + userBank);
    
        //Card value variables
        int cardSum = 0;
        int cardSum2 = 0;
    
        //Labels to display card total
        JLabel userTotal = new JLabel ("You hold 000000");
        JLabel dealerTotal = new JLabel ("Dealer shows 000000");
    
        //Create buttons
        JButton deal = new JButton ("Deal");
        JButton hit = new JButton ("Hit");
        JButton stand = new JButton ("Stand");
        JButton newGame = new JButton ("Reset Cards");
        JButton resetBank = new JButton ("Reset Bankroll");
    
        /************************************************************ Init Method */
        public void init ()
        {
            //Pre: None
            //Post: Sets up widgets required in the game
        
            //Set windows
            setBackground (new Color (0, 99, 0));
            resize (490, 365);
        
            //Shuffle deck
            d.shuffle ();
        
            //Set-up panels
            Panel blank = new Panel (new GridLayout (1, 1));
            Panel dealerComment = new Panel (new GridLayout (1, 3));
            Panel gameComment = new Panel (new GridLayout (1, 1));
            Panel userComment = new Panel (new GridLayout (1, 1));
            Panel buttons = new Panel (new GridLayout (1, 6));
            Panel reset = new Panel (new GridLayout (1, 1));
            Panel resetMoney = new Panel (new GridLayout(1, 1));
        
            //Show blanks at users' hand
            for (int i = 0 ; i < 8 ; i++)
            {
                //User cards
                hand [i] = new card ();
                userHand [i] = new JLabel (createImageIcon ("pics\\blank.jpg"));
                userCard.add (userHand [i]);
        
                //Dealer cards
                hand2 [i] = new card ();
                dealerHand [i] = new JLabel (createImageIcon ("pics\\blank.jpg"));
                dealerCard.add (dealerHand [i]);
            }
        
            //Set color of panels
            blank.setBackground (new Color (0, 99, 0));
            dealerCard.setBackground (new Color (0, 99, 0));
            dealerComment.setBackground (new Color (0, 99, 0));
            gameComment.setBackground (new Color (0, 99, 0));
            userCard.setBackground (new Color (0, 99, 0));
            buttons.setBackground (Color.black);
        
            bank.setForeground (Color.black);
        
            //Modify game comment section
            gamecomment.setFont (new Font ("Comic Sans MS", Font.BOLD, 26));
            gamecomment.setForeground (new Color (214, 240, 23));
        
            JLabel wager = new JLabel ("  Wager: ");
            wager.setForeground (new Color (214, 240, 23));
            wager.setFont (new Font ("Comic Sans MS", Font.BOLD, 12));
        
            //Filler text
            JLabel filler = new JLabel ("fillerfillerfillerfillerfiller");
            filler.setForeground (new Color (0, 99, 0));
            JLabel filler2 = new JLabel ("fillerfillerfillerfillerfiller");
            filler2.setForeground (new Color (0, 99, 0));
            filler2.setFont (new Font ("Comic Sans MS", Font.BOLD, 16));
        
            //Show user their stats
            userComment.add (userTotal);
            userComment.add (filler);
            userComment.add (bank);
        
            //Credits link
            JLabel credit = new JLabel ("Created by The Gill");
            credit.setFont (new Font ("Times New Roman", Font.PLAIN, 12));
            credit.setForeground (Color.black);
        
            //Set color for card totals
            userTotal.setForeground (new Color (214, 240, 23));
            userTotal.setFont (new Font ("Comic Sans MS", Font.PLAIN, 12));
            dealerTotal.setForeground (new Color (214, 240, 23));
            dealerTotal.setFont (new Font ("Comic Sans MS", Font.PLAIN, 12));
        
            //Add credit to top
            blank.add (credit);
        
            //Add action listeners to buttons
            deal.setBackground (Color.black);
            deal.setForeground (Color.white);
            deal.setActionCommand ("1");
            deal.addActionListener (this);
        
            hit.setBackground (Color.black);
            hit.setForeground (Color.white);
            hit.setActionCommand ("2");
            hit.addActionListener (this);
        
            stand.setBackground (Color.black);
            stand.setForeground (Color.white);
            stand.setActionCommand ("3");
            stand.addActionListener (this);
        
            newGame.setBackground (Color.black);
            newGame.setForeground (Color.white);
            newGame.setActionCommand ("4");
            newGame.addActionListener (this);
            
            resetBank.setBackground (Color.black);
            resetBank.setForeground (Color.white);
            resetBank.setActionCommand ("5");
            resetBank.addActionListener (this);
        
            //Add all inputs to buttons panel
            buttons.add (deal);
            buttons.add (hit);
            buttons.add (stand);
            buttons.add (wager);
            buttons.add (userBet);
            reset.add (newGame);
            resetMoney.add (resetBank);
        
            //Add dealerTotal to panel
            dealerComment.add (dealerTotal);
            dealerComment.add (filler2);
        
            //Add gamecomment to panel
            gameComment.add (gamecomment);
        
            //Add everything to screen
            add (blank);
            add (dealerCard);
            add (dealerComment);
            add (gameComment);
            add (userCard);
            add (userComment);
            add (buttons);
            add (reset);
            add (resetMoney);
        
            //Disable buttons
            hit.setEnabled (false);
            deal.setEnabled (false);
            stand.setEnabled (false);
            newGame.setEnabled (true);
            userBet.setEnabled (false);
            resetBank.setEnabled (false);
        }
    
    
        /************************************************ Action Performed Method */
        public void actionPerformed (ActionEvent e)
        {
            /******************************************************** Deal Button */
            if (e.getActionCommand ().equals ("1"))
            {            
                try
                {
                    //Enable/disable buttons
                    deal.setEnabled (false);
                    hit.setEnabled (true);
                    stand.setEnabled (true);
                    userBet.setEnabled (false);
                    
                    //Get user's bet
                    x = Integer.parseInt (userBet.getText ());
                    
                    //When user is bankrupt
                    if(userBank <= 0)
                    {
                        JOptionPane.showMessageDialog (null, "You're bankrupt!",
                        "Bank", JOptionPane.WARNING_MESSAGE);
                        
                        //Disable buttons
                        hit.setEnabled (false);
                        deal.setEnabled (false);
                        stand.setEnabled (false);
                        newGame.setEnabled (false);
                        userBet.setEnabled (false);
                        resetBank.setEnabled (true);
                    }
                    
                    //If user over bets
                    else if(x > userBank)
                    {
                        JOptionPane.showMessageDialog (null, "You don't have that much money!",
                        "Betting", JOptionPane.WARNING_MESSAGE);
                        
                        reset();
                        
                        //Disable buttons
                        hit.setEnabled (false);
                        deal.setEnabled (false);
                        stand.setEnabled (false);
                        newGame.setEnabled (true);
                        userBet.setEnabled (false);
                    }
                    
                    //Deal cards to user
                    hand [count] = d.dealOne ();
                    cardSum += hand [count].value;
                    count++;
                    
                    hand [count] = d.dealOne ();
                    cardSum += hand [count].value;
                    count++;
                    
                    //Deal cards to dealer
                    hand2 [count2] = d.dealOne ();
                    count2++;
                    hand2 [count2] = d.dealOne ();
                    cardSum2 += hand2 [count2].value;
                    count2++;
            
                    //Update the table cards
                    update ();
            
                    //Show card total
                    userTotal.setText ("You hold " + cardSum);
                    dealerTotal.setText ("Dealer shows " + cardSum2);
                }
                
                catch(NumberFormatException m)
                {
                    JOptionPane.showMessageDialog (null, "Please enter a bet!",
                    "Betting", JOptionPane.WARNING_MESSAGE);
                    
                    hit.setEnabled (false);
                    deal.setEnabled (true);
                    stand.setEnabled (false);
                    newGame.setEnabled (false);
                    userBet.setEnabled (true);
                    resetBank.setEnabled (false);
                }
            }
    
            /********************************************************* Hit Button */
            else if (e.getActionCommand ().equals ("2"))
            {
                //Hit user with single card
                hand [count] = d.dealOne ();
                cardSum += hand [count].value;
                count++;
            
                //If user busts
                if (cardSum > 21)
                {
                    gamecomment.setText ("--------- Bust! ---------");
                    deal.setEnabled (false);
                    hit.setEnabled (false);
                    stand.setEnabled (false);
                    newGame.setEnabled (true);
                    userBank -= x;
                }
                
                //Show card total
                userTotal.setText ("You hold " + cardSum);
            
                //Update text for bank
                bank.setText ("Your Bank: $" + userBank);
            
                //Update table cards
                update ();
            }
        
            /******************************************************* Stand Button */
            else if (e.getActionCommand ().equals ("3"))
            {
                //Set enabled/disabled buttons
                deal.setEnabled (true);
                hit.setEnabled (false);
                stand.setEnabled (false);
                
                cardSum2 += hand2 [0].value;
                dealerHand [0].setIcon (createImageIcon (hand2 [0].picture));
            
                //Dealer hits if under 17
                while (cardSum2 < 18)
                {
                    hand2 [count2] = d.dealOne ();
                    cardSum2 += hand2 [count2].value;
                    count2++;
                }
                update ();
                
                //Show card total
                userTotal.setText ("You hold " + cardSum);
                dealerTotal.setText ("Dealer shows " + cardSum2);
                
                //If user busts
                if (cardSum > 21)
                {
                    gamecomment.setText ("--------- Bust! ---------");
                    userBank -= x;
                }
            
                //Evaluate cards, declare winner
                if (cardSum <= 21 && cardSum2 <= 21 && cardSum > cardSum2)
                {
                    gamecomment.setText ("-------- You Win! --------");
                    userBank += x;
                }
            
                else if (cardSum <= 21 && cardSum2 <= 21 && cardSum < cardSum2)
                {
                    gamecomment.setText ("-------- You Lose! --------");
                    userBank -= x;
                }
            
                else if (cardSum == cardSum2)
                    gamecomment.setText ("-------- Tie Game --------");
            
                else if (cardSum2 > 21)
                {
                    gamecomment.setText ("------- Dealer Bust -------");
                    userBank += x;
                }
            
                else
                    gamecomment.setText ("--------- Error! ---------");
            
                //Update text for bank
                bank.setText ("Your Bank: $" + userBank);
            
                //Buttons manage
                deal.setEnabled (false);
                hit.setEnabled (false);
                stand.setEnabled (false);
                newGame.setEnabled (true);           
            }
        
            /************************************************* Reset Cards Method */
            else if (e.getActionCommand ().equals ("4"))
            {
                reset();
            }
            
            /******************************************************** Reset Money */
            else if (e.getActionCommand ().equals ("5"))
            {
                //Reset users' money
                userBank = 500;
                bank.setText ("Your Bank: $" + userBank);
                
                //Enable gameplay
                hit.setEnabled (false);
                deal.setEnabled (false);
                stand.setEnabled (false);
                newGame.setEnabled (true);
                userBet.setEnabled (false);
                resetBank.setEnabled (false);
            }
        }
    
    
        /********************************************************** Update Method */
        public void update ()
        {
            for (int i = 0 ; i < count ; i++)
            {
                userHand [i].setIcon (createImageIcon (hand [i].picture));
            }
        
            for (int i = 1 ; i < count2 ; i++)
            {
                dealerHand [i].setIcon (createImageIcon (hand2 [i].picture));
            }
        }
        
        /*********************************************************** Reset Method */
        public void reset()
        {
            //Reset everything
            deal.setEnabled (true);
            hit.setEnabled (false);
            stand.setEnabled (false);
            userBet.setEnabled (true);
            
            //Shuffle deck
            d.shuffle ();
                
            //Reset variables
            count = 0;
            count2 = 0;
            cardSum = 0;
            cardSum2 = 0;
                
            //Set game text
            gamecomment.setText ("--------- Blackjack ---------");
            
            //Reset cards
            card hand2[] = new card [8];
            card hand[] = new card [8];
                
            //Reset card total
            userTotal.setText ("You hold 000000");
            dealerTotal.setText ("Dealer shows 000000");
                
            //Disable new game button
            newGame.setEnabled (false);
                
            //Show blanks at users' hand
            for (int i = 0 ; i < 8 ; i++)
            {
                //User cards
                hand [i] = new card ();
                userHand [i].setIcon (createImageIcon ("pics\\blank.jpg"));
                userCard.add (userHand [i]);
                    
                //Dealer cards
                hand2 [i] = new card ();
                dealerHand [i].setIcon (createImageIcon ("pics\\blank.jpg"));
                dealerCard.add (dealerHand [i]);
            }
        }
        
        /************************************************* Create Pictures Method */
        protected ImageIcon createImageIcon (String path)
        {
            java.net.URL imgURL = Blackjack.class.getResource (path);
            if (imgURL != null)
            {
                return new ImageIcon (imgURL);
            }
            else
            {
                System.err.println ("Couldn't find file: " + path);
                return null;
            }
        }
    }
    
    Any help is appreciated!

    Thanks in advance,
    Sports :D
     
  2. sportscrazy

    sportscrazy Thread Starter

    Joined:
    Nov 27, 2004
    Messages:
    398
    Not too many java programmers I guess...
     
  3. Chicon

    Chicon

    Joined:
    Jul 29, 2004
    Messages:
    6,650
    Hi sportscrazy,

    There's no miracle here, you have to build a method that reflects all the possibilities of cards summation, knowing that there are only 4 aces in a card games and the acceptable values for :
    - 1 ace are 1 or 10,
    - 2 aces are 2, 11 or 20,
    - 3 aces are 3, 12, 21,
    - 4 aces are 4, 13

    I would put those values in a 2-dimensionnal arrays of integers this way :

    int[][] sumAces = new int[4][3];
    sumAces[0,0] = 1;
    sumAces[0,1] = 11;
    sumAces[0,2] = whatever out of range value, ex: 99 ;
    sumAces[1,0] = 2;
    sumAces[1,1] = 11;
    sumAces[1,2] = 20;
    sumAces[2,0] = 3;
    sumAces[2,1] = 12;
    sumAces[2,2] = 21;
    sumAces[3,0] = 4;
    sumAces[3,1] = 13;
    sumAces[3,2] = 99 (see above);

    Then, each time the user is picking a card and has already ace(s) in his game, use the method to compute the sum of his cards, check according to the number of picked aces :
    - if the player is out of range;
    - if the player reaches 21;
    - if the player is stable to pick a card.

    Example :

    Code:
    [SIZE=2]
    // the passed parameters :
    // na = number of aces already picked by the player;
    // snac = sum of the non aces cards picked by the player; 
    
    private int checkAces(int na, int snac) {
       for (int i = 0; i < 3; i++) {
          int sum = snac + sumAces[(na-1), i];
          if (sum < 22) return sum; // return as soon an acceptable value is reached
       }
       return 99;  // otherwise the sum is out of range
    }
    [/SIZE]
     
  4. sportscrazy

    sportscrazy Thread Starter

    Joined:
    Nov 27, 2004
    Messages:
    398
    Thank you, Chicon for your help. I will go try that out! :D
     
  5. Squashman

    Squashman Trusted Advisor

    Joined:
    Apr 4, 2003
    Messages:
    19,786
    Can we play.
     
  6. sportscrazy

    sportscrazy Thread Starter

    Joined:
    Nov 27, 2004
    Messages:
    398
  7. WhiteHat.exe

    WhiteHat.exe

    Joined:
    Nov 4, 2005
    Messages:
    35
    Great work, SportsCrazy! As a fellow programmer, I know how frustrating the whole process can be. Kudos! Can't say I dont admire you!
     
  8. sportscrazy

    sportscrazy Thread Starter

    Joined:
    Nov 27, 2004
    Messages:
    398
    Hehe, well....:eek: Thank You! :D
     
  9. Sponsor

As Seen On
As Seen On...

Welcome to Tech Support Guy!

Are you looking for the solution to your computer problem? Join our site today to ask your question. This site is completely free -- paid for by advertisers and donations.

If you're not already familiar with forums, watch our Welcome Guide to get started.

Join over 733,556 other people just like you!

Thread Status:
Not open for further replies.

Short URL to this thread: https://techguy.org/538400

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice