Merge pull request 'feat(blackjack): add split functionality to the game' (!116) from task/CAS-50/add_rest_blackjack_logic_with_frontend_animations into main
All checks were successful
Release / Release (push) Successful in 48s
All checks were successful
Release / Release (push) Successful in 48s
Reviewed-on: #116 Reviewed-by: Jan K9f <jan@kjan.email>
This commit is contained in:
commit
5d15f40a30
7 changed files with 409 additions and 277 deletions
|
@ -94,6 +94,23 @@ public class BlackJackGameController {
|
||||||
return ResponseEntity.ok(blackJackService.doubleDown(game));
|
return ResponseEntity.ok(blackJackService.doubleDown(game));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@PostMapping("/blackjack/{id}/split")
|
||||||
|
public ResponseEntity<Object> split(@PathVariable Long id, @RequestHeader("Authorization") String token) {
|
||||||
|
Optional<UserEntity> optionalUser = userService.getCurrentUser(token);
|
||||||
|
|
||||||
|
if (optionalUser.isEmpty()) {
|
||||||
|
return ResponseEntity.notFound().build();
|
||||||
|
}
|
||||||
|
|
||||||
|
UserEntity user = optionalUser.get();
|
||||||
|
BlackJackGameEntity game = blackJackService.getBlackJackGame(id);
|
||||||
|
if (game == null || !Objects.equals(game.getUserId(), user.getId())) {
|
||||||
|
return ResponseEntity.notFound().build();
|
||||||
|
}
|
||||||
|
|
||||||
|
return ResponseEntity.ok(blackJackService.split(game));
|
||||||
|
}
|
||||||
|
|
||||||
@PostMapping("/blackjack/start")
|
@PostMapping("/blackjack/start")
|
||||||
public ResponseEntity<Object> createBlackJackGame(@RequestBody @Valid CreateBlackJackGameDto createBlackJackGameDto, @RequestHeader("Authorization") String token) {
|
public ResponseEntity<Object> createBlackJackGame(@RequestBody @Valid CreateBlackJackGameDto createBlackJackGameDto, @RequestHeader("Authorization") String token) {
|
||||||
Optional<UserEntity> optionalUser = userService.getCurrentUser(token);
|
Optional<UserEntity> optionalUser = userService.getCurrentUser(token);
|
||||||
|
|
|
@ -51,4 +51,15 @@ public class BlackJackGameEntity {
|
||||||
@JsonManagedReference
|
@JsonManagedReference
|
||||||
@SQLRestriction("card_type = 'DEALER'")
|
@SQLRestriction("card_type = 'DEALER'")
|
||||||
private List<CardEntity> dealerCards = new ArrayList<>();
|
private List<CardEntity> dealerCards = new ArrayList<>();
|
||||||
|
|
||||||
|
@OneToMany(mappedBy = "game", cascade = CascadeType.ALL, orphanRemoval = true)
|
||||||
|
@JsonManagedReference
|
||||||
|
@SQLRestriction("card_type = 'PLAYER_SPLIT'")
|
||||||
|
private List<CardEntity> playerSplitCards = new ArrayList<>();
|
||||||
|
|
||||||
|
@Column(name = "split_bet")
|
||||||
|
private BigDecimal splitBet;
|
||||||
|
|
||||||
|
@Column(name = "is_split")
|
||||||
|
private boolean isSplit;
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,245 +1,314 @@
|
||||||
package de.szut.casino.blackjack;
|
package de.szut.casino.blackjack;
|
||||||
|
|
||||||
import de.szut.casino.user.UserEntity;
|
import de.szut.casino.user.UserEntity;
|
||||||
import de.szut.casino.user.UserRepository;
|
import de.szut.casino.user.UserRepository;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
import java.math.BigDecimal;
|
import java.math.BigDecimal;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import java.util.Random;
|
import java.util.Random;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
public class BlackJackService {
|
public class BlackJackService {
|
||||||
private final BlackJackGameRepository blackJackGameRepository;
|
private final BlackJackGameRepository blackJackGameRepository;
|
||||||
private final UserRepository userRepository;
|
private final UserRepository userRepository;
|
||||||
private final Random random = new Random();
|
private final Random random = new Random();
|
||||||
|
|
||||||
public BlackJackService(BlackJackGameRepository blackJackGameRepository, UserRepository userRepository) {
|
public BlackJackService(BlackJackGameRepository blackJackGameRepository, UserRepository userRepository) {
|
||||||
this.blackJackGameRepository = blackJackGameRepository;
|
this.blackJackGameRepository = blackJackGameRepository;
|
||||||
this.userRepository = userRepository;
|
this.userRepository = userRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
public BlackJackGameEntity getBlackJackGame(Long id) {
|
public BlackJackGameEntity getBlackJackGame(Long id) {
|
||||||
return blackJackGameRepository.findById(id).orElse(null);
|
return blackJackGameRepository.findById(id).orElse(null);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
public BlackJackGameEntity createBlackJackGame(UserEntity user, BigDecimal betAmount) {
|
public BlackJackGameEntity createBlackJackGame(UserEntity user, BigDecimal betAmount) {
|
||||||
BlackJackGameEntity game = new BlackJackGameEntity();
|
BlackJackGameEntity game = new BlackJackGameEntity();
|
||||||
game.setUser(user);
|
game.setUser(user);
|
||||||
game.setBet(betAmount);
|
game.setBet(betAmount);
|
||||||
|
|
||||||
initializeDeck(game);
|
initializeDeck(game);
|
||||||
dealInitialCards(game);
|
dealInitialCards(game);
|
||||||
|
|
||||||
game.setState(getState(game));
|
game.setState(getState(game));
|
||||||
deductBetFromBalance(user, betAmount);
|
deductBetFromBalance(user, betAmount);
|
||||||
|
|
||||||
return blackJackGameRepository.save(game);
|
return blackJackGameRepository.save(game);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
public BlackJackGameEntity hit(BlackJackGameEntity game) {
|
public BlackJackGameEntity hit(BlackJackGameEntity game) {
|
||||||
game = refreshGameState(game);
|
if (game.getState() != BlackJackState.IN_PROGRESS) {
|
||||||
|
return game;
|
||||||
if (game.getState() != BlackJackState.IN_PROGRESS) {
|
}
|
||||||
return game;
|
|
||||||
}
|
dealCardToPlayer(game);
|
||||||
|
|
||||||
dealCardToPlayer(game);
|
updateGameStateAndBalance(game);
|
||||||
updateGameStateAndBalance(game);
|
|
||||||
|
return blackJackGameRepository.save(game);
|
||||||
return blackJackGameRepository.save(game);
|
}
|
||||||
}
|
|
||||||
|
@Transactional
|
||||||
@Transactional
|
public BlackJackGameEntity stand(BlackJackGameEntity game) {
|
||||||
public BlackJackGameEntity stand(BlackJackGameEntity game) {
|
if (game.getState() != BlackJackState.IN_PROGRESS) {
|
||||||
game = refreshGameState(game);
|
return game;
|
||||||
|
}
|
||||||
if (game.getState() != BlackJackState.IN_PROGRESS) {
|
|
||||||
return game;
|
dealCardsToDealerUntilMinimumScore(game);
|
||||||
}
|
determineWinnerAndUpdateBalance(game);
|
||||||
|
|
||||||
dealCardsToDealerUntilMinimumScore(game);
|
return blackJackGameRepository.save(game);
|
||||||
determineWinnerAndUpdateBalance(game);
|
}
|
||||||
|
|
||||||
return blackJackGameRepository.save(game);
|
@Transactional
|
||||||
}
|
public BlackJackGameEntity doubleDown(BlackJackGameEntity game) {
|
||||||
|
if (game.getState() != BlackJackState.IN_PROGRESS || game.getPlayerCards().size() != 2) {
|
||||||
@Transactional
|
return game;
|
||||||
public BlackJackGameEntity doubleDown(BlackJackGameEntity game) {
|
}
|
||||||
game = refreshGameState(game);
|
|
||||||
|
UserEntity user = getUserWithFreshData(game.getUser());
|
||||||
if (game.getState() != BlackJackState.IN_PROGRESS || game.getPlayerCards().size() != 2) {
|
BigDecimal additionalBet = game.getBet();
|
||||||
return game;
|
|
||||||
}
|
if (user.getBalance().compareTo(additionalBet) < 0) {
|
||||||
|
return game;
|
||||||
UserEntity user = getUserWithFreshData(game.getUser());
|
}
|
||||||
BigDecimal additionalBet = game.getBet();
|
|
||||||
|
deductBetFromBalance(user, additionalBet);
|
||||||
if (user.getBalance().compareTo(additionalBet) < 0) {
|
game.setBet(game.getBet().add(additionalBet));
|
||||||
return game;
|
|
||||||
}
|
dealCardToPlayer(game);
|
||||||
|
updateGameStateAndBalance(game);
|
||||||
deductBetFromBalance(user, additionalBet);
|
|
||||||
game.setBet(game.getBet().add(additionalBet));
|
if (game.getState() == BlackJackState.IN_PROGRESS) {
|
||||||
|
return stand(game);
|
||||||
dealCardToPlayer(game);
|
}
|
||||||
updateGameStateAndBalance(game);
|
|
||||||
|
return game;
|
||||||
if (game.getState() == BlackJackState.IN_PROGRESS) {
|
}
|
||||||
return stand(game);
|
|
||||||
}
|
@Transactional
|
||||||
|
public BlackJackGameEntity split(BlackJackGameEntity game) {
|
||||||
return game;
|
if (game.getState() != BlackJackState.IN_PROGRESS ||
|
||||||
}
|
game.getPlayerCards().size() != 2 ||
|
||||||
|
game.isSplit() ||
|
||||||
private BlackJackGameEntity refreshGameState(BlackJackGameEntity game) {
|
!game.getPlayerCards().get(0).getRank().equals(game.getPlayerCards().get(1).getRank())) {
|
||||||
return blackJackGameRepository.findById(game.getId()).orElse(game);
|
return game;
|
||||||
}
|
}
|
||||||
|
|
||||||
private UserEntity getUserWithFreshData(UserEntity user) {
|
UserEntity user = getUserWithFreshData(game.getUser());
|
||||||
return userRepository.findById(user.getId()).orElse(user);
|
BigDecimal splitBet = game.getBet();
|
||||||
}
|
|
||||||
|
if (user.getBalance().compareTo(splitBet) < 0) {
|
||||||
private void dealInitialCards(BlackJackGameEntity game) {
|
return game;
|
||||||
for (int i = 0; i < 2; i++) {
|
}
|
||||||
dealCardToPlayer(game);
|
|
||||||
}
|
deductBetFromBalance(user, splitBet);
|
||||||
|
game.setSplitBet(splitBet);
|
||||||
dealCardToDealer(game);
|
game.setSplit(true);
|
||||||
}
|
|
||||||
|
CardEntity card = game.getPlayerCards().remove(1);
|
||||||
private void dealCardToPlayer(BlackJackGameEntity game) {
|
card.setCardType(CardType.PLAYER_SPLIT);
|
||||||
CardEntity card = drawCardFromDeck(game);
|
game.getPlayerSplitCards().add(card);
|
||||||
card.setCardType(CardType.PLAYER);
|
|
||||||
game.getPlayerCards().add(card);
|
dealCardToPlayer(game);
|
||||||
}
|
dealCardToSplitHand(game);
|
||||||
|
|
||||||
private void dealCardToDealer(BlackJackGameEntity game) {
|
return blackJackGameRepository.save(game);
|
||||||
CardEntity card = drawCardFromDeck(game);
|
}
|
||||||
card.setCardType(CardType.DEALER);
|
|
||||||
game.getDealerCards().add(card);
|
private BlackJackGameEntity refreshGameState(BlackJackGameEntity game) {
|
||||||
}
|
return blackJackGameRepository.findById(game.getId()).orElse(game);
|
||||||
|
}
|
||||||
private void dealCardsToDealerUntilMinimumScore(BlackJackGameEntity game) {
|
|
||||||
while (calculateHandValue(game.getDealerCards()) < 17) {
|
private UserEntity getUserWithFreshData(UserEntity user) {
|
||||||
dealCardToDealer(game);
|
return userRepository.findById(user.getId()).orElse(user);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
private void dealInitialCards(BlackJackGameEntity game) {
|
||||||
private void updateGameStateAndBalance(BlackJackGameEntity game) {
|
for (int i = 0; i < 2; i++) {
|
||||||
game.setState(getState(game));
|
dealCardToPlayer(game);
|
||||||
|
}
|
||||||
if (game.getState() == BlackJackState.PLAYER_WON) {
|
|
||||||
updateUserBalance(game, true);
|
dealCardToDealer(game);
|
||||||
} else if (game.getState() == BlackJackState.PLAYER_LOST) {
|
}
|
||||||
updateUserBalance(game, false);
|
|
||||||
}
|
private void dealCardToPlayer(BlackJackGameEntity game) {
|
||||||
}
|
CardEntity card = drawCardFromDeck(game);
|
||||||
|
card.setCardType(CardType.PLAYER);
|
||||||
private void determineWinnerAndUpdateBalance(BlackJackGameEntity game) {
|
game.getPlayerCards().add(card);
|
||||||
int playerValue = calculateHandValue(game.getPlayerCards());
|
}
|
||||||
int dealerValue = calculateHandValue(game.getDealerCards());
|
|
||||||
|
private void dealCardToDealer(BlackJackGameEntity game) {
|
||||||
if (dealerValue > 21 || playerValue > dealerValue) {
|
CardEntity card = drawCardFromDeck(game);
|
||||||
game.setState(BlackJackState.PLAYER_WON);
|
card.setCardType(CardType.DEALER);
|
||||||
updateUserBalance(game, true);
|
game.getDealerCards().add(card);
|
||||||
} else if (playerValue < dealerValue) {
|
}
|
||||||
game.setState(BlackJackState.PLAYER_LOST);
|
|
||||||
updateUserBalance(game, false);
|
private void dealCardsToDealerUntilMinimumScore(BlackJackGameEntity game) {
|
||||||
} else {
|
while (calculateHandValue(game.getDealerCards()) < 17) {
|
||||||
game.setState(BlackJackState.DRAW);
|
dealCardToDealer(game);
|
||||||
updateUserBalance(game, false); // For draw, player gets their bet back
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
private void dealCardToSplitHand(BlackJackGameEntity game) {
|
||||||
private void deductBetFromBalance(UserEntity user, BigDecimal betAmount) {
|
CardEntity card = drawCardFromDeck(game);
|
||||||
user.setBalance(user.getBalance().subtract(betAmount));
|
card.setCardType(CardType.PLAYER_SPLIT);
|
||||||
userRepository.save(user);
|
game.getPlayerSplitCards().add(card);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional
|
private void updateGameStateAndBalance(BlackJackGameEntity game) {
|
||||||
private void updateUserBalance(BlackJackGameEntity game, boolean isWin) {
|
if (game.isSplit()) {
|
||||||
UserEntity user = getUserWithFreshData(game.getUser());
|
int mainHandValue = calculateHandValue(game.getPlayerCards());
|
||||||
BigDecimal betAmount = game.getBet();
|
int splitHandValue = calculateHandValue(game.getPlayerSplitCards());
|
||||||
BigDecimal balance = user.getBalance();
|
|
||||||
|
if (mainHandValue > 21 && splitHandValue > 21) {
|
||||||
if (isWin) {
|
game.setState(BlackJackState.PLAYER_LOST);
|
||||||
balance = balance.add(betAmount.multiply(BigDecimal.valueOf(2)));
|
updateUserBalance(game, false);
|
||||||
} else if (game.getState() == BlackJackState.DRAW) {
|
} else if (mainHandValue <= 21 && splitHandValue <= 21) {
|
||||||
balance = balance.add(betAmount);
|
game.setState(BlackJackState.IN_PROGRESS);
|
||||||
}
|
} else {
|
||||||
|
game.setState(BlackJackState.IN_PROGRESS);
|
||||||
user.setBalance(balance);
|
}
|
||||||
userRepository.save(user);
|
} else {
|
||||||
}
|
game.setState(getState(game));
|
||||||
|
|
||||||
private void initializeDeck(BlackJackGameEntity game) {
|
if (game.getState() == BlackJackState.PLAYER_WON) {
|
||||||
for (Suit suit : Suit.values()) {
|
updateUserBalance(game, true);
|
||||||
for (Rank rank : Rank.values()) {
|
} else if (game.getState() == BlackJackState.PLAYER_LOST) {
|
||||||
CardEntity card = new CardEntity();
|
updateUserBalance(game, false);
|
||||||
card.setGame(game);
|
}
|
||||||
card.setSuit(suit);
|
}
|
||||||
card.setRank(rank);
|
}
|
||||||
card.setCardType(CardType.DECK);
|
|
||||||
game.getDeck().add(card);
|
private void determineWinnerAndUpdateBalance(BlackJackGameEntity game) {
|
||||||
}
|
int playerValue = calculateHandValue(game.getPlayerCards());
|
||||||
}
|
int dealerValue = calculateHandValue(game.getDealerCards());
|
||||||
|
|
||||||
java.util.Collections.shuffle(game.getDeck(), random);
|
if (dealerValue > 21 || playerValue > dealerValue) {
|
||||||
}
|
game.setState(BlackJackState.PLAYER_WON);
|
||||||
|
updateUserBalance(game, true);
|
||||||
private CardEntity drawCardFromDeck(BlackJackGameEntity game) {
|
} else if (playerValue < dealerValue) {
|
||||||
if (game.getDeck().isEmpty()) {
|
game.setState(BlackJackState.PLAYER_LOST);
|
||||||
throw new IllegalStateException("Deck is empty");
|
updateUserBalance(game, false);
|
||||||
}
|
} else {
|
||||||
|
game.setState(BlackJackState.DRAW);
|
||||||
return game.getDeck().removeFirst();
|
updateUserBalance(game, false);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
private BlackJackState getState(BlackJackGameEntity game) {
|
|
||||||
int playerHandValue = calculateHandValue(game.getPlayerCards());
|
private void deductBetFromBalance(UserEntity user, BigDecimal betAmount) {
|
||||||
|
user.setBalance(user.getBalance().subtract(betAmount));
|
||||||
if (playerHandValue == 21) {
|
userRepository.save(user);
|
||||||
CardEntity hole = drawCardFromDeck(game);
|
}
|
||||||
hole.setCardType(CardType.DEALER);
|
|
||||||
game.getDealerCards().add(hole);
|
@Transactional
|
||||||
|
private void updateUserBalance(BlackJackGameEntity game, boolean isWin) {
|
||||||
int dealerHandValue = calculateHandValue(game.getDealerCards());
|
UserEntity user = getUserWithFreshData(game.getUser());
|
||||||
|
BigDecimal totalBet = game.getBet();
|
||||||
if (dealerHandValue == 21) {
|
BigDecimal balance = user.getBalance();
|
||||||
return BlackJackState.DRAW;
|
|
||||||
} else {
|
if (game.isSplit()) {
|
||||||
BigDecimal blackjackWinnings = game.getBet().multiply(new BigDecimal("1.5"));
|
totalBet = totalBet.add(game.getSplitBet());
|
||||||
UserEntity user = getUserWithFreshData(game.getUser());
|
|
||||||
user.setBalance(user.getBalance().add(blackjackWinnings));
|
if (isWin) {
|
||||||
return BlackJackState.PLAYER_BLACKJACK;
|
int mainHandValue = calculateHandValue(game.getPlayerCards());
|
||||||
}
|
int splitHandValue = calculateHandValue(game.getPlayerSplitCards());
|
||||||
} else if (playerHandValue > 21) {
|
int dealerValue = calculateHandValue(game.getDealerCards());
|
||||||
return BlackJackState.PLAYER_LOST;
|
|
||||||
}
|
if (mainHandValue <= 21 && (dealerValue > 21 || mainHandValue > dealerValue)) {
|
||||||
|
balance = balance.add(game.getBet().multiply(BigDecimal.valueOf(2)));
|
||||||
return BlackJackState.IN_PROGRESS;
|
} else if (mainHandValue == dealerValue) {
|
||||||
}
|
balance = balance.add(game.getBet());
|
||||||
|
}
|
||||||
private int calculateHandValue(List<CardEntity> hand) {
|
|
||||||
int sum = 0;
|
if (splitHandValue <= 21 && (dealerValue > 21 || splitHandValue > dealerValue)) {
|
||||||
int aceCount = 0;
|
balance = balance.add(game.getSplitBet().multiply(BigDecimal.valueOf(2)));
|
||||||
for (CardEntity card : hand) {
|
} else if (splitHandValue == dealerValue) {
|
||||||
sum += card.getRank().getValue();
|
balance = balance.add(game.getSplitBet());
|
||||||
if (card.getRank() == Rank.ACE) {
|
}
|
||||||
aceCount++;
|
} else if (game.getState() == BlackJackState.DRAW) {
|
||||||
}
|
balance = balance.add(totalBet);
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
while (sum > 21 && aceCount > 0) {
|
if (isWin) {
|
||||||
sum -= 10;
|
balance = balance.add(totalBet.multiply(BigDecimal.valueOf(2)));
|
||||||
aceCount--;
|
} else if (game.getState() == BlackJackState.DRAW) {
|
||||||
}
|
balance = balance.add(totalBet);
|
||||||
|
}
|
||||||
return sum;
|
}
|
||||||
}
|
|
||||||
}
|
user.setBalance(balance);
|
||||||
|
userRepository.save(user);
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
card.setCardType(CardType.DECK);
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
|
||||||
|
private BlackJackState getState(BlackJackGameEntity game) {
|
||||||
|
int playerHandValue = calculateHandValue(game.getPlayerCards());
|
||||||
|
|
||||||
|
if (playerHandValue == 21) {
|
||||||
|
CardEntity hole = drawCardFromDeck(game);
|
||||||
|
hole.setCardType(CardType.DEALER);
|
||||||
|
game.getDealerCards().add(hole);
|
||||||
|
|
||||||
|
int dealerHandValue = calculateHandValue(game.getDealerCards());
|
||||||
|
|
||||||
|
if (dealerHandValue == 21) {
|
||||||
|
return BlackJackState.DRAW;
|
||||||
|
} else {
|
||||||
|
BigDecimal blackjackWinnings = game.getBet().multiply(new BigDecimal("1.5"));
|
||||||
|
UserEntity user = getUserWithFreshData(game.getUser());
|
||||||
|
user.setBalance(user.getBalance().add(blackjackWinnings));
|
||||||
|
return BlackJackState.PLAYER_BLACKJACK;
|
||||||
|
}
|
||||||
|
} else if (playerHandValue > 21) {
|
||||||
|
return BlackJackState.PLAYER_LOST;
|
||||||
|
}
|
||||||
|
|
||||||
|
return BlackJackState.IN_PROGRESS;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int calculateHandValue(List<CardEntity> hand) {
|
||||||
|
int sum = 0;
|
||||||
|
int aceCount = 0;
|
||||||
|
for (CardEntity card : hand) {
|
||||||
|
sum += card.getRank().getValue();
|
||||||
|
if (card.getRank() == Rank.ACE) {
|
||||||
|
aceCount++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
while (sum > 21 && aceCount > 0) {
|
||||||
|
sum -= 10;
|
||||||
|
aceCount--;
|
||||||
|
}
|
||||||
|
|
||||||
|
return sum;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -36,5 +36,5 @@ public class CardEntity {
|
||||||
}
|
}
|
||||||
|
|
||||||
enum CardType {
|
enum CardType {
|
||||||
DECK, PLAYER, DEALER
|
DECK, PLAYER, DEALER, PLAYER_SPLIT
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
import { ChangeDetectionStrategy, Component, inject, signal } from '@angular/core';
|
import { ChangeDetectionStrategy, Component, inject, signal, OnInit } from '@angular/core';
|
||||||
import { CommonModule } from '@angular/common';
|
import { CommonModule } from '@angular/common';
|
||||||
import { Router } from '@angular/router';
|
import { Router } from '@angular/router';
|
||||||
import { PlayingCardComponent } from './components/playing-card/playing-card.component';
|
import { PlayingCardComponent } from './components/playing-card/playing-card.component';
|
||||||
|
@ -13,6 +13,7 @@ import { GameResultComponent } from '@blackjack/components/game-result/game-resu
|
||||||
import { GameState } from '@blackjack/enum/gameState';
|
import { GameState } from '@blackjack/enum/gameState';
|
||||||
import { NavbarComponent } from '@shared/components/navbar/navbar.component';
|
import { NavbarComponent } from '@shared/components/navbar/navbar.component';
|
||||||
import { UserService } from '@service/user.service';
|
import { UserService } from '@service/user.service';
|
||||||
|
import { timer } from 'rxjs';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-blackjack',
|
selector: 'app-blackjack',
|
||||||
|
@ -30,7 +31,7 @@ import { UserService } from '@service/user.service';
|
||||||
templateUrl: './blackjack.component.html',
|
templateUrl: './blackjack.component.html',
|
||||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||||
})
|
})
|
||||||
export default class BlackjackComponent {
|
export default class BlackjackComponent implements OnInit {
|
||||||
private router = inject(Router);
|
private router = inject(Router);
|
||||||
private userService = inject(UserService);
|
private userService = inject(UserService);
|
||||||
private blackjackService = inject(BlackjackService);
|
private blackjackService = inject(BlackjackService);
|
||||||
|
@ -47,13 +48,11 @@ export default class BlackjackComponent {
|
||||||
isActionInProgress = signal(false);
|
isActionInProgress = signal(false);
|
||||||
currentAction = signal<string>('');
|
currentAction = signal<string>('');
|
||||||
|
|
||||||
constructor() {
|
ngOnInit(): void {
|
||||||
this.refreshUserBalance();
|
this.userService.currentUser$.subscribe((user) => {
|
||||||
}
|
if (user) {
|
||||||
|
this.balance.set(user.balance);
|
||||||
private refreshUserBalance(): void {
|
}
|
||||||
this.userService.getCurrentUser().subscribe((user) => {
|
|
||||||
this.balance.set(user?.balance ?? 0);
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -83,8 +82,10 @@ export default class BlackjackComponent {
|
||||||
if (isGameOver) {
|
if (isGameOver) {
|
||||||
console.log('Game is over, state:', game.state);
|
console.log('Game is over, state:', game.state);
|
||||||
this.userService.refreshCurrentUser();
|
this.userService.refreshCurrentUser();
|
||||||
this.showGameResult.set(true);
|
timer(1500).subscribe(() => {
|
||||||
console.log('Game result dialog should be shown now');
|
this.showGameResult.set(true);
|
||||||
|
console.log('Game result dialog shown after delay');
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -180,21 +181,18 @@ export default class BlackjackComponent {
|
||||||
onCloseGameResult(): void {
|
onCloseGameResult(): void {
|
||||||
console.log('Closing game result dialog');
|
console.log('Closing game result dialog');
|
||||||
this.showGameResult.set(false);
|
this.showGameResult.set(false);
|
||||||
|
this.userService.refreshCurrentUser();
|
||||||
}
|
}
|
||||||
|
|
||||||
private handleGameError(error: HttpErrorResponse): void {
|
private handleGameError(error: HttpErrorResponse): void {
|
||||||
if (error instanceof HttpErrorResponse) {
|
if (error instanceof HttpErrorResponse) {
|
||||||
if (error.status === 400 && error.error?.error === 'Invalid state') {
|
if (error.status === 400 && error.error?.error === 'Invalid state') {
|
||||||
this.gameInProgress.set(false);
|
this.gameInProgress.set(false);
|
||||||
|
this.userService.refreshCurrentUser();
|
||||||
this.refreshUserBalance();
|
|
||||||
} else if (error.status === 500) {
|
} else if (error.status === 500) {
|
||||||
console.log('Server error occurred. The game may have been updated in another session.');
|
console.log('Server error occurred. The game may have been updated in another session.');
|
||||||
|
|
||||||
this.gameInProgress.set(false);
|
this.gameInProgress.set(false);
|
||||||
|
this.userService.refreshCurrentUser();
|
||||||
this.refreshUserBalance();
|
|
||||||
|
|
||||||
if (this.currentGameId()) {
|
if (this.currentGameId()) {
|
||||||
this.refreshGameState(this.currentGameId()!);
|
this.refreshGameState(this.currentGameId()!);
|
||||||
}
|
}
|
||||||
|
|
|
@ -6,9 +6,11 @@ import {
|
||||||
OnChanges,
|
OnChanges,
|
||||||
Output,
|
Output,
|
||||||
SimpleChanges,
|
SimpleChanges,
|
||||||
|
signal,
|
||||||
} from '@angular/core';
|
} from '@angular/core';
|
||||||
import { CommonModule, CurrencyPipe } from '@angular/common';
|
import { CommonModule, CurrencyPipe } from '@angular/common';
|
||||||
import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
|
import { FormGroup, ReactiveFormsModule } from '@angular/forms';
|
||||||
|
import { BettingService } from '@blackjack/services/betting.service';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-game-info',
|
selector: 'app-game-info',
|
||||||
|
@ -65,10 +67,12 @@ import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angula
|
||||||
type="number"
|
type="number"
|
||||||
id="bet"
|
id="bet"
|
||||||
formControlName="bet"
|
formControlName="bet"
|
||||||
class="w-full px-3 py-2 bg-deep-blue-light text-white rounded focus:outline-none focus:ring-2 focus:ring-emerald"
|
class="w-full px-3 py-2 bg-deep-blue-light text-white rounded focus:outline-none focus:ring-2 focus:ring-emerald disabled:opacity-50"
|
||||||
[min]="1"
|
[min]="1"
|
||||||
[max]="balance"
|
[max]="balance"
|
||||||
step="0.01"
|
step="0.01"
|
||||||
|
[disabled]="gameInProgress || isActionInProgress"
|
||||||
|
[placeholder]="balance | currency: 'EUR'"
|
||||||
/>
|
/>
|
||||||
@if (betForm.get('bet')?.errors?.['required'] && betForm.get('bet')?.touched) {
|
@if (betForm.get('bet')?.errors?.['required'] && betForm.get('bet')?.touched) {
|
||||||
<span class="text-xs text-accent-red">Bitte geben Sie einen Einsatz ein</span>
|
<span class="text-xs text-accent-red">Bitte geben Sie einen Einsatz ein</span>
|
||||||
|
@ -101,7 +105,14 @@ import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angula
|
||||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||||
})
|
})
|
||||||
export class GameInfoComponent implements OnChanges {
|
export class GameInfoComponent implements OnChanges {
|
||||||
@Input() balance = 0;
|
@Input() set balance(value: number) {
|
||||||
|
this._balance.set(value);
|
||||||
|
}
|
||||||
|
get balance() {
|
||||||
|
return this._balance();
|
||||||
|
}
|
||||||
|
private _balance = signal(0);
|
||||||
|
|
||||||
@Input() currentBet = 0;
|
@Input() currentBet = 0;
|
||||||
@Input() gameInProgress = false;
|
@Input() gameInProgress = false;
|
||||||
@Input() isActionInProgress = false;
|
@Input() isActionInProgress = false;
|
||||||
|
@ -109,24 +120,19 @@ export class GameInfoComponent implements OnChanges {
|
||||||
|
|
||||||
betForm: FormGroup;
|
betForm: FormGroup;
|
||||||
|
|
||||||
constructor(private fb: FormBuilder) {
|
constructor(private bettingService: BettingService) {
|
||||||
this.betForm = this.fb.group({
|
this.betForm = this.bettingService.createBetForm();
|
||||||
bet: ['', [Validators.required, Validators.min(1)]],
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
ngOnChanges(changes: SimpleChanges): void {
|
ngOnChanges(changes: SimpleChanges): void {
|
||||||
if (changes['balance']) {
|
if (changes['balance']) {
|
||||||
this.betForm
|
this.bettingService.updateBetFormValidators(this.betForm, this.balance);
|
||||||
.get('bet')
|
|
||||||
?.setValidators([Validators.required, Validators.min(1), Validators.max(this.balance)]);
|
|
||||||
this.betForm.get('bet')?.updateValueAndValidity();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
setBetAmount(percentage: number) {
|
setBetAmount(percentage: number) {
|
||||||
const betAmount = Math.floor(this.balance * percentage * 100) / 100;
|
const betAmount = this.bettingService.calculateBetAmount(this.balance, percentage);
|
||||||
if (betAmount >= 1) {
|
if (this.bettingService.isValidBet(betAmount, this.balance)) {
|
||||||
this.betForm.patchValue({ bet: betAmount });
|
this.betForm.patchValue({ bet: betAmount });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -134,7 +140,7 @@ export class GameInfoComponent implements OnChanges {
|
||||||
onSubmit() {
|
onSubmit() {
|
||||||
if (this.betForm.valid) {
|
if (this.betForm.valid) {
|
||||||
const betAmount = parseFloat(this.betForm.value.bet);
|
const betAmount = parseFloat(this.betForm.value.bet);
|
||||||
if (betAmount <= this.balance) {
|
if (this.bettingService.isValidBet(betAmount, this.balance)) {
|
||||||
this.newGame.emit(betAmount);
|
this.newGame.emit(betAmount);
|
||||||
this.betForm.reset();
|
this.betForm.reset();
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,31 @@
|
||||||
|
import { Injectable } from '@angular/core';
|
||||||
|
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
|
||||||
|
|
||||||
|
@Injectable({
|
||||||
|
providedIn: 'root',
|
||||||
|
})
|
||||||
|
export class BettingService {
|
||||||
|
constructor(private fb: FormBuilder) {}
|
||||||
|
|
||||||
|
createBetForm(): FormGroup {
|
||||||
|
return this.fb.group({
|
||||||
|
bet: ['', [Validators.required, Validators.min(1)]],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
updateBetFormValidators(form: FormGroup, balance: number): void {
|
||||||
|
form.reset();
|
||||||
|
form
|
||||||
|
.get('bet')
|
||||||
|
?.setValidators([Validators.required, Validators.min(1), Validators.max(balance)]);
|
||||||
|
form.get('bet')?.updateValueAndValidity();
|
||||||
|
}
|
||||||
|
|
||||||
|
calculateBetAmount(balance: number, percentage: number): number {
|
||||||
|
return Math.floor(balance * percentage * 100) / 100;
|
||||||
|
}
|
||||||
|
|
||||||
|
isValidBet(betAmount: number, balance: number): boolean {
|
||||||
|
return betAmount >= 1 && betAmount <= balance;
|
||||||
|
}
|
||||||
|
}
|
Loading…
Add table
Add a link
Reference in a new issue