Home - Programming - Java- BlackJack

BlackJack

BlackJack Main Class

001/**
002* @(#)BlackJack.java
003* BlackJack application
004* Author: Brian SonniE
005*/
006import javax.swing.*;
007import javax.swing.border.*;
008import java.awt.*;
009import java.awt.event.*;
010import java.awt.image.*;
011import java.util.*;
012import java.io.*;
013import javax.imageio.*;
014 
015public class BlackJack extends JFrame{
016    int cash = 0;
017    int currentBet = 0;
018    ArrayList<Card> deck;
019    Card[] usersCards = new Card[10];
020    Card[] dealersCards = new Card[10];
021    private JButton buttonHit, buttonStay, buttonDeal, buttonCashOut;
022    private JPanel userPane, dealerPane, userCardPane;
023    private JLabel labelMoney, labelBet;
024    BufferedImage img;
025    final int cardWidth = 79;
026    final int cardHeight = 123;
027    boolean gameOn = true
028 
029public BlackJack() {
030    setTitle("BlackJack"); 
031    setSize(450,500);  
032    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    
033    setLayout(new BorderLayout());
034    setVisible(true);  
035    setBackground(Color.green);    
036    buildTable();  
037    gameInit();    
038    repaint();
039    getContentPane().setBackground(Color.GREEN);
040    
041     
042public void paint(Graphics g) {    
043     
044    super.paint(g);    
045    g.drawString("Dealers Hand", 20, 60);  
046    g.drawString("Your Hand", 20, 230);        
047    g.drawString("Sum: "+getUserSum(), 90, 230);       
048    int x1 = 10;   
049    int y1 = 250;  
050    int x2 = x1+cardWidth; 
051    int y2 = y1+cardHeight;        
052    int dx1 = 10;  
053    int dy1 = 80;  
054    int dx2 = dx1+cardWidth;   
055    int dy2 = dy1+cardHeight;      
056    // Draw Dealers Cards      
057    for(int i = 1; i<=getNumDealerCards(); i++) 
058    {  
059    g.drawImage(img, dx1+(cardWidth*(i-1)), dy1, dx2+(cardWidth*(i-1)), dy2, dealersCards[i-1].getX(),
060        dealersCards[i-1].getY(), dealersCards[i-1].getX()+cardWidth ,dealersCards[i-1].getY()+cardHeight,null);
061    }      
062    // Draw User Cards
063    for(int i = 1; i<=getNumUserCards(); i++)
064    {  
065        g.drawImage(img, x1+(cardWidth*(i-1)), y1, x2+(cardWidth*(i-1)), y2, usersCards[i-1].getX(),
066            usersCards[i-1].getY(), usersCards[i-1].getX()+cardWidth ,usersCards[i-1].getY()+cardHeight,null);
067    }
068    
069    public int getNumUserCards()
070    {  
071        int numCards = 0;  
072        while(usersCards[numCards]!=null)
073        numCards++;
074        return numCards;
075    }
076     
077    public int getNumDealerCards() {
078    int numCards = 0;
079 
080    while(dealersCards[numCards]!=null)
081        numCards++;    
082    return numCards;
083    } public int getUserSum()
084    {  
085    int numCards = 0;  
086    int sum = 0;   
087    int cardVal = 0;
088    while(usersCards[numCards]!=null){
089        cardVal = usersCards[numCards].getValue();
090        if(cardVal == 1 && sum<=10)
091                cardVal = 11;
092        else if(cardVal == 11)
093                cardVal = 10;
094        else if(cardVal == 12)
095                cardVal = 10;
096        else if(cardVal == 13)
097                cardVal = 10;
098        sum+=cardVal;
099        numCards++;
100    }  
101    return sum;
102 }
103 public int getDealerSum() {   
104    int numCards = 0;  
105    int sum = 0;   
106    int cardVal = 0;   
107    while(dealersCards[numCards]!=null){       
108    cardVal = dealersCards[numCards].getValue();       
109    if(cardVal == 1 && sum<=10)             
110        cardVal = 11;
111        else if(cardVal == 11)
112                cardVal = 10;
113        else if(cardVal == 12)
114                cardVal = 10;
115        else if(cardVal == 13)
116                cardVal = 10;
117        sum+=cardVal;
118        numCards++;
119    }  
120    return sum;
121 }
122 // Recursion Implemented Check \
123  public int setBet(int bet)
124  {
125    try{   
126    bet = Integer.parseInt(JOptionPane.showInputDialog("Enter Your Bet: "));
127    }catch(NumberFormatException ex)
128    {   bet=0; }
129    if(bet <= 0 || bet > cash)
130    bet=setBet(0);
131        else
132        labelBet.setText(Integer.toString(bet));
133        return bet;
134 }
135 public void buildTable() {
136    //***Dealer Pane***\
137    dealerPane = new JPanel();
138    dealerPane.setBackground(Color.gray);
139    buttonDeal = new JButton("Deal");
140    buttonCashOut = new JButton("Walk Away");
141    dealerPane.add(buttonCashOut);
142    dealerPane.add(buttonDeal);
143    buttonDeal.addActionListener(new Dealer());
144    buttonCashOut.addActionListener(new Walk());
145      
146    //***UserCardPane***\
147    userCardPane = new JPanel();
148    //***UserPane***\
149    userPane = new JPanel(new GridLayout(3,2));
150    Border pancakes = BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Your Money");
151    userPane.setBorder(pancakes);
152    userPane.setBackground(Color.gray);
153    buttonHit = new JButton("Hit");
154    buttonStay = new JButton("Stay");
155    labelBet = new JLabel("0");
156    labelMoney = new JLabel("0");
157    userPane.add(new JLabel("Your Total Monies: "));
158    userPane.add(labelMoney);
159    userPane.add(new JLabel("Your Bet: "));
160    userPane.add(labelBet);
161    userPane.add(buttonHit);
162    userPane.add(buttonStay);
163    buttonHit.addActionListener(new HitMe());
164    buttonStay.addActionListener(new Stay());
165    add(dealerPane, BorderLayout.NORTH);
166    add(userPane, BorderLayout.SOUTH);
167     // Set Starting Money
168    try {
169    img = ImageIO.read(new File("cards.png"));
170    } catch (IOException e) {}
171    cash = getStartingAmmt();
172    labelMoney.setText(Integer.toString(cash));
173    
174    /**
175    * Code for New Round
176    */
177    public void gameInit() {
178    currentBet = setBet(0);
179    usersCards = new Card[10];
180    dealersCards = new Card[10];
181    deck = new ArrayList<Card>(52);
182     
183    for(int i = 0; i<52; i++)
184        deck.add(i, new Card((i%4),(i%13)+1));     
185     
186    // Give User and Dealer 2 Cards Each       
187    usersCards[0] = pullRandomCard();
188    usersCards[1] = pullRandomCard();
189    dealersCards[0] = pullRandomCard();
190    dealersCards[1] = pullRandomCard();
191    repaint();
192    }
193     
194    public int getStartingAmmt() {
195        int amnt = 0;
196    while(amnt<=0)
197    {
198        try{
199        amnt = Integer.parseInt(JOptionPane.showInputDialog("Enter Starting Ammount of Money:"));
200        }catch(NumberFormatException nfe){      amnt=0;     }
201    }
202    return amnt;
203    }
204 
205    public Card pullRandomCard()
206    {
207        Random rand = new Random();
208                return deck.remove(rand.nextInt(deck.size()));
209    }
210    //*********************EVENTS*******************\
211  /** Deal
212    * Recreate The deck 
213    * Give dealer and user 2 cards
214    */
215 
216    class Dealer implements ActionListener{
217        public void actionPerformed(ActionEvent ae)
218        {
219            gameOn = true;
220            gameInit();
221        }
222    
223     
224    /** Hit Me
225    * Draw a random card from the deck
226    * Check the new sum of cards
227    * if 21 user wins
228    * if > 21 user losses
229    * if < 21 user can choose to hit/stay
230    */ 
231    class HitMe implements ActionListener{
232        public void actionPerformed(ActionEvent ae)
233        {
234            if(gameOn){
235            usersCards[getNumUserCards()] = pullRandomCard();
236            repaint();
237            if(getUserSum()>21)
238            {
239                    // You Lose
240                JOptionPane.showMessageDialog(null, "You Lost...");
241                gameOn = false;
242                cash-=currentBet;
243                labelMoney.setText(Integer.toString(cash));
244            }
245            if(cash<=0)
246            {
247                JOptionPane.showMessageDialog(null,"You broke...");
248                System.exit(0);
249            }
250            }
251        }  
252    }
253 
254   /**  
255    * Check for winner
256    */
257    class Stay implements ActionListener{
258        public void actionPerformed(ActionEvent ae)
259        {
260            if(gameOn){
261            gameOn = false;
262            if(getUserSum()>21)
263            {
264                // You Lose
265                JOptionPane.showMessageDialog(null, "You Lost...");
266                cash-=currentBet;
267                labelMoney.setText(Integer.toString(cash));
268            }
269            // Ai
270            else {
271                while(getDealerSum()<17)
272                {
273                    dealersCards[getNumDealerCards()] = pullRandomCard();
274                }
275                if(getDealerSum()>21)
276                {
277                    // You Win
278                    JOptionPane.showMessageDialog(null, "You Win!!");
279                    cash+=currentBet;
280                    labelMoney.setText(Integer.toString(cash));
281                }
282                else{
283                    if(21-getUserSum() < 21-getDealerSum())
284                    {// You win
285                        JOptionPane.showMessageDialog(null, "You Win!!");
286                        cash+=currentBet;
287                        labelMoney.setText(Integer.toString(cash));
288                    }
289                    else if(getUserSum() == getDealerSum())
290                    {
291                        JOptionPane.showMessageDialog(null, "Tie...");
292                    }
293                    else // You Lose
294                    {
295                        JOptionPane.showMessageDialog(null, "You Lost...");
296                        cash-=currentBet;
297                        labelMoney.setText(Integer.toString(cash));
298                    }
299                }
300            }
301            repaint();
302            if(cash<=0)
303            {
304                JOptionPane.showMessageDialog(null,"You broke...");
305            System.exit(0);
306            }
307            }
308        }  
309    }
310     
311    /**
312     * Leav App
313     */
314     class Walk implements ActionListener{
315        public void actionPerformed(ActionEvent ae)
316        {
317            JOptionPane.showMessageDialog(null, "You played and walked away with $" + cash);
318            System.exit(0);
319        }
320    }
321     
322    public static void main(String[] args) {
323        new BlackJack();
324    }
325}

Card.class

01public class Card {
02    private int cardValue;
03    private int cardSuit;
04    public Card()
05    {
06        cardValue = 0;
07        cardSuit = 0;
08    }
09    public Card(int suit, int val)
10    {
11        cardValue = val;
12        cardSuit = suit;
13    }
14    public void setValue(int val)
15    {
16        cardValue = val;
17    }
18    public void setSuit(int suit)
19    {
20        cardSuit = suit;
21    }
22    public int getValue()
23    {
24        return cardValue;
25    }
26    public int getSuit()
27    {
28        return cardSuit;
29    }
30    public int getY()
31    {
32        return 123*cardSuit;
33    }
34    public int getX()
35    {
36        return 79*(cardValue-1);
37    }
38}

Output

 

Ad Space

Ads