casino/frontend/src/app/services/jackpot.service.ts

130 lines
3 KiB
TypeScript

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class JackpotService {
private readonly INITIAL_JACKPOT = 1234567;
private readonly INITIAL_TIME = '04:59';
private readonly UPDATE_INTERVAL = 2000;
private readonly INCREASE_THRESHOLDS = {
MEGA: 0.997,
BONUS: 0.97,
BASE: 0.5,
};
private readonly INCREASE_RANGES = {
MEGA: {
MIN: 30000,
MAX: 100000,
},
BONUS: {
MIN: 2000,
MAX: 15000,
},
BASE: {
MIN: 100,
MAX: 1000,
},
};
private readonly TIME_LIMITS = {
MINUTES: 4,
SECONDS: 59,
URGENT_THRESHOLD: 30,
};
private readonly jackpot = new BehaviorSubject<number>(this.INITIAL_JACKPOT);
private readonly timeLeft = new BehaviorSubject<string>(this.INITIAL_TIME);
private lastUpdateTime = Date.now();
private minutes = this.TIME_LIMITS.MINUTES;
private seconds = this.TIME_LIMITS.SECONDS;
readonly currentJackpot$ = this.jackpot.asObservable();
readonly timeLeft$ = this.timeLeft.asObservable();
updateJackpot(): void {
if (!this.shouldUpdate()) return;
const increase = this.calculateIncrease();
if (increase > 0) {
this.updateJackpotValue(increase);
this.lastUpdateTime = Date.now();
}
}
updateTimeLeft(): void {
this.updateTimers();
this.updateTimeDisplay();
}
isUrgent(): boolean {
return this.minutes === 0 && this.seconds <= this.TIME_LIMITS.URGENT_THRESHOLD;
}
private shouldUpdate(): boolean {
return Date.now() - this.lastUpdateTime >= this.UPDATE_INTERVAL;
}
private calculateIncrease(): number {
const random = Math.random();
if (random > this.INCREASE_THRESHOLDS.MEGA) {
return this.getRandomIncrease(this.INCREASE_RANGES.MEGA);
}
if (random > this.INCREASE_THRESHOLDS.BONUS) {
return this.getRandomIncrease(this.INCREASE_RANGES.BONUS);
}
if (random > this.INCREASE_THRESHOLDS.BASE) {
return this.getRandomIncrease(this.INCREASE_RANGES.BASE);
}
return 0;
}
private getRandomIncrease(range: { MIN: number; MAX: number }): number {
return Math.floor(Math.random() * (range.MAX - range.MIN) + range.MIN);
}
private updateJackpotValue(increase: number): void {
this.jackpot.next(this.jackpot.value + increase);
}
private updateTimers(): void {
if (this.seconds === 0) {
this.handleMinuteChange();
} else {
this.seconds--;
}
}
private handleMinuteChange(): void {
if (this.minutes === 0) {
this.resetTimers();
} else {
this.minutes--;
this.seconds = this.TIME_LIMITS.SECONDS;
}
}
private resetTimers(): void {
this.minutes = this.TIME_LIMITS.MINUTES;
this.seconds = this.TIME_LIMITS.SECONDS;
}
private updateTimeDisplay(): void {
this.timeLeft.next(this.formatTime());
}
private formatTime(): string {
return `${this.padNumber(this.minutes)}:${this.padNumber(this.seconds)}`;
}
private padNumber(num: number): string {
return num.toString().padStart(2, '0');
}
}