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));
|
||||
}
|
||||
|
||||
@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);
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
|
|
@ -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,7 +155,26 @@ public class BlackJackService {
|
|||
}
|
||||
}
|
||||
|
||||
private void dealCardToSplitHand(BlackJackGameEntity game) {
|
||||
CardEntity card = drawCardFromDeck(game);
|
||||
card.setCardType(CardType.PLAYER_SPLIT);
|
||||
game.getPlayerSplitCards().add(card);
|
||||
}
|
||||
|
||||
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) {
|
||||
|
@ -139,6 +183,7 @@ public class BlackJackService {
|
|||
updateUserBalance(game, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void determineWinnerAndUpdateBalance(BlackJackGameEntity game) {
|
||||
int playerValue = calculateHandValue(game.getPlayerCards());
|
||||
|
@ -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 (game.isSplit()) {
|
||||
totalBet = totalBet.add(game.getSplitBet());
|
||||
|
||||
if (isWin) {
|
||||
balance = balance.add(betAmount.multiply(BigDecimal.valueOf(2)));
|
||||
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(betAmount);
|
||||
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);
|
||||
|
|
|
@ -36,5 +36,5 @@ public class CardEntity {
|
|||
}
|
||||
|
||||
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 { 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();
|
||||
ngOnInit(): void {
|
||||
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) {
|
||||
console.log('Game is over, state:', game.state);
|
||||
this.userService.refreshCurrentUser();
|
||||
timer(1500).subscribe(() => {
|
||||
this.showGameResult.set(true);
|
||||
console.log('Game result dialog should be shown now');
|
||||
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()!);
|
||||
}
|
||||
|
|
|
@ -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();
|
||||
}
|
||||
|
|
|
@ -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