Page 2 of 2 First 12
  • Jump to page:
    #16
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    31
    Rep Power
    2
    Ok I tried various methods and I got nothing.

    So I decided to change my GUI into a JFrame, and majority of my code. I still need some help in displaying pictures in the correct position and actually calling the correct pictures to display with the correct card.

    Here's my new code:
    Code:
    package project4;
    
     /* Ronald U. 
      * CMPSCI182 - Project 4: Card Game
      * April 25, 2013
      * In this applet, the user plays a game of Blackjack.  The
      * computer acts as the dealer.  The user plays by clicking
      * "Hit!" and "Stand!" buttons.    
     */
    
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    
    public class Project4 extends JFrame implements ActionListener {
    
      private static int winxpos=0,winypos=0;      // place window here
    
    
      private JButton exitButton, newButton, hitButton, standButton;
      private CardList theDeck = null;
      private JPanel northPanel;
      private MyPanel centerPanel;
      private static JFrame myFrame = null;
      private boolean gameInProgress;
      private CardList playerHand;
      private CardList dealerHand;
      private int playerscore = 0, dealerscore = 0;
      private Font smallFont, bigFont;
      private int numberofCards, handCards;
      private String message;
      private Card hit;
    
      ////////////              MAIN      ////////////////////////
      public static void main(String[] args) {
         Project4 tpo = new Project4();
      }
    
      ////////////            CONSTRUCTOR   /////////////////////
      public Project4 ()
      {
            myFrame = this;                 // need a static variable reference to a JFrame object
            northPanel = new JPanel();
            setBackground( new Color(130,50,40) );
            northPanel.setBackground( new Color(220,200,180) );
            getContentPane().add(northPanel, BorderLayout.NORTH);
            setBackground( new Color(0,120,0) );
            //shuffleButton = new JButton("Shuffle");
            //northPanel.add(shuffleButton);
            //shuffleButton.addActionListener(this);
            newButton = new JButton("New Game");
            northPanel.add(newButton);
            newButton.addActionListener(this);
            
            hitButton = new JButton("Hit!");
            northPanel.add(hitButton);
            hitButton.addActionListener(this);
            
            standButton = new JButton("Stand");
            northPanel.add(standButton);
            standButton.addActionListener(this);
            
            exitButton = new JButton("Exit");
            northPanel.add(exitButton);
            exitButton.addActionListener(this);
            getContentPane().add("North",northPanel);
    
            centerPanel = new MyPanel();
            getContentPane().add("Center",centerPanel);
            
            doNewGame();
            
    
            setSize(800,700);
            setLocation(winxpos,winypos);
    
            setVisible(true);
       }
      
      
      public CardList getDeck(){
          return theDeck;
      }
      
      public CardList getPlayerHand(){
          return playerHand;
      }
      
      public CardList getDealerHand(){
          return dealerHand;
      }
    
      ////////////   BUTTON CLICKS ///////////////////////////
      public void actionPerformed(ActionEvent e) {
    
          if (e.getSource()== exitButton) {
            dispose(); 
            System.exit(0);
          }
          
          if (e.getSource()== newButton) {
            doNewGame();
          }
          
          if (e.getSource() == hitButton){
              doHit();
          }
          if (e.getSource() == standButton){
              doStand();
          }
      }
      
      void doNewGame(){
          theDeck = new CardList(52);
          playerHand = new CardList(0);
          dealerHand = new CardList(0);
          hit = theDeck.deleteCard(0);
          playerscore = 0;
          dealerscore = 0;
          handCards = 0;
          theDeck.shuffle();
          playerHand.insertCard(hit);
          playerHand.insertCard(hit);
          dealerHand.insertCard(hit);
          dealerHand.insertCard(hit);
          if (dealerscore == 21){
              message = "Sorry, you lose. Dealer has Blackjack.";
              gameInProgress = false;
          }
          else if (playerscore == 21){
              message = "You win! You have Blackjack.";
              gameInProgress = false;
          }
          else {
              message = "You have " + playerscore + ". Hit or Stand?";
              gameInProgress = true;
          }
          repaint();
      }
      
      void doHit(){
          hit = theDeck.deleteCard(0);
            if (gameInProgress == false){
              message ="Click \"New Game\" to start a new game.";
              repaint();
              return;
          }
          playerHand.insertCard(hit);
          numberofCards--;
          handCards++;
          playerscore = playerscore + hit.CardValue();
          if (playerscore > 21){
              message = "You've busted! Sorry, you lose.";
              gameInProgress = false;
          }
          else {
              message = "You have " + playerscore + ". Hit or Stand?";
          }
          repaint();
      
      }
      
      void doStand(){
          if (gameInProgress == false){
              message = "Click \"New Game\" to start a new game.";
              repaint();
              return;
          }
          gameInProgress = false;
            while (dealerscore <= 16 ){
                hit = theDeck.deleteCard(0);
                dealerHand.insertCard(hit);
                dealerscore = dealerscore + hit.CardValue();
                numberofCards--;
                handCards++;
            if (dealerscore > 21){
                message = "You win! Dealer has busted with " + dealerscore + ".";
            }
            else if (dealerscore > playerscore){
                message = "Sorry, you lose, " + dealerscore + " to "
                        + playerscore;
            }
            else if (dealerscore == playerscore){
                message = "Sorry, you lose. Dealer wins on a tie.";
            }
            else {
                message = "You win, " + playerscore + " to "
                        + dealerscore;
            }
        }
        repaint();
      }
    
    
    // This routine will load an image into memory
    //
    public static Image load_picture(String fname)
    {
            // Create a MediaTracker to inform us when the image has
            // been completely loaded.
            Image image;
            MediaTracker tracker = new MediaTracker(myFrame);
    
    
            // getImage() returns immediately.  The image is not
            // actually loaded until it is first used.  We use a
            // MediaTracker to make sure the image is loaded
            // before we try to display it.
    
            image = myFrame.getToolkit().getImage(fname);
    
            // Add the image to the MediaTracker so that we can wait
            // for it.
            tracker.addImage(image, 0);
            try { tracker.waitForID(0); }
            catch ( InterruptedException e) { System.err.println(e); }
    
            if (tracker.isErrorID(0)) { image=null;}
            return image;
    }
    // --------------   end of load_picture ---------------------------
    
    class MyPanel extends JPanel {
    
     ////////////    PAINT   ////////////////////////////////
      public void paintComponent (Graphics g) {
        //
        Card currentPlayerHand = playerHand.getFirstCard();
        Card currentDealerHand = dealerHand.getFirstCard();
        Image tempPlayerImage = currentPlayerHand.getCardImage();
        Image tempDealerImage = currentDealerHand.getCardImage();
        
        super.paintComponent(g);
        g.setFont(bigFont);
        g.setColor(Color.green);
        g.drawString(message, 10, getSize().height - 10);
        g.drawString("Dealer's Cards: ", 10, 23);
        g.drawString("Your Cards: ", 10, 153);
        int xpos = 25, ypos = 5;
        if (gameInProgress){
            drawCard(g, null, 10, 30);
        }
        else {
            drawCard(g, currentDealerHand.getNextCard(), 10, 30);
        }
    //    if (theDeck == null) return;
    //    Card current = theDeck.getFirstCard();
    //    while (current!=null) {
    //       Image tempimage = current.getCardImage();
    //       g.drawImage(tempimage, xpos, ypos, this);
    //       // note: tempimage member variable must be set BEFORE paint is called
    //       xpos += 80;
    //       if (xpos > 700) {
    //          xpos = 25; ypos += 105;
    //       }
    //       current = current.getNextCard();
    //    } //while
      }
    }
        void drawCard(Graphics g, Card card, int x, int y){
            
            if (card == null){
                g.setColor(Color.blue);
                    g.fillRect(x,y,80,100);
                    g.setColor(Color.white);
                    g.drawRect(x+3,y+3,73,93);
                    g.drawRect(x+4,y+4,71,91);
                
            }
            else {
               g.setColor(Color.white);
                    g.fillRect(x,y,80,100);
                    g.setColor(Color.gray);
                    g.drawRect(x,y,79,99);
                    g.drawRect(x+1,y+1,77,97);
                    
            }
            
        }
    
    }    // End Of class Project4
    
    /*****************************************************************
       Class Link, the base class for a link list of playing cards
       May be placed in a file named Link.java
    
    ******************************************************************/
    class Link {
      protected Link next;
    
      public Link getNext() { return next; }
      public void setNext(Link newnext) { next = newnext; }
    
    }  // end class Link
    
    /*****************************************************************
       Class Card, the derived class each card is one object of type Card
       May be placed in a file named Card.java
    ******************************************************************/
    
    class Card extends Link {
      private Image cardimage;
      private int value;
    
      public Card (int cardnum) {
        value = cardnum;
        cardimage = Project4.load_picture("images/gbCard" + cardnum + ".gif");
        // code ASSUMES there is an images sub-dir in your project folder
        if (cardimage == null) {
          System.out.println("Error - image failed to load: images/gbCard" + cardnum + ".gif");
          System.exit(-1);
        }
      }
      public String getValueAsString(){
          switch (value) {
                case 1:
                    return "Ace";
                case 2:
                    return "2";
                case 3:
                    return "3";
                case 4:
                    return "4";
                case 5:
                    return "5";
                case 6:
                    return "6";
                case 7:
                    return "7";
                case 8:
                    return "8";
                case 9:
                    return "9";
                case 10:
                    return "10";
                case 11:
                    return "Jack";
                case 12:
                    return "Queen";
                case 13:
                    return "King";
                default:
                    return "??";
            }
        }
      
     
      public int CardValue() {
            if (cardimage == Project4.load_picture("images/gbCard" + 0 + ".gif") || cardimage == Project4.load_picture("images/gbCard" + 13 + ".gif") || cardimage == Project4.load_picture("images/gbCard" + 26 + ".gif") || cardimage == Project4.load_picture("images/gbCard" + 39 + ".gif")) {
                Object[] possibleChoices = {"1", "11"};
                Object selectedChoice = JOptionPane.showInputDialog(null, "1 or 11?", "You drew an Ace, pick a value", JOptionPane.INFORMATION_MESSAGE, null, possibleChoices, possibleChoices[0]);
                if (selectedChoice == possibleChoices[0]) {
                    return 1;
                } else {
                    return 11;
                }
            } else if (cardimage == Project4.load_picture("images/gbCard" + 1 + ".gif") || cardimage == Project4.load_picture("images/gbCard" + 14 + ".gif") || cardimage == Project4.load_picture("images/gbCard" + 27 + ".gif") || cardimage == Project4.load_picture("images/gbCard" + 40 + ".gif")) {
                return 2;
            } else if (cardimage == Project4.load_picture("images/gbCard" + 2 + ".gif") || cardimage == Project4.load_picture("images/gbCard" + 15 + ".gif") || cardimage == Project4.load_picture("images/gbCard" + 28 + ".gif") || cardimage == Project4.load_picture("images/gbCard" + 41 + ".gif")) {
                return 3;
            } else if (cardimage == Project4.load_picture("images/gbCard" + 3 + ".gif") || cardimage == Project4.load_picture("images/gbCard" + 16 + ".gif") || cardimage == Project4.load_picture("images/gbCard" + 29 + ".gif") || cardimage == Project4.load_picture("images/gbCard" + 42 + ".gif")) {
                return 4;
            } else if (cardimage == Project4.load_picture("images/gbCard" + 4 + ".gif") || cardimage == Project4.load_picture("images/gbCard" + 17 + ".gif") || cardimage == Project4.load_picture("images/gbCard" + 30 + ".gif") || cardimage == Project4.load_picture("images/gbCard" + 43 + ".gif")) {
                return 5;
            } else if (cardimage == Project4.load_picture("images/gbCard" + 5 + ".gif") || cardimage == Project4.load_picture("images/gbCard" + 18 + ".gif") || cardimage == Project4.load_picture("images/gbCard" + 31 + ".gif") || cardimage == Project4.load_picture("images/gbCard" + 44 + ".gif")) {
                return 6;
            } else if (cardimage == Project4.load_picture("images/gbCard" + 6 + ".gif") || cardimage == Project4.load_picture("images/gbCard" + 19 + ".gif") || cardimage == Project4.load_picture("images/gbCard" + 32 + ".gif") || cardimage == Project4.load_picture("images/gbCard" + 45 + ".gif")) {
                return 7;
            } else if (cardimage == Project4.load_picture("images/gbCard" + 7 + ".gif") || cardimage == Project4.load_picture("images/gbCard" + 20 + ".gif") || cardimage == Project4.load_picture("images/gbCard" + 33 + ".gif") || cardimage == Project4.load_picture("images/gbCard" + 46 + ".gif")) {
                return 8;
            } else if (cardimage == Project4.load_picture("images/gbCard" + 8 + ".gif") || cardimage == Project4.load_picture("images/gbCard" + 21 + ".gif") || cardimage == Project4.load_picture("images/gbCard" + 34 + ".gif") || cardimage == Project4.load_picture("images/gbCard" + 47 + ".gif")) {
                return 9;
            } else if (cardimage == Project4.load_picture("images/gbCard" + 9 + ".gif") || cardimage == Project4.load_picture("images/gbCard" + 22 + ".gif") || cardimage == Project4.load_picture("images/gbCard" + 35 + ".gif") || cardimage == Project4.load_picture("images/gbCard" + 48 + ".gif")) {            
                return 10;
            } else if (cardimage == Project4.load_picture("images/gbCard" + 10 + ".gif") || cardimage == Project4.load_picture("images/gbCard" +23 + ".gif") || cardimage == Project4.load_picture("images/gbCard" + 36 + ".gif") || cardimage == Project4.load_picture("images/gbCard" + 49 + ".gif")) {            
                return 10;
            } else if (cardimage == Project4.load_picture("images/gbCard" + 11 + ".gif") || cardimage == Project4.load_picture("images/gbCard" +24 + ".gif") || cardimage == Project4.load_picture("images/gbCard" + 37 + ".gif") || cardimage == Project4.load_picture("images/gbCard" + 50 + ".gif")) {            
                return 10;
            } else if (cardimage == Project4.load_picture("images/gbCard" + 12 + ".gif") || cardimage == Project4.load_picture("images/gbCard" +25 + ".gif") || cardimage == Project4.load_picture("images/gbCard" + 38 + ".gif") || cardimage == Project4.load_picture("images/gbCard" + 51 + ".gif")) {            
                return 10;
            } else {
                return 0;
            }
      }
      
      
      public int getValue(){
          return value;
      }  
      
      public void setCardImage(int newImage){
          cardimage = Project4.load_picture("images/gbCard" + newImage + ".gif");
      }
      
      public Card getNextCard() {
        return (Card)next;
      }
      public Image getCardImage() {
        return cardimage;
      }
     
     
    }  //end class Card
    
    /*****************************************************************
       Class CardList, A Linked list of playing cards
       May be placed in a file named CardList.java
    
       Note : This class can be used to create a 'hand' of cards
       Just Create another CardList object, and delete cards from
       'theDeck' and insert the into the new CardList object
    
    ******************************************************************/
    
    class CardList {
      private Card firstcard = null;
      private int numcards=0;
      
    
      public  CardList(int num) {
        numcards = num;   //set numcards in the deck
        for (int i = 0; i < num; i++) {  // load the cards
          Card temp = new Card(i);
          if (firstcard != null) {
            temp.setNext(firstcard);
          }
          firstcard = temp;
        }
      }
      
    
      public Card getFirstCard() {
          return firstcard;
      }
    
      public Card deleteCard(int cardnum) {
        Card target, targetprevious;
    
        if (cardnum > numcards)
          return null;   // not enough cards to delete that one
        else
          numcards--;
    
        target = firstcard;
        targetprevious = null;
        while (cardnum-- > 0) {
            targetprevious = target;
            target = target.getNextCard();
            if (target == null) return null;  // error, card not found
        }
        if (targetprevious != null)
          targetprevious.setNext(target.getNextCard());
        else
          firstcard =  target.getNextCard();
        return target;
      }
    
      public void insertCard(Card target) {
        numcards++;
        if (firstcard != null)
          target.setNext(firstcard);
        else
          target.setNext(null);
        firstcard =  target;
      }
    
      public void shuffle() {
        for ( int i = 0; i < 300; i++) {
          int rand = (int)(Math.random() * 100) % numcards;
          Card temp = deleteCard(rand);
          if (temp != null) insertCard(temp);
        }  // end for loop
      }   // end shuffle
      
     
    
    }    // end class CardList
    It would also be greatly appreciated if someone could give me tips on how to shorten my CardValue() method inside my Card class. A friend of mine gave me a tip to create a setCardImage() method, but I'm trying to figure out how to pass a a value as a parameter to that method.

    *EDIT* Also he gave me a tip on utilizing an extra window to choose between the value of 1 or 11 when the player drew an ace. Now it works, but I prefer my original class where it automatically does it for me. The problem is, I'm having difficulties utilizing my class because I rewrote my original Deck class and combined it into a CardList class
  2. #17
  3. Java Junkie
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jan 2004
    Location
    Mobile, Alabama
    Posts
    4,021
    Rep Power
    1285
    Look at the pattern of the numbers in the first if.

    1 14 27 40

    Notice what each has in common and how they relate to the value 2.
  4. #18
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    31
    Rep Power
    2
    Alright, so I managed to get my images to load based on the tips given to me by everyone. So I would like to thank you all

    Now the only other problem I have is that my card images don't correspond with the value of my card (for example, my card value is 8, but the image is a 9 of spades or the value is 2 but the image is an ace).

    Could anyone maybe double check what might be causing this problem?

    I'll upload my fixed code w/ all my classes as soon as I get home from school
  6. #19
  7. Contributing User
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Aug 2010
    Location
    Eastern Florida
    Posts
    3,711
    Rep Power
    347
    Array indexes start at 0 vs 1. Sometimes you need to make array indexing start at 1 so that the contents of an array slot matches the index. Define the array one element longer: say 53 to hold cards with indexes from 1 to 52. don't use the slot with index 0.
  8. #20
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    31
    Rep Power
    2
    Originally Posted by NormR
    Array indexes start at 0 vs 1. Sometimes you need to make array indexing start at 1 so that the contents of an array slot matches the index. Define the array one element longer: say 53 to hold cards with indexes from 1 to 52. don't use the slot with index 0.
    I tried that and one of my cards disappeared.

    EDIT: I actually tried a different approach in my getCardImage() method and now the values correspond with the card. I would like to thank you for helping me out with my program. It's working perfectly now.
  10. #21
  11. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    31
    Rep Power
    2
    Also, here's my updated code:

    Code:
    package project4homeversion;
    
     
     /* Ronald U. 
      * CMPSCI182 - Project 4: Card Game
      * April 25, 2013
      * In this applet, the user plays a game of Blackjack.  The
      * computer acts as the dealer.  The user plays by clicking
      * "Hit!" and "Stand!" buttons.    
     */
        
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;
    
        
        public class BlackjackGUI extends JApplet {
           private static int winxpos=0, winypos=0;
           private static JApplet myFrame = null;
           public void init() {
              myFrame = this;
                 // The init() method creates components and lays out the applet.
                 // A BlackjackCanvas occupies the CENTER position of the layout.
                 // On the bottom is a panel that holds three buttons.  The
                 // BlackjackCanvas object listens for events from the buttons
                 // and does all the real work of the program.
                 
              setBackground( new Color(130,50,40) );
              
              BlackjackCanvas board = new BlackjackCanvas();
              getContentPane().add(board, BorderLayout.CENTER);
              
              JPanel buttonPanel = new JPanel();
              buttonPanel.setBackground( new Color(220,200,180) );
              getContentPane().add(buttonPanel, BorderLayout.SOUTH);
              
              JButton newGame = new JButton( "New Game" );
              newGame.addActionListener(board);
              buttonPanel.add(newGame);
              
              JButton hit = new JButton( "Hit!" );
              hit.addActionListener(board);
              buttonPanel.add(hit);
              
              JButton stand = new JButton( "Stand!" );
              stand.addActionListener(board);
              buttonPanel.add(stand);
              
              
              
              JButton exit = new JButton("Exit");
              exit.addActionListener(board);
              buttonPanel.add(exit);
              
              setSize(800,700);
              setLocation(winxpos,winypos);
    
              setVisible(true);
              
           }  // end init()
           
           public Insets getInsets() {
                 // Specify how much space to leave between the edges of
                 // the applet and the components it contains.  The background
                 // color shows through in this border.
              return new Insets(3,3,3,3);
           }
           
           public static Image load_picture(String fname)
    {
            // Create a MediaTracker to inform us when the image has
            // been completely loaded.
            Image image;
            MediaTracker tracker = new MediaTracker(myFrame);
    
    
            // getImage() returns immediately.  The image is not
            // actually loaded until it is first used.  We use a
            // MediaTracker to make sure the image is loaded
            // before we try to display it.
    
            image = myFrame.getToolkit().getImage(fname);
    
            // Add the image to the MediaTracker so that we can wait
            // for it.
            tracker.addImage(image, 0);
            try { tracker.waitForID(0); }
            catch ( InterruptedException e) { System.err.println(e); }
    
            if (tracker.isErrorID(0)) { image=null;}
            return image;
    }
           
    
           // --- The remainder of this class consists of a nested class ---
    
        
           class BlackjackCanvas extends JPanel implements ActionListener {
    
                 // A nested class that displays the card game and does all the work
                 // of keeping track of the state and responding to user events.
    
              Deck deck;         // A deck of cards to be used in the game.
    
              BlackjackHand dealerHand;   // Hand containing the dealer's cards.
              BlackjackHand playerHand;   // Hand containing the user's cards.
    
              String message;  // A message drawn on the canvas, which changes
                               //    to reflect the state of the game.
    
              boolean gameInProgress;  // Set to true when a game begins and to false
                                       //   when the game ends.
    
              Font bigFont;      // Font that will be used to display the message.
              Font smallFont;    // Font that will be used to draw the cards.
    
    
              BlackjackCanvas() {
                    // Constructor.  Creates fonts and starts the first game.
                 
                 setBackground( new Color(0,120,0) );
                 smallFont = new Font("SansSerif", Font.PLAIN, 12);
                 bigFont = new Font("Serif", Font.BOLD, 14);
                 doNewGame();
              }
    
    
              public void actionPerformed(ActionEvent evt) {
                     // Respond when the user clicks on a button by calling
                     // the appropriate procedure.  Note that the canvas is
                     // registered as a listener in the BlackjackGUI class.
                 String command = evt.getActionCommand();
                 if (command.equals("Hit!"))
                    doHit();
                 else if (command.equals("Stand!"))
                    doStand();
                 else if (command.equals("New Game"))
                    doNewGame();
                 else if (command.equals("Exit"))
                     System.exit(0); 
              }
    
    
              void doHit() {
                     // This method is called when the user clicks the "Hit!" button.
                     // First check that a game is actually in progress.  If not, give
                     // an error message and exit.  Otherwise, give the user a card.
                     // The game can end at this point if the user goes over 21 or
                     // if the user has taken 5 cards without going over 21.
                 if (gameInProgress == false) {
                    message = "Click \"New Game\" to start a new game.";
                    repaint();
                    return;
                 }
                 playerHand.addCard( deck.dealCard() );
                 if ( playerHand.getBlackjackValue() > 21 ) {
                    message = "You've busted!  Sorry, you lose.";
                    gameInProgress = false;
                 }
                 else if (playerHand.getCardCount() == 5) {
                    message = "You win by taking 5 cards without going over 21.";
                    gameInProgress = false;
                 }
                 else {
                    message = "You have " + playerHand.getBlackjackValue() + ".  Hit or Stand?";
                 }
                 repaint();
              }
    
    
              void doStand() {
                      // This method is called when the user clicks the "Stand!" button.
                      // Check whether a game is actually in progress.  If it is,
                      // the game ends.  The dealer takes cards until either the
                      // dealer has 5 cards or more than 16 points.  Then the 
                      // winner of the game is determined.
                 if (gameInProgress == false) {
                    message = "Click \"New Game\" to start a new game.";
                    repaint();
                    return;
                 }
                 gameInProgress = false;
                 while (dealerHand.getBlackjackValue() <= 16 && dealerHand.getCardCount() < 5)
                    dealerHand.addCard( deck.dealCard() );
                 if (dealerHand.getBlackjackValue() > 21)
                     message = "You win!  Dealer has busted with " + dealerHand.getBlackjackValue() + ".";
                 else if (dealerHand.getCardCount() == 5)
                     message = "Sorry, you lose.  Dealer took 5 cards without going over 21.";
                 else if (dealerHand.getBlackjackValue() > playerHand.getBlackjackValue())
                     message = "Sorry, you lose, " + dealerHand.getBlackjackValue()
                                                       + " to " + playerHand.getBlackjackValue() + ".";
                 else if (dealerHand.getBlackjackValue() == playerHand.getBlackjackValue())
                     message = "Sorry, you lose.  Dealer wins on a tie.";
                 else
                     message = "You win, " + playerHand.getBlackjackValue()
                                                       + " to " + dealerHand.getBlackjackValue() + "!";
                 repaint();
              }
    
    
              void doNewGame() {
                     // Called by the constructor, and called by actionPerformed() if
                     // the use clicks the "New Game" button.  Start a new game.
                     // Deal two cards to each player.  The game might end right then
                     // if one of the players had blackjack.  Otherwise, gameInProgress
                     // is set to true and the game begins.
                 if (gameInProgress) {
                         // If the current game is not over, it is an error to try
                         // to start a new game.
                    message = "You still have to finish this game!";
                    repaint();
                    return;
                 }
                 deck = new Deck();   // Create the deck and hands to use for this game.
                 dealerHand = new BlackjackHand();
                 playerHand = new BlackjackHand();
                 deck.shuffle();
                 dealerHand.addCard( deck.dealCard() );  // Deal two cards to each player.
                 dealerHand.addCard( deck.dealCard() );
                 playerHand.addCard( deck.dealCard() );
                 playerHand.addCard( deck.dealCard() );
                 if (dealerHand.getBlackjackValue() == 21) {
                     message = "Sorry, you lose.  Dealer has Blackjack.";
                     gameInProgress = false;
                 }
                 else if (playerHand.getBlackjackValue() == 21) {
                     message = "You win!  You have Blackjack.";
                     gameInProgress = false;
                 }
                 else {
                     message = "You have " + playerHand.getBlackjackValue() + ".  Hit or stand?";
                     gameInProgress = true;
                 }
                 repaint();
              }  // end newGame();
    
    
              public void paintComponent(Graphics g) {
                    // The paint method shows the message at the bottom of the
                    // canvas, and it draws all of the dealt cards spread out
                    // across the canvas.
                // Card temp = new Card();
                 super.paintComponent(g); // fill with background color.
    
                 g.setFont(bigFont);
                 g.setColor(Color.black);
                 g.drawString(message, 10, getSize().height - 10);
    
                 // Draw labels for the two sets of cards.
    
                 g.drawString("Dealer's Cards:", 10, 23);
                 g.drawString("Your Cards:", 10, 153);
    
                 // Draw dealer's cards.  Draw first card face down if
                 // the game is still in progress,  It will be revealed
                 // when the game ends.
    
                 g.setFont(smallFont);
                 if (gameInProgress)
                    drawCard(g, null, 10, 30);
                 else
                    drawCard(g, dealerHand.getCard(0), 10, 30);
                 for (int i = 1; i < dealerHand.getCardCount(); i++)
                    drawCard(g, dealerHand.getCard(i), 10 + i * 90, 30);
    
                 // Draw the user's cards.
    
                 for (int i = 0; i < playerHand.getCardCount(); i++)
                    drawCard(g, playerHand.getCard(i), 10 + i * 90, 160);
    
              }  // end paint();
    
    
              void drawCard(Graphics g, Card card, int x, int y) {
                      // Draws a card as a 80 by 100 rectangle with
                      // upper left corner at (x,y).  The card is drawn
                      // in the graphics context g.  If card is null, then
                      // a face-down card is drawn.  (The cards are 
                      // rather primitive.)
                  
                 if (card == null) {  
                        // Draw a face-down card
                     
                    g.setColor(Color.blue);
                    g.fillRect(x,y,80,100);
                    g.setColor(Color.blue.darker());
                    g.drawRect(x+3,y+3,73,93);
                    g.drawRect(x+4,y+4,71,91);
                 }
                 else {
    //                g.setColor(Color.white);
    //                g.fillRect(x,y,80,100);
    //                g.setColor(Color.gray);
    //                g.drawRect(x,y,79,99);
    //                g.drawRect(x+1,y+1,77,97);
    //      
                    g.drawImage(card.getCardImage(), x, y, this);
                    g.drawString(card.getValueAsString(), x + 10, y + 30);
    //                
                    
                 }
              }  // end drawCard()
    
    
           } // end nested class BlackjackCanvas
    
    
        } // end class BlackjackGUI
    Here's my Deck class where it creates the deck of Cards:
    Code:
    /*
    
    * To change this template, choose Tools | Templates
    
    * and open the template in the editor.
    
    */
    
    package project4homeversion;
    
     
    
    /**
    
    *
    
    * @author ronaldu
    
    */
    
    public class Deck {
    
        private Card[] deck;   // An array of 52 Cards, representing the deck.
        private int cardsUsed; // How many cards have been dealt from the deck.
    
        public Deck() {
            // Create an unshuffled deck of cards.
           deck = new Card[52];
    
           int cardCt = 0; // How many cards have been created so far.
    
           for ( int suit = 0; suit <= 3; suit++ ) {
    
              for ( int value = 1; value <= 13; value++ ) {
    
                 deck[cardCt] = new Card(value);
    
                 cardCt++;
    
              }
           }
           cardsUsed = 0;
        }
    
        public void shuffle() {
    
              // Put all the used cards back into the deck, and shuffle it into
    
              // a random order.
    
            for ( int i = 51; i > 0; i-- ) {
    
                int rand = (int)(Math.random()*(i+1));
    
                Card temp = deck[i];
    
                deck[i] = deck[rand];
    
                deck[rand] = temp;
    
            }
    
            cardsUsed = 0;
    
        }
    
       
    
        public int cardsLeft() {
    
              // As cards are dealt from the deck, the number of cards left
    
              // decreases.  This function returns the number of cards that
    
              // are still left in the deck.
    
            return 52 - cardsUsed;
    
        }
    
       
    
        public Card dealCard() {
    
              // Deals one card from the deck and returns it.
    
            if (cardsUsed == 52)
    
               shuffle();
    
            cardsUsed++;
    
            return deck[cardsUsed];
    
        }
    } // end class Deck
    And this class, my Card class, establishes a value to the cards as well as grabs the cardimage.
    Code:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package project4homeversion;
    
    import java.awt.Image;
    
    /**
     *
     * @author ronaldu
     */
    public class Card extends Link {
        private Image cardimage;
        
        
    //    public final static int SPADES = 0,       // Codes for the 4 suits.
    //                            HEARTS = 1,
    //                            DIAMONDS = 2,
    //                            CLUBS = 3;
                                
        public final static int ACE = 1,          // Codes for the non-numeric cards.
                                JACK = 11,        //   Cards 2 through 10 have their 
                                QUEEN = 12,       //   numerical values for their codes.
                                KING = 13;
                                
        //private final int suit;   // The suit of this card, one of the constants
                                  //    SPADES, HEARTS, DIAMONDS, CLUBS.
                                  
        private final int value;  // The value of this card, from 1 to 11.
                                 
        public Card (int theValue) {
                // Construct a card with the specified value and suit.
                // Value must be between 1 and 13.  Suit must be between
                // 0 and 3.  If the parameters are outside these ranges,
                // the constructed card object will be invalid.
            value = theValue;
    
            cardimage = BlackjackGUI.load_picture("images/gbCard" + theValue + ".gif");
            if (cardimage == null){
                System.out.println("Error - Image failed to load: images/gbCard" + theValue
                        + ".gif");
                System.exit(-1);
            }
            cardimage = BlackjackGUI.load_picture("images/gbCard" + theValue + ".gif");
            
            
        }
            
    //    public int getSuit() {
    //            // Return the int that codes for this card's suit.
    //        return suit;
    //    }
    //    
        public int getValue() {
                // Return the int that codes for this card's value.
            return value;
        }
        
    //    public String getSuitAsString() {
    //            // Return a String representing the card's suit.
    //            // (If the card's suit is invalid, "??" is returned.)
    //        switch ( suit ) {
    //           case SPADES:   return "Spades";
    //           case HEARTS:   return "Hearts";
    //           case DIAMONDS: return "Diamonds";
    //           case CLUBS:    return "Clubs";
    //           default:       return "??";
    //        }
    //    }
    //    
        
        
        public String getValueAsString() {
                // Return a String representing the card's value.
                // If the card's value is invalid, "??" is returned.
            switch ( value ) {
               case 1:   return "Ace";
               case 2:   return "2";
               case 3:   return "3";
               case 4:   return "4";
               case 5:   return "5";
               case 6:   return "6";
               case 7:   return "7";
               case 8:   return "8";
               case 9:   return "9";
               case 10:  return "10";
               case 11:  return "Jack";
               case 12:  return "Queen";
               case 13:  return "King";
               default:  return "??";
            }
        }
        
        public String toString() {
               // Return a String representation of this card, such as
               // "10 of Hearts" or "Queen of Spades".
            return getValueAsString();
        }
        
        public Image getCardImage() {
            return cardimage;
        }
        public Card getNextCard() {
            return (Card)next;
        }
    
    } // end class Card
    EDITED TO REMOVE LAST NAME.
  12. #22
  13. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    31
    Rep Power
    2
    Quick question tho, say in the future, if I want to send this game to a friend so he could play it, how would I do that without having him install Netbeans or any other programs?
    Is there a way to compile it into one package so that anyone could just double click the file and immediately play it?
  14. #23
  15. Java Junkie
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jan 2004
    Location
    Mobile, Alabama
    Posts
    4,021
    Rep Power
    1285
    Originally Posted by jron5
    Quick question tho, say in the future, if I want to send this game to a friend so he could play it, how would I do that without having him install Netbeans or any other programs?
    Is there a way to compile it into one package so that anyone could just double click the file and immediately play it?
    They would need to at least have the JRE installed.
  16. #24
  17. Lord of the Dance
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Oct 2003
    Posts
    3,575
    Rep Power
    1906
    Originally Posted by jron5
    Quick question tho, say in the future, if I want to send this game to a friend so he could play it, how would I do that without having him install Netbeans or any other programs?
    Is there a way to compile it into one package so that anyone could just double click the file and immediately play it?
    You should also look up how to create a Jar (Java ARchive) file.
Page 2 of 2 First 12
  • Jump to page:

IMN logo majestic logo threadwatch logo seochat tools logo