From e6e29440563e33bb67e0ad51f9fb6c5c2c3fe809 Mon Sep 17 00:00:00 2001 From: Elizabeth Hunt Date: Thu, 7 Mar 2024 20:45:47 -0700 Subject: level one (applications prototype finished!) --- src/engine/systems/Music.ts | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 src/engine/systems/Music.ts (limited to 'src/engine/systems/Music.ts') diff --git a/src/engine/systems/Music.ts b/src/engine/systems/Music.ts new file mode 100644 index 0000000..6e2004d --- /dev/null +++ b/src/engine/systems/Music.ts @@ -0,0 +1,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(); + } + } +} -- cgit v1.2.3-70-g09d2