feat: add audio features and sounds to the game #197
12 changed files with 140 additions and 1 deletions
BIN
frontend/public/sounds/bet.mp3
Normal file
BIN
frontend/public/sounds/bet.mp3
Normal file
Binary file not shown.
BIN
frontend/public/sounds/coinflip.mp3
Normal file
BIN
frontend/public/sounds/coinflip.mp3
Normal file
Binary file not shown.
BIN
frontend/public/sounds/drag.mp3
Normal file
BIN
frontend/public/sounds/drag.mp3
Normal file
Binary file not shown.
BIN
frontend/public/sounds/win.mp3
Normal file
BIN
frontend/public/sounds/win.mp3
Normal file
Binary file not shown.
|
@ -1,10 +1,12 @@
|
|||
import { Component, HostListener, signal } from '@angular/core';
|
||||
import { Component, HostListener, inject, signal } from '@angular/core';
|
||||
import { RouterOutlet } from '@angular/router';
|
||||
import { NavbarComponent } from './shared/components/navbar/navbar.component';
|
||||
import { FooterComponent } from './shared/components/footer/footer.component';
|
||||
import { LoginComponent } from './feature/auth/login/login.component';
|
||||
import { RegisterComponent } from './feature/auth/register/register.component';
|
||||
import { RecoverPasswordComponent } from './feature/auth/recover-password/recover-password.component';
|
||||
import { PlaySoundDirective } from './shared/directives/play-sound.directive';
|
||||
import { SoundInitializerService } from './shared/services/sound-initializer.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-root',
|
||||
|
@ -16,14 +18,22 @@ import { RecoverPasswordComponent } from './feature/auth/recover-password/recove
|
|||
LoginComponent,
|
||||
RegisterComponent,
|
||||
RecoverPasswordComponent,
|
||||
PlaySoundDirective,
|
||||
],
|
||||
templateUrl: './app.component.html',
|
||||
hostDirectives: [PlaySoundDirective],
|
||||
})
|
||||
export class AppComponent {
|
||||
private soundInitializer = inject(SoundInitializerService);
|
||||
|
||||
showLogin = signal(false);
|
||||
showRegister = signal(false);
|
||||
showRecoverPassword = signal(false);
|
||||
|
||||
constructor() {
|
||||
this.soundInitializer.initialize();
|
||||
}
|
||||
|
||||
@HostListener('document:keydown.escape')
|
||||
handleEscapeKey() {
|
||||
this.hideAuthForms();
|
||||
|
|
|
@ -14,6 +14,7 @@ import { UserService } from '@service/user.service';
|
|||
import { timer } from 'rxjs';
|
||||
import { DebtDialogComponent } from '@shared/components/debt-dialog/debt-dialog.component';
|
||||
import { AuthService } from '@service/auth.service';
|
||||
import { AudioService } from '@shared/services/audio.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-blackjack',
|
||||
|
@ -35,6 +36,7 @@ export default class BlackjackComponent implements OnInit {
|
|||
private userService = inject(UserService);
|
||||
private authService = inject(AuthService);
|
||||
private blackjackService = inject(BlackjackService);
|
||||
private audioService = inject(AudioService);
|
||||
|
||||
dealerCards = signal<Card[]>([]);
|
||||
playerCards = signal<Card[]>([]);
|
||||
|
@ -91,6 +93,9 @@ export default class BlackjackComponent implements OnInit {
|
|||
// Show the result dialog after refreshing user data
|
||||
timer(500).subscribe(() => {
|
||||
this.showGameResult.set(true);
|
||||
if (game.state === GameState.PLAYER_WON || game.state === GameState.PLAYER_BLACKJACK) {
|
||||
this.audioService.playWinSound();
|
||||
}
|
||||
console.log('Game result dialog shown after delay');
|
||||
});
|
||||
});
|
||||
|
@ -99,6 +104,7 @@ export default class BlackjackComponent implements OnInit {
|
|||
|
||||
onNewGame(bet: number): void {
|
||||
this.isActionInProgress.set(true);
|
||||
this.audioService.playBetSound();
|
||||
|
||||
this.blackjackService.startGame(bet).subscribe({
|
||||
next: (game) => {
|
||||
|
@ -117,6 +123,7 @@ export default class BlackjackComponent implements OnInit {
|
|||
if (!this.currentGameId() || this.isActionInProgress()) return;
|
||||
|
||||
this.isActionInProgress.set(true);
|
||||
this.audioService.playBetSound();
|
||||
|
||||
this.blackjackService.hit(this.currentGameId()!).subscribe({
|
||||
next: (game) => {
|
||||
|
@ -143,6 +150,7 @@ export default class BlackjackComponent implements OnInit {
|
|||
}
|
||||
|
||||
this.isActionInProgress.set(true);
|
||||
this.audioService.playBetSound();
|
||||
|
||||
this.blackjackService.stand(this.currentGameId()!).subscribe({
|
||||
next: (game) => {
|
||||
|
@ -167,6 +175,7 @@ export default class BlackjackComponent implements OnInit {
|
|||
}
|
||||
|
||||
this.isActionInProgress.set(true);
|
||||
this.audioService.playBetSound();
|
||||
|
||||
this.blackjackService.doubleDown(this.currentGameId()!).subscribe({
|
||||
next: (game) => {
|
||||
|
|
|
@ -40,6 +40,7 @@ export default class SlotsComponent implements OnInit, OnDestroy {
|
|||
private userService = inject(UserService);
|
||||
private authService = inject(AuthService);
|
||||
private userSubscription: Subscription | undefined;
|
||||
private winSound: HTMLAudioElement;
|
||||
|
||||
slotInfo = signal<Record<string, number> | null>(null);
|
||||
slotResult = signal<SlotResult>({
|
||||
|
@ -56,6 +57,10 @@ export default class SlotsComponent implements OnInit, OnDestroy {
|
|||
betAmount = signal<number>(1);
|
||||
isSpinning = false;
|
||||
|
||||
constructor() {
|
||||
this.winSound = new Audio('/sounds/win.mp3');
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.httpClient.get<Record<string, number>>('/backend/slots/info').subscribe((data) => {
|
||||
this.slotInfo.set(data);
|
||||
|
@ -111,6 +116,7 @@ export default class SlotsComponent implements OnInit, OnDestroy {
|
|||
this.slotResult.set(result);
|
||||
|
||||
if (result.status === 'win') {
|
||||
this.winSound.play();
|
||||
this.userService.updateLocalBalance(result.amount);
|
||||
}
|
||||
|
||||
|
|
|
@ -24,6 +24,7 @@ export default class LootboxOpeningComponent {
|
|||
prizeList: Reward[] = [];
|
||||
animationCompleted = false;
|
||||
currentUser: User | null = null;
|
||||
private winSound: HTMLAudioElement;
|
||||
|
||||
constructor(
|
||||
private route: ActivatedRoute,
|
||||
|
@ -33,6 +34,7 @@ export default class LootboxOpeningComponent {
|
|||
private authService: AuthService,
|
||||
private cdr: ChangeDetectorRef
|
||||
) {
|
||||
this.winSound = new Audio('/sounds/win.mp3');
|
||||
this.loadLootbox();
|
||||
this.authService.userSubject.subscribe((user) => {
|
||||
this.currentUser = user;
|
||||
|
@ -145,6 +147,7 @@ export default class LootboxOpeningComponent {
|
|||
this.animationCompleted = true;
|
||||
|
||||
if (this.wonReward) {
|
||||
this.winSound.play();
|
||||
this.userService.updateLocalBalance(this.wonReward.value);
|
||||
}
|
||||
|
||||
|
|
15
frontend/src/app/shared/directives/play-sound.directive.ts
Normal file
15
frontend/src/app/shared/directives/play-sound.directive.ts
Normal file
|
@ -0,0 +1,15 @@
|
|||
import { Directive, HostListener, inject } from '@angular/core';
|
||||
import { AudioService } from '../services/audio.service';
|
||||
|
||||
@Directive({
|
||||
selector: '[appPlaySound]',
|
||||
standalone: true,
|
||||
})
|
||||
export class PlaySoundDirective {
|
||||
private audioService = inject(AudioService);
|
||||
|
||||
@HostListener('click')
|
||||
onClick() {
|
||||
this.audioService.playBetSound();
|
||||
}
|
||||
}
|
30
frontend/src/app/shared/services/audio.service.ts
Normal file
30
frontend/src/app/shared/services/audio.service.ts
Normal file
|
@ -0,0 +1,30 @@
|
|||
import { Injectable } from '@angular/core';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class AudioService {
|
||||
private audioCache = new Map<string, HTMLAudioElement>();
|
||||
|
||||
private getAudio(soundName: string): HTMLAudioElement {
|
||||
if (this.audioCache.has(soundName)) {
|
||||
ptran marked this conversation as resolved
Outdated
|
||||
return this.audioCache.get(soundName)!;
|
||||
}
|
||||
|
||||
const audio = new Audio(`/sounds/${soundName}.mp3`);
|
||||
this.audioCache.set(soundName, audio);
|
||||
return audio;
|
||||
}
|
||||
|
||||
playBetSound(): void {
|
||||
const audio = this.getAudio('bet.mp3');
|
||||
audio.currentTime = 0;
|
||||
audio.play().catch((error) => console.error('Error playing bet sound:', error));
|
||||
}
|
||||
|
||||
playWinSound(): void {
|
||||
const audio = this.getAudio('win.mp3');
|
||||
audio.currentTime = 0;
|
||||
audio.play().catch((error) => console.error('Error playing win sound:', error));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,51 @@
|
|||
import { Injectable, Renderer2, RendererFactory2 } from '@angular/core';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class SoundInitializerService {
|
||||
private renderer: Renderer2;
|
||||
private observer: MutationObserver;
|
||||
|
||||
constructor(rendererFactory: RendererFactory2) {
|
||||
this.renderer = rendererFactory.createRenderer(null, null);
|
||||
|
||||
this.observer = new MutationObserver((mutations) => {
|
||||
mutations.forEach((mutation) => {
|
||||
mutation.addedNodes.forEach((node) => {
|
||||
if (node instanceof HTMLElement) {
|
||||
this.processElement(node);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
initialize() {
|
||||
document.querySelectorAll('button, a').forEach((element) => {
|
||||
if (!element.hasAttribute('appPlaySound')) {
|
||||
this.renderer.setAttribute(element, 'appPlaySound', '');
|
||||
}
|
||||
});
|
||||
|
||||
this.observer.observe(document.body, {
|
||||
childList: true,
|
||||
subtree: true,
|
||||
});
|
||||
}
|
||||
|
||||
private processElement(element: HTMLElement) {
|
||||
if (
|
||||
(element.tagName === 'BUTTON' || element.tagName === 'A') &&
|
||||
!element.hasAttribute('appPlaySound')
|
||||
) {
|
||||
this.renderer.setAttribute(element, 'appPlaySound', '');
|
||||
}
|
||||
|
||||
element.querySelectorAll('button, a').forEach((child) => {
|
||||
if (!child.hasAttribute('appPlaySound')) {
|
||||
this.renderer.setAttribute(child, 'appPlaySound', '');
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
|
@ -174,3 +174,18 @@ a {
|
|||
.modal-card .button-secondary {
|
||||
@apply bg-deep-blue-light/50 hover:bg-deep-blue-light w-full py-2.5 my-2 border border-deep-blue-light/30 hover:border-deep-blue-light/50;
|
||||
}
|
||||
|
||||
button,
|
||||
a {
|
||||
-webkit-tap-highlight-color: transparent;
|
||||
}
|
||||
|
||||
button[appPlaySound],
|
||||
a[appPlaySound] {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button:not([appPlaySound]),
|
||||
a:not([appPlaySound]) {
|
||||
--add-sound-directive: true;
|
||||
}
|
||||
|
|
Reference in a new issue
flip this if statement for better readability
`package main
import (
"context"
"crypto/x509"
"encoding/json"
"fmt"
"io"
stdlog "log"
"maps"
"net/http"
"os"
"os/signal"
"slices"
"strings"
"syscall"
"time"
)
func main() {
// traefik config inits
tConfig := cmd.NewTraefikConfiguration()
Complete documentation is available at https://traefik.io`,
Configuration: tConfig,
Resources: loaders,
Run: func(_ []string) error {
return runCmd(&tConfig.Configuration)
},
}
}
func runCmd(staticConfiguration *static.Configuration) error {
if err := setupLogger(staticConfiguration); err != nil {
return fmt.Errorf("setting up logger: %w", err)
}
}
func setupServer(staticConfiguration *static.Configuration) (*server.Server, error) {
providerAggregator := aggregator.NewProviderAggregator(*staticConfiguration.Providers)
}
func getHTTPChallengeHandler(acmeProviders []*acme.Provider, httpChallengeProvider http.Handler) http.Handler {
var acmeHTTPHandler http.Handler
for _, p := range acmeProviders {
if p != nil && p.HTTPChallenge != nil {
acmeHTTPHandler = httpChallengeProvider
break
}
}
return acmeHTTPHandler
}
func getDefaultsEntrypoints(staticConfiguration *static.Configuration) []string {
var defaultEntryPoints []string
}
func switchRouter(routerFactory *server.RouterFactory, serverEntryPointsTCP server.TCPEntryPoints, serverEntryPointsUDP server.UDPEntryPoints) func(conf dynamic.Configuration) {
return func(conf dynamic.Configuration) {
rtConf := runtime.NewConfig(conf)
}
// initACMEProvider creates and registers acme.Provider instances corresponding to the configured ACME certificate resolvers.
func initACMEProvider(c *static.Configuration, providerAggregator *aggregator.ProviderAggregator, tlsManager *traefiktls.Manager, httpChallengeProvider, tlsChallengeProvider challenge.Provider, routinesPool *safe.Pool) []*acme.Provider {
localStores := map[string]*acme.LocalStore{}
}
// initTailscaleProviders creates and registers tailscale.Provider instances corresponding to the configured Tailscale certificate resolvers.
func initTailscaleProviders(cfg *static.Configuration, providerAggregator *aggregator.ProviderAggregator) []*tailscale.Provider {
var providers []*tailscale.Provider
for name, resolver := range cfg.CertificatesResolvers {
if resolver.Tailscale == nil {
continue
}
}
func registerMetricClients(metricsConfig *types.Metrics) []metrics.Registry {
if metricsConfig == nil {
return nil
}
}
func appendCertMetric(gauge gokitmetrics.Gauge, certificate *x509.Certificate) {
slices.Sort(certificate.DNSNames)
}
func setupAccessLog(conf *types.AccessLog) *accesslog.Handler {
if conf == nil {
return nil
}
}
func setupTracing(conf *static.Tracing) (*tracing.Tracer, io.Closer) {
if conf == nil {
return nil, nil
}
}
func checkNewVersion() {
ticker := time.Tick(24 * time.Hour)
safe.Go(func() {
for time.Sleep(10 * time.Minute); ; <-ticker {
version.CheckNewVersion()
}
})
}
func stats(staticConfiguration *static.Configuration) {
logger := log.With().Logger()
Stats collection is disabled.
Help us improve Traefik by turning this feature on :)
More details on: https://doc.traefik.io/traefik/contributing/data-collection/
`)
}
}
func collect(staticConfiguration *static.Configuration) {
ticker := time.Tick(24 * time.Hour)
safe.Go(func() {
for time.Sleep(10 * time.Minute); ; <-ticker {
if err := collector.Collect(staticConfiguration); err != nil {
log.Debug().Err(err).Send()
}
}
})
}
`