Compare commits

...

28 commits

Author SHA1 Message Date
9981ebc9d1
fix(deps): update dependencies (major and minor)
Some checks failed
CI / Get Changed Files (pull_request) Successful in 7s
CI / eslint (pull_request) Successful in 30s
CI / test-build (pull_request) Successful in 37s
CI / prettier (pull_request) Successful in 1m2s
CI / Checkstyle Main (pull_request) Failing after 2m20s
2025-04-02 10:01:44 +00:00
ac6e3be52c
Merge pull request 'Add all the renovate changes' (!115) from renovate-test into main
All checks were successful
Release / Release (push) Successful in 58s
Reviewed-on: #115
2025-04-02 10:00:20 +00:00
3c64b9ec8b
build: update stripe-java dependency version to 20.136.0
All checks were successful
CI / Get Changed Files (pull_request) Successful in 6s
CI / Checkstyle Main (pull_request) Has been skipped
CI / prettier (pull_request) Successful in 23s
CI / eslint (pull_request) Successful in 1m26s
CI / test-build (pull_request) Successful in 1m50s
2025-04-02 11:54:06 +02:00
6b3a8a41fd
ci: remove debug job from CI workflow
Some checks failed
CI / Get Changed Files (pull_request) Successful in 6s
CI / eslint (pull_request) Successful in 29s
CI / test-build (pull_request) Successful in 35s
CI / prettier (pull_request) Successful in 1m0s
CI / Checkstyle Main (pull_request) Failing after 1m52s
2025-04-02 11:45:35 +02:00
06318a8b57
build(frontend): update ajv and ajv-formats versions
Some checks failed
CI / Get Changed Files (pull_request) Successful in 7s
CI / prettier (pull_request) Successful in 24s
CI / Checkstyle Main (pull_request) Failing after 33s
CI / eslint (pull_request) Failing after 1m38s
CI / test-build (pull_request) Successful in 1m51s
2025-04-02 11:42:53 +02:00
5d15f40a30
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
Reviewed-on: #116
Reviewed-by: Jan K9f <jan@kjan.email>
2025-04-02 09:41:18 +00:00
4c83419a31
Merge branch 'main' into task/CAS-50/add_rest_blackjack_logic_with_frontend_animations
All checks were successful
CI / Get Changed Files (pull_request) Successful in 8s
CI / eslint (pull_request) Successful in 21s
CI / test-build (pull_request) Successful in 28s
CI / prettier (pull_request) Successful in 42s
CI / Checkstyle Main (pull_request) Successful in 1m47s
2025-04-02 09:38:43 +00:00
d22c4c243f
feat(game-info): add placeholder and disable bet input
All checks were successful
CI / Get Changed Files (pull_request) Successful in 7s
CI / eslint (pull_request) Successful in 25s
CI / prettier (pull_request) Successful in 26s
CI / Checkstyle Main (pull_request) Successful in 41s
CI / test-build (pull_request) Successful in 42s
2025-04-02 11:38:14 +02:00
f60ce73e65
build(frontend): add ajv-formats dependency to package.json
Some checks failed
CI / Get Changed Files (pull_request) Successful in 6s
CI / prettier (pull_request) Successful in 24s
CI / Checkstyle Main (pull_request) Failing after 32s
CI / eslint (pull_request) Failing after 1m35s
CI / test-build (pull_request) Failing after 1m45s
2025-04-02 11:36:55 +02:00
bd82262049
ci: add debug step to CI workflow for better logging
Some checks failed
CI / Get Changed Files (pull_request) Successful in 7s
CI / eslint (pull_request) Failing after 24s
CI / test-build (pull_request) Failing after 27s
CI / prettier (pull_request) Successful in 1m3s
CI / Checkstyle Main (pull_request) Failing after 2m1s
2025-04-02 11:34:46 +02:00
6b4adfca0a
build(frontend): update angular compiler version to 19.2.4
Some checks failed
CI / Get Changed Files (pull_request) Successful in 10s
CI / eslint (pull_request) Failing after 35s
CI / prettier (pull_request) Successful in 39s
CI / test-build (pull_request) Failing after 42s
CI / Checkstyle Main (pull_request) Failing after 51s
2025-04-02 11:31:39 +02:00
1fc62af66d
build(frontend): update rxjs version to ~7.8.2
Some checks failed
CI / Get Changed Files (pull_request) Successful in 7s
CI / prettier (pull_request) Successful in 26s
CI / Checkstyle Main (pull_request) Failing after 36s
CI / eslint (pull_request) Failing after 1m26s
CI / test-build (pull_request) Failing after 1m24s
2025-04-02 11:31:08 +02:00
e9c4d4fbed
refactor(BlackJackService): simplify card dealing logic
All checks were successful
CI / Get Changed Files (pull_request) Successful in 5s
CI / prettier (pull_request) Successful in 21s
CI / test-build (pull_request) Successful in 40s
CI / eslint (pull_request) Successful in 48s
CI / Checkstyle Main (pull_request) Successful in 52s
2025-04-02 11:29:16 +02:00
1916c04f4a
chore: update lint command in package.json
Some checks failed
CI / Get Changed Files (pull_request) Successful in 7s
CI / eslint (pull_request) Failing after 20s
CI / test-build (pull_request) Failing after 25s
CI / prettier (pull_request) Successful in 1m0s
CI / Checkstyle Main (pull_request) Failing after 2m12s
2025-04-02 11:28:01 +02:00
575a6651d6
build(frontend): update Angular CLI version in package.json
Some checks failed
CI / Get Changed Files (pull_request) Successful in 9s
CI / eslint (pull_request) Failing after 33s
CI / prettier (pull_request) Successful in 34s
CI / Checkstyle Main (pull_request) Failing after 51s
CI / test-build (pull_request) Failing after 23s
2025-04-02 11:25:24 +02:00
3ef5530e77
feat(blackjack): add split functionality to the game
All checks were successful
CI / Get Changed Files (pull_request) Successful in 6s
CI / prettier (pull_request) Successful in 19s
CI / Checkstyle Main (pull_request) Successful in 50s
CI / eslint (pull_request) Successful in 53s
CI / test-build (pull_request) Successful in 1m12s
2025-04-02 11:25:03 +02:00
942a47c1b2
build(frontend): update Angular dependencies to v19.0.0
Some checks failed
CI / Get Changed Files (pull_request) Successful in 6s
CI / prettier (pull_request) Successful in 23s
CI / Checkstyle Main (pull_request) Failing after 33s
CI / eslint (pull_request) Failing after 1m17s
CI / test-build (pull_request) Failing after 1m23s
2025-04-02 11:20:36 +02:00
ff98cab6ac
Merge pull request 'feat: Create api routes for lootboxes (CAS-43)' (!110) from feat/lootboxes into main
All checks were successful
Release / Release (push) Successful in 1m22s
Reviewed-on: #110
Reviewed-by: Jan K9f <jan@kjan.email>
Reviewed-by: lziemke <lea.z4@schule.bremen.de>
2025-04-02 09:18:54 +00:00
c64fccb236
Merge pull request 'chore(deps): update devdependencies (non-major)' (!114) from renovate/devdependencies-(non-major) into renovate-test
Some checks failed
CI / Get Changed Files (pull_request) Successful in 6s
CI / prettier (pull_request) Successful in 18s
CI / Checkstyle Main (pull_request) Failing after 31s
CI / eslint (pull_request) Successful in 59s
CI / test-build (pull_request) Failing after 58s
Reviewed-on: #114
2025-04-02 09:17:38 +00:00
210500783f
Merge pull request 'fix(deps): update dependencies (major and minor)' (!113) from renovate/major-dependencies-(major-and-minor) into renovate-test
Reviewed-on: #113
2025-04-02 09:16:18 +00:00
ec994616ee
Merge branch 'main' into feat/lootboxes
All checks were successful
CI / Get Changed Files (pull_request) Successful in 7s
CI / eslint (pull_request) Has been skipped
CI / prettier (pull_request) Has been skipped
CI / test-build (pull_request) Has been skipped
CI / Checkstyle Main (pull_request) Successful in 38s
2025-04-02 09:15:31 +00:00
Phan Huy Tran
948240ba1e fix: fix wrong reward getting returned, refactor to service
All checks were successful
CI / Get Changed Files (pull_request) Successful in 7s
CI / eslint (pull_request) Has been skipped
CI / prettier (pull_request) Has been skipped
CI / test-build (pull_request) Has been skipped
CI / Checkstyle Main (pull_request) Successful in 39s
2025-04-02 11:15:08 +02:00
Phan Huy Tran
b963595ab4 feat: manage balance
All checks were successful
CI / Get Changed Files (pull_request) Successful in 7s
CI / eslint (pull_request) Has been skipped
CI / prettier (pull_request) Has been skipped
CI / test-build (pull_request) Has been skipped
CI / Checkstyle Main (pull_request) Successful in 1m29s
2025-04-02 11:04:20 +02:00
38f4617fb0
chore(deps): update devdependencies (non-major)
Some checks failed
CI / Get Changed Files (pull_request) Successful in 6s
CI / Checkstyle Main (pull_request) Has been skipped
CI / eslint (pull_request) Successful in 20s
CI / test-build (pull_request) Failing after 21s
CI / prettier (pull_request) Successful in 34s
2025-04-02 09:01:53 +00:00
Phan Huy Tran
8a6bc95c92 feat: add route to get all lootboxes 2025-04-02 10:18:51 +02:00
Phan Huy Tran
e4bcd9d791 refactor: use many to many relation for lootboxes and rewards 2025-04-02 10:08:23 +02:00
Phan Huy Tran
084d478cd9 feat: create repositories
All checks were successful
CI / Get Changed Files (pull_request) Successful in 7s
CI / eslint (pull_request) Has been skipped
CI / prettier (pull_request) Has been skipped
CI / test-build (pull_request) Has been skipped
CI / Checkstyle Main (pull_request) Successful in 1m28s
2025-04-02 09:18:17 +02:00
Phan Huy Tran
1878ed8fe4 feat: create lootbox and rewards entity 2025-04-02 09:15:37 +02:00
17 changed files with 1318 additions and 680 deletions

