Main.java

mail@pastecode.io avatar
unknown
plain_text
8 months ago
22 kB
0
Indexable
Never
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Random;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;

class ImagePanel extends JPanel {
    private BufferedImage backgroundImage;

    public ImagePanel(String imagePath) {
        try {
            URL resource = getClass().getResource(imagePath);
            if (resource != null) {
                backgroundImage = ImageIO.read(resource);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (backgroundImage != null) {
            g.drawImage(backgroundImage, 0, 0, getWidth(), getHeight(), this);
        }
    }
}

public class Main {

    private JFrame frame;
    private JPanel topPanel;
    private JPanel bottomPanel;
    private boolean isFirstMode = true;
    private JLabel betLabel;
    private JLabel balanceLabel;

    int betOffsetIndex = 0;
    int betAmount = 0;

    static ArrayList<Bets> bets = new ArrayList<>();
    ArrayList<JLabel> displayedBets = new ArrayList<>(); // Store displayed bets
    
 	public static ArrayList<Cards> cards = new ArrayList<>();
 	public static ArrayList<Cards> playerCards = new ArrayList<>();
 	public static ArrayList<Cards> dealerCards = new ArrayList<>();
 	public static ArrayList<ImageIcon> cardIcons = new ArrayList<>();
 	
 	// Using two sums for the case where Ace is both 1 and 11.
 	public static int playerS1 = 0;
 	public static int playerS2 = 0;
 	public static int dealerS1 = 0;
 	public static int dealerS2 = 0;
 	
 	public static int balance = 1000;
 	
 	public static int winner; // 0 = player, 1 = dealer, 2 = tie
 	
 	public static int dealerMaxSum = 0;
 	
    String[] ranks = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};
    String[] suits = {"Hearts", "Diamonds", "Clubs", "Spades"};

    Random rng = new Random();
	
	int numberOfDecks = 3;

    Boolean b = true;

    
    public Main() {
        frame = new JFrame("Blackjack");
        frame.setLayout(new BorderLayout());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(1000, 700);
        frame.setResizable(false);
        
        topPanel = new ImagePanel("/background.png"); // Replace with your image path
        topPanel.setLayout(null);

        bottomPanel = new JPanel();
        bottomPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
        bottomPanel.setPreferredSize(new Dimension(frame.getWidth(), 40));
        
        betLabel = new JLabel("Bet: " + betAmount);
        balanceLabel = new JLabel("Balance: " + balance);

        switchMode();

        frame.add(topPanel, BorderLayout.CENTER);
        frame.add(bottomPanel, BorderLayout.SOUTH);

        frame.setVisible(true);
        
    }

    private void switchMode() {
        bottomPanel.removeAll(); // Clear previous components
        
        if (isFirstMode) {
        	
        	if(b) {
        		Bets bet10 = new Bets(10, new ImageIcon (new ImageIcon(this.getClass().getResource("Chip10.png")).getImage().getScaledInstance(70, 70,  java.awt.Image.SCALE_SMOOTH)));
                Bets bet50 = new Bets(50, new ImageIcon (new ImageIcon(this.getClass().getResource("Chip50.png")).getImage().getScaledInstance(70, 70,  java.awt.Image.SCALE_SMOOTH)));
                Bets bet100 = new Bets(100, new ImageIcon (new ImageIcon(this.getClass().getResource("Chip100.png")).getImage().getScaledInstance(70, 70,  java.awt.Image.SCALE_SMOOTH)));
                Bets bet500 = new Bets(500, new ImageIcon (new ImageIcon(this.getClass().getResource("Chip500.png")).getImage().getScaledInstance(70, 70,  java.awt.Image.SCALE_SMOOTH)));

                bets.add(bet10);
                bets.add(bet50);
                bets.add(bet100);
                bets.add(bet500);
                
                b = false;
        	}
        	
            topPanel.removeAll();
            topPanel.revalidate();
            topPanel.repaint();

            displayedBets.clear();

            betAmount = 0;
            betOffsetIndex = 0;
            betLabel.setText("Bet: " + betAmount);
            balanceLabel.setText("Balance: " + balance);
            
            bottomPanel.setBackground(Color.decode("#3d3d3d"));

            for (Bets bet : bets) {
                JButton betButton = new JButton(String.valueOf(bet.betAmmount));
                
                bottomPanel.add(betButton);

                if (!"Deal Cards!".equals(betButton.getText())) { // Exclude "Deal cards" button from processing
                    betButton.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            int clickedBet = Integer.parseInt(betButton.getText());
                            if (balance >= clickedBet) {
                                addIconAtPosition(bet.icon, 163, 277 + betOffsetIndex);
                               
                                betAmount += clickedBet;
                                balance -= clickedBet;

                                betLabel.setText("Bet: " + betAmount);
                                balanceLabel.setText("Balance: " + balance);

                                betOffsetIndex -= 12;
                            }

                            // Update buttons' enabled status based on the available balance
                            for (Component comp : bottomPanel.getComponents()) {
                                if (comp instanceof JButton) {
                                    JButton button = (JButton) comp;
                                    if (!"Deal Cards!".equals(button.getText())) { // Exclude "Deal cards" button
                                        int buttonBet = Integer.parseInt(button.getText());
                                        button.setEnabled(balance >= buttonBet);
                                    }
                                }
                            }
                        }
                    });

                    // Initially disable buttons that exceed the available balance
                    betButton.setEnabled(balance >= bet.betAmmount);
                }
            }

