From 55daca72c054a6069c30d099910110f5b7307747 Mon Sep 17 00:00:00 2001
From: Phan Huy Tran
Date: Thu, 27 Mar 2025 11:40:50 +0100
Subject: [PATCH] feat: add deck to blackjack game instead of random cards
---
.../casino/blackjack/BlackJackGameEntity.java | 4 +++
.../casino/blackjack/BlackJackService.java | 31 ++++++++++++++-----
2 files changed, 27 insertions(+), 8 deletions(-)
diff --git a/backend/src/main/java/de/szut/casino/blackjack/BlackJackGameEntity.java b/backend/src/main/java/de/szut/casino/blackjack/BlackJackGameEntity.java
index e3380a7..112e9f0 100644
--- a/backend/src/main/java/de/szut/casino/blackjack/BlackJackGameEntity.java
+++ b/backend/src/main/java/de/szut/casino/blackjack/BlackJackGameEntity.java
@@ -36,6 +36,10 @@ public class BlackJackGameEntity {
private String state;
private BigDecimal bet;
+ @OneToMany(mappedBy = "game", cascade = CascadeType.ALL, orphanRemoval = true)
+ @JsonIgnore
+ private List deck = new ArrayList<>();
+
@OneToMany(mappedBy = "game", cascade = CascadeType.ALL, orphanRemoval = true)
@JsonManagedReference
private List playerCards = new ArrayList<>();
diff --git a/backend/src/main/java/de/szut/casino/blackjack/BlackJackService.java b/backend/src/main/java/de/szut/casino/blackjack/BlackJackService.java
index cca78e4..44e5858 100644
--- a/backend/src/main/java/de/szut/casino/blackjack/BlackJackService.java
+++ b/backend/src/main/java/de/szut/casino/blackjack/BlackJackService.java
@@ -24,13 +24,14 @@ public class BlackJackService {
game.setUser(user);
game.setBet(betAmount);
game.setState("IN_PROGRESS");
+ initializeDeck(game);
for (int i = 0; i < 2; i++) {
- CardEntity playerCard = createRandomCard(game);
+ CardEntity playerCard = drawCardFromDeck(game);
game.getPlayerCards().add(playerCard);
}
- CardEntity dealerCard = createRandomCard(game);
+ CardEntity dealerCard = drawCardFromDeck(game);
game.getDealerCards().add(dealerCard);
user.setBalance(user.getBalance().subtract(betAmount));
@@ -41,11 +42,25 @@ public class BlackJackService {
return game;
}
- private CardEntity createRandomCard(BlackJackGameEntity game) {
- CardEntity card = new CardEntity();
- card.setGame(game);
- card.setSuit(Suit.values()[random.nextInt(Suit.values().length)]);
- card.setRank(Rank.values()[random.nextInt(Rank.values().length)]);
- return card;
+ private void initializeDeck(BlackJackGameEntity game) {
+ for (Suit suit : Suit.values()) {
+ for (Rank rank : Rank.values()) {
+ CardEntity card = new CardEntity();
+ card.setGame(game);
+ card.setSuit(suit);
+ card.setRank(rank);
+ game.getDeck().add(card);
+ }
+ }
+
+ java.util.Collections.shuffle(game.getDeck(), random);
+ }
+
+ private CardEntity drawCardFromDeck(BlackJackGameEntity game) {
+ if (game.getDeck().isEmpty()) {
+ throw new IllegalStateException("Deck is empty");
+ }
+
+ return game.getDeck().removeFirst();
}
}