Module: Music

Defined in:
lib/fantasy/music.rb

Constant Summary collapse

@@musics =
{}
@@actual_song =
nil

Class Method Summary collapse

Class Method Details

.base_pathObject



51
52
53
# File 'lib/fantasy/music.rb', line 51

def base_path
  "#{Dir.pwd}/musics"
end

.locate_music(music_name) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/fantasy/music.rb', line 29

def locate_music(music_name)
  return @@musics[music_name] if @@musics[music_name]

  puts "Initialize Music: '#{music_name}'"

  file_name = Dir.entries(base_path).find { |e| e =~ /^#{music_name}($|\.)/ }

  raise "Music file not found with name '#{music_name}'" if file_name.nil?

  @@musics[music_name] = Gosu::Song.new("#{base_path}/#{file_name}")

  @@musics[music_name]
end

.play(music_name, volume: nil) ⇒ Object



8
9
10
11
12
13
14
15
# File 'lib/fantasy/music.rb', line 8

def play(music_name, volume: nil)
  stop

  @@actual_song = locate_music(music_name)
  @@actual_song.play(true)

  self.volume = volume unless volume.nil?
end

.preload_musicsObject



43
44
45
46
47
48
49
# File 'lib/fantasy/music.rb', line 43

def preload_musics
  return unless Dir.exist?(base_path)

  Dir.each_child(base_path) do |file_name|
    locate_music(file_name) unless file_name.start_with?(".")
  end
end

.stopObject



17
18
19
# File 'lib/fantasy/music.rb', line 17

def stop
  @@actual_song&.stop
end

.volumeObject



21
22
23
# File 'lib/fantasy/music.rb', line 21

def volume
  @@actual_song&.volume
end

.volume=(value) ⇒ Object



25
26
27
# File 'lib/fantasy/music.rb', line 25

def volume=(value)
  @@actual_song.volume = value unless @@actual_song.nil?
end