            bottomPanel.add(betLabel);
            bottomPanel.add(balanceLabel);

            betLabel.setForeground(Color.WHITE);
    		balanceLabel.setForeground(Color.WHITE);
            
            JButton switchModeButton = new JButton("Deal Cards!");
            switchModeButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                	if(betAmount != 0) {
                		isFirstMode = !isFirstMode;
                        switchMode();
                	}
                }
            });
            bottomPanel.add(switchModeButton);
            
            if (balance <= 0) {
            	bottomPanel.removeAll(); 
                frame.revalidate();
                frame.repaint();
            }
        } 
        else  
        {
        	playerCards.clear();
        	dealerCards.clear();

            JLabel dealerLabel = new JLabel("Dealer: ");
            JLabel playerLabel = new JLabel("You: ");
            JLabel betLabel = new JLabel("Bet: " + betAmount);
            
            bottomPanel.add(dealerLabel);
            bottomPanel.add(playerLabel);
            bottomPanel.add(betLabel);

            betLabel.setForeground(Color.WHITE);
    		dealerLabel.setForeground(Color.WHITE);
    		playerLabel.setForeground(Color.WHITE);
            
            JButton hitButton = new JButton("Hit");
            JButton standButton = new JButton("Stand");
            JButton switchModeButton = new JButton("Play Again!");
            
            switchModeButton.setEnabled(false);
            
            hitButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                	                	
                	if(playerS1 < 21 || playerS2 < 21 && playerS1 != 21 && playerS2 != 21) {
                    	hit();
                    	if(playerS1 > 21 && playerS2 > 21) {
                    		winner = 1;
                    		bottomPanel.setBackground(Color.decode("#e03d27"));
                    		
                    		playerLabel.setForeground(Color.WHITE);
                    		dealerLabel.setForeground(Color.WHITE);
                    		betLabel.setForeground(Color.WHITE);
                    		
                    		hitButton.setForeground(Color.decode("#e03d27"));
                    		standButton.setForeground(Color.decode("#e03d27"));
                    		switchModeButton.setForeground(Color.decode("#e03d27"));
                    		
                    		switchModeButton.setEnabled(true);
                    		hitButton.setEnabled(false);
                    		standButton.setEnabled(false);
                    	}
                	}

                    displayPlayerCards(topPanel);
                    
                    playerLabel.setText("You: " + playerS1 + " / " + playerS2);
                    
                	topPanel.revalidate();
                    topPanel.repaint();
                }
            });
            
            standButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                	
                	dealerMaxSum = Math.max(dealerS1, dealerS2);
                	while(dealerMaxSum <= 16) {
                		dealerHit();
                		dealerSum();
                	
                		dealerLabel.setText("Dealer: " + dealerS1 + " / " + dealerS2);
                		
                    	dealerMaxSum = Math.max(dealerS1, dealerS2);
                    	
                    	displayDealerCards(topPanel);
                	}
                    	hitButton.setEnabled(false);
                    	standButton.setEnabled(false);
                    	switchModeButton.setEnabled(true);
                    	
                    	checkWinner();
                    	
                    	if(winner == 0) {
                    		balance += 2 * betAmount;
                    		betAmount = 0;
                    		bottomPanel.setBackground(Color.decode("#1bbc2e"));
                    		
                    		playerLabel.setForeground(Color.WHITE);
                    		dealerLabel.setForeground(Color.WHITE);
                    		betLabel.setForeground(Color.WHITE);

                    		hitButton.setForeground(Color.decode("#1bbc2e"));
                    		standButton.setForeground(Color.decode("#1bbc2e"));
                    		switchModeButton.setForeground(Color.decode("#1bbc2e"));
                    	}
                    	else if(winner == 1) {
                    		betAmount = 0;
                    		bottomPanel.setBackground(Color.decode("#e03d27"));
                    		
                    		playerLabel.setForeground(Color.WHITE);
                    		dealerLabel.setForeground(Color.WHITE);
                    		betLabel.setForeground(Color.WHITE);
                    		
                    		hitButton.setForeground(Color.decode("#e03d27"));
                    		standButton.setForeground(Color.decode("#e03d27"));
                    		switchModeButton.setForeground(Color.decode("#e03d27"));
                    	}
                    	else if(winner == 2){
                    		balance += betAmount;
                    		betAmount = 0;
                    		bottomPanel.setBackground(Color.decode("#f2c033"));
                    		
                    		playerLabel.setForeground(Color.WHITE);
                    		dealerLabel.setForeground(Color.WHITE);
                    		betLabel.setForeground(Color.WHITE);
                    		
                    		hitButton.setForeground(Color.decode("#f2c033"));
                    		standButton.setForeground(Color.decode("#f2c033"));
                    		switchModeButton.setForeground(Color.decode("#f2c033"));
                    	}
                    	
                    	topPanel.revalidate();
                        topPanel.repaint();
                	
                }
                
            });
            
            bottomPanel.add(hitButton);
            bottomPanel.add(standButton);

            switchModeButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    isFirstMode = !isFirstMode;
                    switchMode();
                    if (balance <= 0) {
                    	bottomPanel.removeAll(); 
                        frame.revalidate();
                        frame.repaint();
                    }
                }
            });
            bottomPanel.add(switchModeButton);
           
            ImageIcon icon;
            
            // Resetting array lists at the start of a new game
            playerCards.clear();
            dealerCards.clear();
            cards.clear();
            
           	for (String rank : ranks) {
           		for (String suit : suits) {
                    String iconAddress = rank + suit;
                   	icon = new ImageIcon (new ImageIcon(this.getClass().getResource(iconAddress + ".png")).getImage().getScaledInstance(1700, 1000,  java.awt.Image.SCALE_SMOOTH));
                    Cards card = new Cards(suit, rank, numberOfDecks, icon);
                    cards.add(card);
                }
            }
            
            hit();
            dealerHit();
            hit();
            
            playerLabel.setText("You: " + playerS1 + " / " + playerS2);
            dealerLabel.setText("Dealer: " + dealerS1 + " / " + dealerS2);
            
            displayPlayerCards(topPanel);
            displayDealerCards(topPanel);
        }

        bottomPanel.revalidate(); // Refresh the layout
        bottomPanel.repaint();    // Repaint the panel
    }

    private void addIconAtPosition(ImageIcon icon, int x, int y) {
        JLabel displayBet = new JLabel(icon);
        displayBet.setBounds(x, y, icon.getIconWidth(), icon.getIconHeight());
        displayedBets.add(displayBet); // Store the displayed bet label

        topPanel.removeAll(); // Clear the panel

        // Add displayed bets in reverse order (from last to first) to maintain the correct layering
        for (int i = displayedBets.size() - 1; i >= 0; i--) {
            JLabel bet = displayedBets.get(i);
            topPanel.add(bet);
        }

        topPanel.revalidate();
        topPanel.repaint();
    }
    
    public static void displayDealerCards(JPanel panel) {
	    int x = 350; // Starting X position for the card icons
	    int y = 120; // Y position for the card icons
	    int cardWidth = 70; // Width for the card icons
	    int cardHeight = 95; // Height for the card icons

	    for (Cards card : dealerCards) {
	        Image resizedImage = card.icon.getImage().getScaledInstance(cardWidth, cardHeight, Image.SCALE_SMOOTH);
	        ImageIcon resizedIcon = new ImageIcon(resizedImage);
	        JLabel cardLabel = new JLabel(resizedIcon);
	        cardLabel.setBounds(x, y, cardWidth, cardHeight);
	        
	        // Set the Z-order of the cardLabel to the topmost layer (highest Z-order)
	        panel.add(cardLabel, Integer.valueOf(0));

	        // Increment X position to display the next card icon
	        x += 75; 
	        
	        // Ensure the cardLabel is brought to the front after setting Z-order
	        cardLabel.repaint();
	    }

	    panel.revalidate();
	    panel.repaint();
	}
    
    public static void displayPlayerCards(JPanel panel) {
	    int x = 350; // Starting X position for the card icons
	    int y = 400; // Y position for the card icons
	    int cardWidth = 70; // Width for the card icons
	    int cardHeight = 95; // Height for the card icons

	    for (Cards card : playerCards) {
	        Image resizedImage = card.icon.getImage().getScaledInstance(cardWidth, cardHeight, Image.SCALE_SMOOTH);
	        ImageIcon resizedIcon = new ImageIcon(resizedImage);
	        JLabel cardLabel = new JLabel(resizedIcon);
	        
	        cardLabel.setBounds(x, y, cardWidth, cardHeight);
	        
	        // Set the Z-order of the cardLabel to the topmost layer (highest Z-order)
	        panel.add(cardLabel, Integer.valueOf(0));

	        // Increment X position to display the next card icon
	        x += 75; 
	        
	        // Ensure the cardLabel is brought to the front after setting Z-order
	        cardLabel.repaint();
	    }

	    panel.revalidate();
	    panel.repaint();
	}
    
    // Hit method
 	public static void hit() {
 		
 		Random rng = new Random();
 		Boolean cardFound = false;

 		while(!cardFound) {
 			int randomIndex = rng.nextInt(52);
 			if(cards.get(randomIndex).numberOfCards > 0) {
 				
 				Cards card = cards.get(randomIndex);
 				
 				card.useCard();
 				playerCards.add(card);
 				
 				
 				cardFound = true;
 			}
 		}
 		
 		playerSum();
 		
 	}
 	
 	// dealerHit method
  	public static void dealerHit() {
  		
  		Random rng = new Random();
  		Boolean cardFound = false;

  		while(!cardFound) {
  			int randomIndex = rng.nextInt(52);
  			if(cards.get(randomIndex).numberOfCards > 0) {
  				
  				Cards card = cards.get(randomIndex);
  				
  				card.useCard();
  				dealerCards.add(card);
  				
  				
  				cardFound = true;
  			}
  		}
  		
  		dealerSum();
  		
  	}
    
 // Player Cards Sum method
 	public static void playerSum() {
 		
 		playerS1 = 0;
 		playerS2 = 0;
 		
 		for( Cards card : playerCards ) {
 			switch(card.rank) {
 				case "2":
 					playerS1 += 2;
 					playerS2 += 2;
 					break;
 				case "3":
 					playerS1 += 3;
 					playerS2 += 3;
 					break;
 				case "4":
 					playerS1 += 4;
 					playerS2 += 4;
 					break;
 				case "5":
 					playerS1 += 5;
 					playerS2 += 5;
 					break;
 				case "6":
 					playerS1 += 6;
 					playerS2 += 6;
 					break;
 				case "7":
 					playerS1 += 7;
 					playerS2 += 7;
 					break;
 				case "8":
 					playerS1 += 8;
 					playerS2 += 8;
 					break;
 				case "9":
 					playerS1 += 9;
 					playerS2 += 9;
 					break;
 				case "10":
 					playerS1 += 10;
 					playerS2 += 10;
 					break;
 				case "J":
 					playerS1 += 10;
 					playerS2 += 10;
 					break;
 				case "Q":
 					playerS1 += 10;
 					playerS2 += 10;
 					break;
 				case "K":
 					playerS1 += 10;
 					playerS2 += 10;
 					break;
 				case "A":
 					playerS1 += 1;
 					playerS2 += 11;
 					break;
 			}
 		}
 	}

 	// Dealer Cards Sum method
 	public static void dealerSum() {
 		
 		dealerS1 = 0;
 		dealerS2 = 0;
 		
 		for( Cards card : dealerCards ) {
 			switch(card.rank) {
 				case "2":
 					dealerS1 += 2;
 					dealerS2 += 2;
 					break;
 				case "3":
 					dealerS1 += 3;
 					dealerS2 += 3;
 					break;
 				case "4":
 					dealerS1 += 4;
 					dealerS2 += 4;
 					break;
 				case "5":
 					dealerS1 += 5;
 					dealerS2 += 5;
 					break;
 				case "6":
 					dealerS1 += 6;
 					dealerS2 += 6;
 					break;
 				case "7":
 					dealerS1 += 7;
 					dealerS2 += 7;
 					break;
 				case "8":
 					dealerS1 += 8;
 					dealerS2 += 8;
 					break;
 				case "9":
 					dealerS1 += 9;
 					dealerS2 += 9;
 					break;
 				case "10":
 					dealerS1 += 10;
 					dealerS2 += 10;
 					break;
 				case "J":
 					dealerS1 += 10;
 					dealerS2 += 10;
 					break;
 				case "Q":
 					dealerS1 += 10;
 					dealerS2 += 10;
 					break;
 				case "K":
 					dealerS1 += 10;
 					dealerS2 += 10;
 					break;
 				case "A":
 					dealerS1 += 1;
 					dealerS2 += 11;
 					break;
 			}
 		}
 		
 	}
  	
 	public static void checkWinner() {
 		 if(playerS2 > 21) {
 	     	   if(playerS1 > 21) {
 	     		   System.out.println("You lost!\n");
 	     		   winner = 1;
 	     	   }
 	     	   else if(playerS1 <= 21 && playerS1 < dealerMaxSum) {
 	     		   System.out.println("You lost!\n");
 	     		   winner = 1;
 	     	   }
 	     	   else if(playerS1 <= 21 && playerS1 > dealerMaxSum) {
 	     		   System.out.println("You won!\n");
 	     		   winner = 0;
 	     	   }
 	     	   else if(playerS1 <= 21 && playerS1 == dealerMaxSum) { 
 	     		   System.out.println("Tie!\n");
 	     		   winner = 2;
 	     	   }
 	        }
 	        else if(playerS2 == 21) {
 	     	   if(playerS2 > dealerMaxSum || dealerMaxSum > 21) {
 	     		   System.out.println("You won!\n");
 	     		   winner = 0;
 	     	   }
 	     	   else if(dealerMaxSum == 21) {
 	     		   System.out.println("Tie!\n");
 	     		   winner = 2;
 	     	   }
 	        }
 	        else if(playerS2 < 21) {
 	     	   if(dealerMaxSum > 21) {
 	     		   System.out.println("You won!\n");
 	     		   winner = 0;
 	     	   }
 	     	   else if(playerS2 > dealerMaxSum) {
 	     		   System.out.println("You won!\n");
 	     		   winner = 0;
 	     	   }
 	     	   else if(playerS2 < dealerMaxSum) {
 	     		   System.out.println("You lost!\n");
 	     		   winner = 1;
 	     	   }
 	     	   else if(playerS2 == dealerMaxSum) {
 	     		   System.out.println("Tie!\n");
 	     		   winner = 2;
 	     	   }
 	        }
 	}
 	
    public static void main(String[] args) {

    	//Main instance = new Main();
    	
        
        
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Main();
            }
        });
    }
}
Leave a Comment