-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlackjackGUI.java
More file actions
428 lines (399 loc) · 14.1 KB
/
Copy pathBlackjackGUI.java
File metadata and controls
428 lines (399 loc) · 14.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import java.io.PrintWriter;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.BufferedReader;
class Card {
String suit;
String rank;
int value;
Card(String suit, String rank, int value) {
this.suit = suit;
this.rank = rank;
this.value = value;
}
public String toString() {
return rank + " of " + suit;
}
public String getImageFileName() {
String r = rank.toLowerCase();
if (r.equals("j")) r = "j";
if (r.equals("q")) r = "q";
if (r.equals("k")) r = "k";
if (r.equals("a")) r = "a";
return r + "_of_" + suit.toLowerCase() + ".png";
}
}
class Deck {
private List<Card> cards = new ArrayList<>();
private static final String[] suits = {"Hearts", "Diamonds", "Clubs", "Spades"};
private static final String[] ranks = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};
private static final Map<String, Integer> values = new HashMap<>();
static {
values.put("2", 2);
values.put("3", 3);
values.put("4", 4);
values.put("5", 5);
values.put("6", 6);
values.put("7", 7);
values.put("8", 8);
values.put("9", 9);
values.put("10", 10);
values.put("J", 10);
values.put("Q", 10);
values.put("K", 10);
values.put("A", 11);
}
Deck() {
for (String suit : suits) {
for (String rank : ranks) {
cards.add(new Card(suit, rank, values.get(rank)));
}
}
java.util.Collections.shuffle(cards);
}
Card deal() {
return cards.remove(cards.size() - 1);
}
}
class Hand {
List<Card> cards = new ArrayList<>();
void addCard(Card card) {
cards.add(card);
}
int getValue() {
int value = 0;
int aces = 0;
for (Card card : cards) {
value += card.value;
if (card.rank.equals("A")) aces++;
}
while (value > 21 && aces > 0) {
value -= 10;
aces--;
}
return value;
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (Card card : cards) sb.append(card.toString()).append(", ");
return sb.toString();
}
}
public class BlackjackGUI extends JFrame {
private Deck deck;
private Hand playerHand;
private Hand dealerHand;
private JPanel playerPanel, dealerPanel;
private JLabel statusLabel;
private JButton hitButton, standButton, restartButton;
private JPanel bettingPanel;
private JLabel balanceLabel, betLabel;
private JButton bet10Button, bet50Button, bet100Button, splitButton, doubleDownButton;
private int playerBalance = 1000;
private static final String BALANCE_FILE = "balance.txt";
private int currentBet = 0;
private boolean bettingOpen = true;
private static final int CARD_WIDTH = 100;
private static final int CARD_HEIGHT = 150;
public BlackjackGUI() {
loadBalance();
setTitle("Blackjack");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(800, 600);
setLayout(new BorderLayout());
// Center panels for cards
JPanel centerPanel = new JPanel(new GridLayout(2, 1));
dealerPanel = new JPanel();
playerPanel = new JPanel();
Color tableGreen = new Color(0, 102, 0);
dealerPanel.setBackground(tableGreen);
playerPanel.setBackground(tableGreen);
centerPanel.setBackground(tableGreen);
centerPanel.add(dealerPanel); // Dealer on top
centerPanel.add(playerPanel); // Player on bottom
add(centerPanel, BorderLayout.CENTER);
// Status and balance
JPanel topPanel = new JPanel(new GridLayout(2, 1));
statusLabel = new JLabel("", SwingConstants.CENTER);
statusLabel.setFont(new Font("Arial", Font.BOLD, 28));
statusLabel.setForeground(new Color(255, 215, 0)); // Gold color for visibility
balanceLabel = new JLabel();
betLabel = new JLabel();
topPanel.add(statusLabel);
topPanel.add(balanceLabel);
add(topPanel, BorderLayout.NORTH);
// Betting panel
bettingPanel = new JPanel();
bettingPanel.setBackground(tableGreen);
bet10Button = new JButton("Bet $10");
bet50Button = new JButton("Bet $50");
bet100Button = new JButton("Bet $100");
bettingPanel.add(new JLabel("Place your bet: "));
bettingPanel.add(bet10Button);
bettingPanel.add(bet50Button);
bettingPanel.add(bet100Button);
bettingPanel.add(betLabel);
add(bettingPanel, BorderLayout.WEST);
// Action buttons
hitButton = new JButton("Hit");
standButton = new JButton("Stand");
restartButton = new JButton("Restart");
splitButton = new JButton("Split");
doubleDownButton = new JButton("Double Down");
JPanel buttonPanel = new JPanel();
buttonPanel.setBackground(tableGreen);
buttonPanel.add(hitButton);
buttonPanel.add(standButton);
buttonPanel.add(splitButton);
buttonPanel.add(doubleDownButton);
buttonPanel.add(restartButton);
add(buttonPanel, BorderLayout.SOUTH);
// Listeners
hitButton.addActionListener(e -> hit());
standButton.addActionListener(e -> stand());
restartButton.addActionListener(e -> startGame());
bet10Button.addActionListener(e -> placeBet(10));
bet50Button.addActionListener(e -> placeBet(50));
bet100Button.addActionListener(e -> placeBet(100));
splitButton.addActionListener(e -> split());
doubleDownButton.addActionListener(e -> doubleDown());
startGame();
}
private void startGame() {
deck = new Deck();
playerHand = new Hand();
dealerHand = new Hand();
statusLabel.setText("");
// Do NOT reset playerBalance here, so winnings persist
currentBet = 0;
bettingOpen = true;
updateBalanceLabel();
updateBetLabel();
enableBetting(true);
updateUI(true);
hitButton.setEnabled(false);
standButton.setEnabled(false);
splitButton.setEnabled(false);
doubleDownButton.setEnabled(false);
}
private void updateUI(boolean hideDealer) {
playerPanel.removeAll();
dealerPanel.removeAll();
playerPanel.add(new JLabel("Player Hand (" + playerHand.getValue() + "):"));
for (Card card : playerHand.cards) {
playerPanel.add(new JLabel(getCardIcon(card)));
}
dealerPanel.add(new JLabel("Dealer Hand:" + (hideDealer ? " ?" : " " + dealerHand.getValue())));
for (int i = 0; i < dealerHand.cards.size(); i++) {
if (i == 0 || !hideDealer) {
dealerPanel.add(new JLabel(getCardIcon(dealerHand.cards.get(i))));
} else {
dealerPanel.add(new JLabel(getBackIcon()));
}
}
playerPanel.revalidate();
playerPanel.repaint();
dealerPanel.revalidate();
dealerPanel.repaint();
}
private void updateBalanceLabel() {
balanceLabel.setText("Balance: $" + playerBalance);
saveBalance();
}
private void saveBalance() {
try (PrintWriter out = new PrintWriter(new FileWriter(BALANCE_FILE))) {
out.println(playerBalance);
} catch (Exception e) {
// ignore
}
}
private void loadBalance() {
try (BufferedReader in = new BufferedReader(new FileReader(BALANCE_FILE))) {
String line = in.readLine();
if (line != null) {
playerBalance = Integer.parseInt(line.trim());
}
} catch (Exception e) {
playerBalance = 1000; // default if file missing or error
}
}
private void updateBetLabel() {
betLabel.setText("Current Bet: $" + currentBet);
}
private void enableBetting(boolean enable) {
bet10Button.setEnabled(enable);
bet50Button.setEnabled(enable);
bet100Button.setEnabled(enable);
bettingOpen = enable;
}
private void placeBet(int amount) {
if (!bettingOpen) return;
if (playerBalance < amount) {
statusLabel.setText("Not enough balance to bet $" + amount);
return;
}
currentBet = amount;
playerBalance -= amount;
updateBalanceLabel();
updateBetLabel();
enableBetting(false);
// Deal cards and enable actions
playerHand = new Hand();
dealerHand = new Hand();
playerHand.addCard(deck.deal());
playerHand.addCard(deck.deal());
dealerHand.addCard(deck.deal());
dealerHand.addCard(deck.deal());
updateUI(true);
hitButton.setEnabled(true);
standButton.setEnabled(true);
// Enable split if two cards of same rank
splitButton.setEnabled(playerHand.cards.size() == 2 && playerHand.cards.get(0).rank.equals(playerHand.cards.get(1).rank));
doubleDownButton.setEnabled(true);
statusLabel.setText("");
}
private ImageIcon getCardIcon(Card card) {
String path = "cards/" + card.getImageFileName();
File file = new File(path);
if (!file.exists()) {
generateCardImage(card, path);
}
try {
BufferedImage img = ImageIO.read(new File(path));
return new ImageIcon(img.getScaledInstance(CARD_WIDTH, CARD_HEIGHT, Image.SCALE_SMOOTH));
} catch (IOException e) {
return new ImageIcon();
}
}
private ImageIcon getBackIcon() {
String path = "cards/back.png";
File file = new File(path);
if (!file.exists()) {
generateBackImage(path);
}
try {
BufferedImage img = ImageIO.read(new File(path));
return new ImageIcon(img.getScaledInstance(CARD_WIDTH, CARD_HEIGHT, Image.SCALE_SMOOTH));
} catch (IOException e) {
return new ImageIcon();
}
}
private void generateCardImage(Card card, String path) {
BufferedImage img = new BufferedImage(CARD_WIDTH, CARD_HEIGHT, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = img.createGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, CARD_WIDTH, CARD_HEIGHT);
g.setColor(Color.BLACK);
g.drawRect(0, 0, CARD_WIDTH - 1, CARD_HEIGHT - 1);
g.setFont(new Font("Arial", Font.BOLD, 24));
String rank = card.rank;
String suit = card.suit;
String suitSymbol = getSuitSymbol(suit);
g.drawString(rank, 10, 30);
g.drawString(suitSymbol, 10, 60);
g.drawString(rank, CARD_WIDTH - 30, CARD_HEIGHT - 10);
g.drawString(suitSymbol, CARD_WIDTH - 30, CARD_HEIGHT - 40);
g.setFont(new Font("Arial", Font.PLAIN, 60));
g.drawString(suitSymbol, CARD_WIDTH / 2 - 20, CARD_HEIGHT / 2 + 20);
g.dispose();
try {
ImageIO.write(img, "png", new File(path));
} catch (IOException e) {
// ignore
}
}
private void generateBackImage(String path) {
BufferedImage img = new BufferedImage(CARD_WIDTH, CARD_HEIGHT, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = img.createGraphics();
g.setColor(Color.LIGHT_GRAY);
g.fillRect(0, 0, CARD_WIDTH, CARD_HEIGHT);
g.setColor(Color.BLUE);
g.setFont(new Font("Arial", Font.BOLD, 40));
g.drawString("BJ", CARD_WIDTH / 2 - 30, CARD_HEIGHT / 2 + 15);
g.dispose();
try {
ImageIO.write(img, "png", new File(path));
} catch (IOException e) {
// ignore
}
}
private String getSuitSymbol(String suit) {
switch (suit) {
case "Hearts": return "♥";
case "Diamonds": return "♦";
case "Clubs": return "♣";
case "Spades": return "♠";
default: return "?";
}
}
private void hit() {
playerHand.addCard(deck.deal());
updateUI(true);
if (playerHand.getValue() > 21) {
statusLabel.setText("Player busts! Dealer wins.");
hitButton.setEnabled(false);
standButton.setEnabled(false);
splitButton.setEnabled(false);
doubleDownButton.setEnabled(false);
updateUI(false);
}
}
private void stand() {
hitButton.setEnabled(false);
standButton.setEnabled(false);
splitButton.setEnabled(false);
doubleDownButton.setEnabled(false);
while (dealerHand.getValue() < 17) {
dealerHand.addCard(deck.deal());
}
updateUI(false);
int playerValue = playerHand.getValue();
int dealerValue = dealerHand.getValue();
if (dealerValue > 21) {
statusLabel.setText("Dealer busts! Player wins.");
playerBalance += currentBet * 2;
} else if (dealerValue > playerValue) {
statusLabel.setText("Dealer wins.");
} else if (dealerValue < playerValue) {
statusLabel.setText("Player wins!");
playerBalance += currentBet * 2;
} else {
statusLabel.setText("Push (Tie).");
playerBalance += currentBet;
}
updateBalanceLabel();
}
private void split() {
// Placeholder for split logic
statusLabel.setText("Split not yet implemented.");
}
private void doubleDown() {
if (playerBalance < currentBet) {
statusLabel.setText("Not enough balance to double down.");
return;
}
playerBalance -= currentBet;
currentBet *= 2;
updateBalanceLabel();
updateBetLabel();
hit();
if (playerHand.getValue() <= 21) {
stand();
}
doubleDownButton.setEnabled(false);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new BlackjackGUI().setVisible(true));
}
}