Hi folks, especially programmers,
I have a small debate yesterday with my friend about programming.
We have discussed many topics, but one interested me much. So, to introduce our conflict, read this piece of c++ code:
//Code #1
#include <bgt_kit/bgt_kit.hpp>
timer steptimer;
int steptime=250;
sound step;
void gameloop()
{
while (true)
{
if (key_pressed(KEY_W) and steptimer.elapsed()>=steptime)
{
step.load("Sounds/step"+std::to_string(random(1, 3))+".ogg");
step.play();
steptimer.restart();
}
Sleep(100);
}
}
int main()
{
bgt_kit_init();
gameloop();
}
This is how I manage step sounds now, I saw it in many example codes for bgt, so considered it as normal. My friend however was shocked, saying it is inefficient and harsh for harddrives.
After bit of discussion, I thought out this modification:
//Code #2
#include <bgt_kit/bgt_kit.hpp>
timer steptimer;
int steptime=250;
std::unordered_map<std::string, sound> audiomanager;
void gameloop()
{
while (true)
{
if (key_pressed(KEY_W) and steptimer.elapsed()>=steptime)
{
audiomanager["Sounds/step"+std::to_string(random(1, 3))+".ogg"].play();
steptimer.restart();
}
Sleep(100);
}
}
void load_sounds()
{
std::vector<std::string> files=find_files("Sounds/");
for (int i=0;i<files.size();i++) {
audiomanager["sounds/"+files[i]]=sound();
audiomanager["Sounds/"+files[i]].load("Sounds/"+files[i]);
}
}
int main()
{
bgt_kit_init();
load_sounds();
gameloop();
}
Then I realized, that this solution does not allow playing one sound more times, bad for sounds of steps. So I thought out a newone, in this form:
//Code #3
#include <bgt_kit/bgt_kit.hpp>
timer steptimer;
int steptime=250;
sound step;
std::unordered_map<std::string, std::string> audiostorage;
void gameloop()
{
while (true)
{
if (key_pressed(KEY_W) and steptimer.elapsed()>=steptime)
{
step.load_from_memory(audiostorage["Sounds/step"+std::to_string(random(1, 3))+".ogg"]);
step.play();
steptimer.restart();
}
Sleep(100);
}
}
void load_sounds()
{
std::vector<std::string> files=find_files("Sounds/");
for (int i=0;i<files.size();i++) {
file reader;
reader.open("Sounds/"+files[i], "rb");
audiostorage["sounds/"+files[i]]=reader.read();
reader.close();
}
}
int main()
{
bgt_kit_init();
load_sounds();
gameloop();
}
And one second after it I added one modification in Code #4, which I will not write here, because only thing changed is, that method load_from_memory does not grab string as a parameter, but pointer to its beginning and its length, so there is no need for copy full data twice - onetime to the load-from_memory method, second to the sound object by that method.
So, what do you think? Which code piece is best to use? Does loading of all sounds to the memory make sense, or it is premature optimization?
I would be happy to hear your opinions.
Best regards
Rastislav