View file

@ -0,0 +1,9 @@
GET http://localhost:8080/lootboxes
Authorization: Bearer {{token}}
Content-Type: application/json
###
POST http://localhost:8080/lootboxes/2
Authorization: Bearer {{token}}
Content-Type: application/json

View file

@ -1,10 +1,20 @@
package de.szut.casino;
import de.szut.casino.lootboxes.LootBoxEntity;
import de.szut.casino.lootboxes.LootBoxRepository;
import de.szut.casino.lootboxes.RewardEntity;
import de.szut.casino.lootboxes.RewardRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@SpringBootApplication
public class CasinoApplication {
@ -16,4 +26,65 @@ public class CasinoApplication {
public static RestTemplate restTemplate() {
return new RestTemplate();
}
@Bean
public CommandLineRunner initData(LootBoxRepository lootBoxRepository, RewardRepository rewardRepository) {
return _ -> {
if (lootBoxRepository.count() == 0) {
LootBoxEntity basicLootBox = new LootBoxEntity();
basicLootBox.setName("Basic LootBox");
basicLootBox.setPrice(new BigDecimal("2"));
basicLootBox.setRewards(new ArrayList<>()); // Initialize the list
LootBoxEntity premiumLootBox = new LootBoxEntity();
premiumLootBox.setName("Premium LootBox");
premiumLootBox.setPrice(new BigDecimal("5"));
premiumLootBox.setRewards(new ArrayList<>()); // Initialize the list
lootBoxRepository.saveAll(Arrays.asList(basicLootBox, premiumLootBox));
RewardEntity commonReward = new RewardEntity();
commonReward.setValue(new BigDecimal("0.50"));
commonReward.setProbability(new BigDecimal("0.7"));
RewardEntity rareReward = new RewardEntity();
rareReward.setValue(new BigDecimal("2.00"));
rareReward.setProbability(new BigDecimal("0.25"));
RewardEntity epicReward = new RewardEntity();
epicReward.setValue(new BigDecimal("5.00"));
epicReward.setProbability(new BigDecimal("0.5"));
RewardEntity premiumCommon = new RewardEntity();
premiumCommon.setValue(new BigDecimal("2.00"));
premiumCommon.setProbability(new BigDecimal("0.6"));
RewardEntity premiumRare = new RewardEntity();
premiumRare.setValue(new BigDecimal("5.00"));
premiumRare.setProbability(new BigDecimal("0.3"));
RewardEntity legendaryReward = new RewardEntity();
legendaryReward.setValue(new BigDecimal("15.00"));
legendaryReward.setProbability(new BigDecimal("0.10"));
rewardRepository.saveAll(Arrays.asList(
commonReward, rareReward, epicReward,
premiumCommon, premiumRare, legendaryReward
));
basicLootBox.getRewards().add(commonReward);
basicLootBox.getRewards().add(premiumRare);
premiumLootBox.getRewards().add(premiumCommon);
premiumLootBox.getRewards().add(premiumRare);
premiumLootBox.getRewards().add(legendaryReward);
lootBoxRepository.saveAll(Arrays.asList(basicLootBox, premiumLootBox));
System.out.println("Initial LootBoxes and rewards created successfully");
} else {
System.out.println("LootBoxes already exist, skipping initialization");
}
};
}
}

View file

@ -94,6 +94,23 @@ public class BlackJackGameController {
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")
public ResponseEntity<Object> createBlackJackGame(@RequestBody @Valid CreateBlackJackGameDto createBlackJackGameDto, @RequestHeader("Authorization") String token) {
Optional<UserEntity> optionalUser = userService.getCurrentUser(token);

View file

@ -51,4 +51,15 @@ public class BlackJackGameEntity {
@JsonManagedReference
@SQLRestriction("card_type = 'DEALER'")
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;
}

View file

@ -42,13 +42,12 @@ public class BlackJackService {
@Transactional
public BlackJackGameEntity hit(BlackJackGameEntity game) {
game = refreshGameState(game);
if (game.getState() != BlackJackState.IN_PROGRESS) {
return game;
}
dealCardToPlayer(game);
updateGameStateAndBalance(game);
return blackJackGameRepository.save(game);
@ -56,8 +55,6 @@ public class BlackJackService {
@Transactional
public BlackJackGameEntity stand(BlackJackGameEntity game) {
game = refreshGameState(game);
if (game.getState() != BlackJackState.IN_PROGRESS) {
return game;
}
@ -70,8 +67,6 @@ public class BlackJackService {
@Transactional
public BlackJackGameEntity doubleDown(BlackJackGameEntity game) {
game = refreshGameState(game);
if (game.getState() != BlackJackState.IN_PROGRESS || game.getPlayerCards().size() != 2) {
return game;
}
@ -96,6 +91,36 @@ public class BlackJackService {
return game;
}
@Transactional
public BlackJackGameEntity split(BlackJackGameEntity game) {
if (game.getState() != BlackJackState.IN_PROGRESS ||
game.getPlayerCards().size() != 2 ||
game.isSplit() ||
!game.getPlayerCards().get(0).getRank().equals(game.getPlayerCards().get(1).getRank())) {
return game;
}
UserEntity user = getUserWithFreshData(game.getUser());
BigDecimal splitBet = game.getBet();
if (user.getBalance().compareTo(splitBet) < 0) {
return game;
}
deductBetFromBalance(user, splitBet);
game.setSplitBet(splitBet);
game.setSplit(true);
CardEntity card = game.getPlayerCards().remove(1);
card.setCardType(CardType.PLAYER_SPLIT);
game.getPlayerSplitCards().add(card);
dealCardToPlayer(game);
dealCardToSplitHand(game);
return blackJackGameRepository.save(game);
}
private BlackJackGameEntity refreshGameState(BlackJackGameEntity game) {
return blackJackGameRepository.findById(game.getId()).orElse(game);
}
@ -130,13 +155,33 @@ public class BlackJackService {
}
}
private void updateGameStateAndBalance(BlackJackGameEntity game) {
game.setState(getState(game));
private void dealCardToSplitHand(BlackJackGameEntity game) {
CardEntity card = drawCardFromDeck(game);
card.setCardType(CardType.PLAYER_SPLIT);
game.getPlayerSplitCards().add(card);
}
if (game.getState() == BlackJackState.PLAYER_WON) {
updateUserBalance(game, true);
} else if (game.getState() == BlackJackState.PLAYER_LOST) {
updateUserBalance(game, false);
private void updateGameStateAndBalance(BlackJackGameEntity game) {
if (game.isSplit()) {
int mainHandValue = calculateHandValue(game.getPlayerCards());
int splitHandValue = calculateHandValue(game.getPlayerSplitCards());
if (mainHandValue > 21 && splitHandValue > 21) {
game.setState(BlackJackState.PLAYER_LOST);
updateUserBalance(game, false);
} else if (mainHandValue <= 21 && splitHandValue <= 21) {
game.setState(BlackJackState.IN_PROGRESS);
} else {
game.setState(BlackJackState.IN_PROGRESS);
}
} else {
game.setState(getState(game));
if (game.getState() == BlackJackState.PLAYER_WON) {
updateUserBalance(game, true);
} else if (game.getState() == BlackJackState.PLAYER_LOST) {
updateUserBalance(game, false);
}
}
}
@ -152,7 +197,7 @@ public class BlackJackService {
updateUserBalance(game, false);
} else {
game.setState(BlackJackState.DRAW);
updateUserBalance(game, false); // For draw, player gets their bet back
updateUserBalance(game, false);
}
}
@ -164,13 +209,37 @@ public class BlackJackService {
@Transactional
private void updateUserBalance(BlackJackGameEntity game, boolean isWin) {
UserEntity user = getUserWithFreshData(game.getUser());
BigDecimal betAmount = game.getBet();
BigDecimal totalBet = game.getBet();
BigDecimal balance = user.getBalance();
if (isWin) {
balance = balance.add(betAmount.multiply(BigDecimal.valueOf(2)));
} else if (game.getState() == BlackJackState.DRAW) {
balance = balance.add(betAmount);
if (game.isSplit()) {
totalBet = totalBet.add(game.getSplitBet());
if (isWin) {
int mainHandValue = calculateHandValue(game.getPlayerCards());
int splitHandValue = calculateHandValue(game.getPlayerSplitCards());
int dealerValue = calculateHandValue(game.getDealerCards());
if (mainHandValue <= 21 && (dealerValue > 21 || mainHandValue > dealerValue)) {
balance = balance.add(game.getBet().multiply(BigDecimal.valueOf(2)));
} else if (mainHandValue == dealerValue) {
balance = balance.add(game.getBet());
}
if (splitHandValue <= 21 && (dealerValue > 21 || splitHandValue > dealerValue)) {
balance = balance.add(game.getSplitBet().multiply(BigDecimal.valueOf(2)));
} else if (splitHandValue == dealerValue) {
balance = balance.add(game.getSplitBet());
}
} else if (game.getState() == BlackJackState.DRAW) {
balance = balance.add(totalBet);
}
} else {
if (isWin) {
balance = balance.add(totalBet.multiply(BigDecimal.valueOf(2)));
} else if (game.getState() == BlackJackState.DRAW) {
balance = balance.add(totalBet);
}
}
user.setBalance(balance);

View file

@ -36,5 +36,5 @@ public class CardEntity {
}
enum CardType {
DECK, PLAYER, DEALER
DECK, PLAYER, DEALER, PLAYER_SPLIT
}

View file

@ -0,0 +1,58 @@
package de.szut.casino.lootboxes;
import de.szut.casino.user.UserEntity;
import de.szut.casino.user.UserRepository;
import de.szut.casino.user.UserService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@RestController
public class LootBoxController {
private final LootBoxRepository lootBoxRepository;
private final UserService userService;
private final LootBoxService lootBoxService;
public LootBoxController(LootBoxRepository lootBoxRepository, UserRepository userRepository, UserService userService, LootBoxService lootBoxService) {
this.lootBoxRepository = lootBoxRepository;
this.userService = userService;
this.lootBoxService = lootBoxService;
}
@GetMapping("/lootboxes")
public List<LootBoxEntity> getAllLootBoxes() {
return lootBoxRepository.findAll();
}
@PostMapping("/lootboxes/{id}")
public ResponseEntity<Object> purchaseLootBox(@PathVariable Long id, @RequestHeader("Authorization") String token) {
Optional<LootBoxEntity> optionalLootBox = lootBoxRepository.findById(id);
if (optionalLootBox.isEmpty()) {
return ResponseEntity.notFound().build();
}
LootBoxEntity lootBox = optionalLootBox.get();
Optional<UserEntity> optionalUser = userService.getCurrentUser(token);
if (optionalUser.isEmpty()) {
return ResponseEntity.notFound().build();
}
UserEntity user = optionalUser.get();
if (lootBoxService.hasSufficientBalance(user, lootBox.getPrice())) {
Map<String, String> errorResponse = new HashMap<>();
errorResponse.put("error", "Insufficient balance");
return ResponseEntity.badRequest().body(errorResponse);
}
RewardEntity reward = lootBoxService.determineReward(lootBox);
lootBoxService.handleBalance(user, lootBox, reward);
return ResponseEntity.ok(reward);
}
}

View file

@ -0,0 +1,40 @@
package de.szut.casino.lootboxes;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import de.szut.casino.blackjack.CardEntity;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.SQLRestriction;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
@Entity
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class LootBoxEntity {
@Id
@GeneratedValue
private Long id;
private String name;
@Column(precision = 19, scale = 2)
private BigDecimal price;
@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinTable(
name = "lootbox_reward",
joinColumns = @JoinColumn(name = "lootbox_id"),
inverseJoinColumns = @JoinColumn(name = "reward_id")
)
private List<RewardEntity> rewards = new ArrayList<>();
}

View file

@ -0,0 +1,8 @@
package de.szut.casino.lootboxes;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;
@Service
public interface LootBoxRepository extends JpaRepository<LootBoxEntity, Long> {
}

View file

@ -0,0 +1,40 @@
package de.szut.casino.lootboxes;
import de.szut.casino.user.UserEntity;
import de.szut.casino.user.UserRepository;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
@Service
public class LootBoxService {
private final UserRepository userRepository;
public LootBoxService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public boolean hasSufficientBalance(UserEntity user, BigDecimal price) {
return user.getBalance().compareTo(price) < 0;
}
public RewardEntity determineReward(LootBoxEntity lootBox) {
double randomValue = Math.random();
BigDecimal cumulativeProbability = BigDecimal.ZERO;
for (RewardEntity reward : lootBox.getRewards()) {
cumulativeProbability = cumulativeProbability.add(reward.getProbability());
if (randomValue <= cumulativeProbability.doubleValue()) {
return reward;
}
}
return lootBox.getRewards().getLast();
}
public void handleBalance(UserEntity user, LootBoxEntity lootBox, RewardEntity reward) {
user.setBalance(user.getBalance().subtract(lootBox.getPrice()));
user.setBalance(user.getBalance().add(reward.getValue()));
userRepository.save(user);
}
}

View file

@ -0,0 +1,30 @@
package de.szut.casino.lootboxes;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
@Getter
@Setter
@Entity
public class RewardEntity {
@Id
@GeneratedValue
private Long id;
@Column(precision = 19, scale = 2)
private BigDecimal value;
@Column(precision = 5, scale = 2)
private BigDecimal probability;
@ManyToMany(mappedBy = "rewards")
@JsonBackReference
private List<LootBoxEntity> lootBoxes = new ArrayList<>();
}

View file

@ -0,0 +1,8 @@
package de.szut.casino.lootboxes;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;
@Service
public interface RewardRepository extends JpaRepository<RewardEntity, Long> {
}

File diff suppressed because it is too large Load diff

View file

@ -9,14 +9,14 @@
"test": "bunx @angular/cli test",
"format": "prettier --write \"src/**/*.{ts,html,css,scss}\"",
"format:check": "prettier --check \"src/**/*.{ts,html,css,scss}\"",
"lint": "ng lint"
"lint": "bunx @angular/cli lint"
},
"private": true,
"dependencies": {
"@angular/animations": "^19.0.0",
"@angular/cdk": "~19.2.0",
"@angular/common": "^19.0.0",
"@angular/compiler": "^19.0.0",
"@angular/compiler": "^19.2.4",
"@angular/core": "^19.0.0",
"@angular/forms": "^19.0.0",
"@angular/platform-browser": "^19.0.0",
@ -28,20 +28,22 @@
"@fortawesome/free-solid-svg-icons": "^6.7.2",
"@stripe/stripe-js": "^7.0.0",
"@tailwindcss/postcss": "^4.0.3",
"ajv": "8.8.0",
"ajv-formats": "3.0.1",
"gsap": "^3.12.7",
"keycloak-angular": "^19.0.0",
"keycloak-js": "^26.0.0",
"postcss": "^8.5.1",
"rxjs": "~7.8.0",
"rxjs": "~7.8.2",
"tailwindcss": "^4.0.3",
"tslib": "^2.3.0"
},
"devDependencies": {
"@angular-devkit/build-angular": "^18.2.2",
"@angular/cli": "^18.2.2",
"@angular/compiler-cli": "^18.2.0",
"@angular-devkit/build-angular": "^19.0.0",
"@angular/cli": "^19.2.5",
"@angular/compiler-cli": "^19.0.0",
"@types/jasmine": "~5.1.0",
"angular-eslint": "19.2.1",
"angular-eslint": "19.3.0",
"eslint": "^9.20.0",
"jasmine-core": "~5.6.0",
"karma": "~6.4.0",
@ -50,7 +52,7 @@
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.1.0",
"prettier": "^3.4.2",
"typescript": "~5.5.0",
"typescript-eslint": "8.26.1"
"typescript": "~5.8.0",
"typescript-eslint": "8.29.0"
}
}

View file

@ -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 { Router } from '@angular/router';
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 { NavbarComponent } from '@shared/components/navbar/navbar.component';
import { UserService } from '@service/user.service';
import { timer } from 'rxjs';
@Component({
selector: 'app-blackjack',
@ -30,7 +31,7 @@ import { UserService } from '@service/user.service';
templateUrl: './blackjack.component.html',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export default class BlackjackComponent {
export default class BlackjackComponent implements OnInit {
private router = inject(Router);
private userService = inject(UserService);
private blackjackService = inject(BlackjackService);
@ -47,13 +48,11 @@ export default class BlackjackComponent {
isActionInProgress = signal(false);
currentAction = signal<string>('');
constructor() {
this.refreshUserBalance();
}
private refreshUserBalance(): void {
this.userService.getCurrentUser().subscribe((user) => {
this.balance.set(user?.balance ?? 0);
ngOnInit(): void {
this.userService.currentUser$.subscribe((user) => {
if (user) {
this.balance.set(user.balance);
}
});
}
@ -83,8 +82,10 @@ export default class BlackjackComponent {
if (isGameOver) {
console.log('Game is over, state:', game.state);
this.userService.refreshCurrentUser();
this.showGameResult.set(true);
console.log('Game result dialog should be shown now');
timer(1500).subscribe(() => {
this.showGameResult.set(true);
console.log('Game result dialog shown after delay');
});
}
}
@ -180,21 +181,18 @@ export default class BlackjackComponent {
onCloseGameResult(): void {
console.log('Closing game result dialog');
this.showGameResult.set(false);
this.userService.refreshCurrentUser();
}
private handleGameError(error: HttpErrorResponse): void {
if (error instanceof HttpErrorResponse) {
if (error.status === 400 && error.error?.error === 'Invalid state') {
this.gameInProgress.set(false);
this.refreshUserBalance();
this.userService.refreshCurrentUser();
} else if (error.status === 500) {
console.log('Server error occurred. The game may have been updated in another session.');
this.gameInProgress.set(false);
this.refreshUserBalance();
this.userService.refreshCurrentUser();
if (this.currentGameId()) {
this.refreshGameState(this.currentGameId()!);
}

View file

@ -6,9 +6,11 @@ import {
OnChanges,
Output,
SimpleChanges,
signal,
} from '@angular/core';
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({
selector: 'app-game-info',
@ -65,10 +67,12 @@ import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angula
type="number"
id="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"
[max]="balance"
step="0.01"
[disabled]="gameInProgress || isActionInProgress"
[placeholder]="balance | currency: 'EUR'"
/>
@if (betForm.get('bet')?.errors?.['required'] && betForm.get('bet')?.touched) {
<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,
})
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() gameInProgress = false;
@Input() isActionInProgress = false;
@ -109,24 +120,19 @@ export class GameInfoComponent implements OnChanges {
betForm: FormGroup;
constructor(private fb: FormBuilder) {
this.betForm = this.fb.group({
bet: ['', [Validators.required, Validators.min(1)]],
});
constructor(private bettingService: BettingService) {
this.betForm = this.bettingService.createBetForm();
}
ngOnChanges(changes: SimpleChanges): void {
if (changes['balance']) {
this.betForm
.get('bet')
?.setValidators([Validators.required, Validators.min(1), Validators.max(this.balance)]);
this.betForm.get('bet')?.updateValueAndValidity();
this.bettingService.updateBetFormValidators(this.betForm, this.balance);
}
}
setBetAmount(percentage: number) {
const betAmount = Math.floor(this.balance * percentage * 100) / 100;
if (betAmount >= 1) {
const betAmount = this.bettingService.calculateBetAmount(this.balance, percentage);
if (this.bettingService.isValidBet(betAmount, this.balance)) {
this.betForm.patchValue({ bet: betAmount });
}
}
@ -134,7 +140,7 @@ export class GameInfoComponent implements OnChanges {
onSubmit() {
if (this.betForm.valid) {
const betAmount = parseFloat(this.betForm.value.bet);
if (betAmount <= this.balance) {
if (this.bettingService.isValidBet(betAmount, this.balance)) {
this.newGame.emit(betAmount);
this.betForm.reset();
}

View file

@ -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;
}
}