feat: add deck to blackjack game instead of random cards #96
2 changed files with 27 additions and 8 deletions
|
@ -36,6 +36,10 @@ public class BlackJackGameEntity {
|
||||||
private String state;
|
private String state;
|
||||||
private BigDecimal bet;
|
private BigDecimal bet;
|
||||||
|
|
||||||
|
@OneToMany(mappedBy = "game", cascade = CascadeType.ALL, orphanRemoval = true)
|
||||||
|
@JsonIgnore
|
||||||
|
private List<CardEntity> deck = new ArrayList<>();
|
||||||
|
|
||||||
@OneToMany(mappedBy = "game", cascade = CascadeType.ALL, orphanRemoval = true)
|
@OneToMany(mappedBy = "game", cascade = CascadeType.ALL, orphanRemoval = true)
|
||||||
@JsonManagedReference
|
@JsonManagedReference
|
||||||
private List<CardEntity> playerCards = new ArrayList<>();
|
private List<CardEntity> playerCards = new ArrayList<>();
|
||||||
|
|
|
@ -24,13 +24,14 @@ public class BlackJackService {
|
||||||
game.setUser(user);
|
game.setUser(user);
|
||||||
game.setBet(betAmount);
|
game.setBet(betAmount);
|
||||||
game.setState("IN_PROGRESS");
|
game.setState("IN_PROGRESS");
|
||||||
|
initializeDeck(game);
|
||||||
|
|
||||||
for (int i = 0; i < 2; i++) {
|
for (int i = 0; i < 2; i++) {
|
||||||
CardEntity playerCard = createRandomCard(game);
|
CardEntity playerCard = drawCardFromDeck(game);
|
||||||
game.getPlayerCards().add(playerCard);
|
game.getPlayerCards().add(playerCard);
|
||||||
}
|
}
|
||||||
|
|
||||||
CardEntity dealerCard = createRandomCard(game);
|
CardEntity dealerCard = drawCardFromDeck(game);
|
||||||
game.getDealerCards().add(dealerCard);
|
game.getDealerCards().add(dealerCard);
|
||||||
|
|
||||||
user.setBalance(user.getBalance().subtract(betAmount));
|
user.setBalance(user.getBalance().subtract(betAmount));
|
||||||
|
@ -41,11 +42,25 @@ public class BlackJackService {
|
||||||
return game;
|
return game;
|
||||||
}
|
}
|
||||||
|
|
||||||
private CardEntity createRandomCard(BlackJackGameEntity game) {
|
private void initializeDeck(BlackJackGameEntity game) {
|
||||||
|
for (Suit suit : Suit.values()) {
|
||||||
|
for (Rank rank : Rank.values()) {
|
||||||
CardEntity card = new CardEntity();
|
CardEntity card = new CardEntity();
|
||||||
card.setGame(game);
|
card.setGame(game);
|
||||||
card.setSuit(Suit.values()[random.nextInt(Suit.values().length)]);
|
card.setSuit(suit);
|
||||||
card.setRank(Rank.values()[random.nextInt(Rank.values().length)]);
|
card.setRank(rank);
|
||||||
return card;
|
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();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue