summaryrefslogtreecommitdiff
path: root/src/engine/systems/Music.ts
blob: 6e2004d63fc75027e0b16924e609b404f86b33c4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import { System, SystemNames } from ".";
import { Music as GameMusic, SOUNDS } from "../config";

export class Music extends System {
  private songs: string[] = [];
  private currentSong?: string;

  constructor() {
    super(SystemNames.Music);

    this.songs = Array.from(GameMusic.states!.values()).map(
      (state) => state.name,
    );
  }

  private chooseRandomSong() {
    return this.songs[Math.floor(Math.random() * this.songs.length)];
  }

  public playNext() {
    let nextSong = this.chooseRandomSong();
    while (nextSong === this.currentSong) {
      nextSong = this.chooseRandomSong();
    }

    this.currentSong = nextSong;
    SOUNDS.get(this.currentSong)?.play();

    // when done, play next song
    SOUNDS.get(this.currentSong)?.addEventListener("ended", () => {
      this.playNext();
    });
  }

  public update(_dt: number) {
    if (!this.currentSong) {
      this.playNext();
    }
  }
}