HTML5 Canvas [139]
function resetApp() {
playSound(SOUND_EXPLODE,0);
playSound(SOUND_SHOOT,0);
startLevel();
appState = STATE_PLAYING;
}
The playSound() function operates in a similar way to iteration #3. It loops through the soundPool array looking for a sound that it can play. However, in this version, we check to see whether the HTMLAudioElement has ended (tSound.element.ended) or if it has not been played (!tSound.played) yet. We also check whether the value in the sound parameter matches the name property of the sound object in soundPool (tSound.name == sound):
function playSound(sound,volume) {
var soundFound = false;
var soundIndex = 0;
var tempSound;
if (soundPool.length > 0) {
while (!soundFound && soundIndex < soundPool.length) {
var tSound = soundPool[soundIndex];
if ((tSound.element.ended || !tSound.played) && tSound.name == sound) {
soundFound = true;
tSound.played = true;
} else {
soundIndex++;
}
}
}
Using this method, we play a sound only if it has not been played, it has ended, and it already has the sound file loaded that we need to play. There is no pause to load (most of the time), and sounds play at pretty much the time we need them to play. If we need more sounds, we can load more up front, or set MAX_SOUNDS to a number greater than the number of preloaded sounds. If we do that, we will create new sound objects on the fly (although this might still give you a pause when loading from a web server):
if (soundFound) {
tempSound = soundPool[soundIndex].element;
tempSound.volume = volume;
tempSound.play();
} else if (soundPool.length < MAX_SOUNDS){
tempSound = document.createElement("audio");
tempSound.setAttribute("src", sound + "." + audioType);
tempSound.volume = volume;
tempSound.play();
soundPool.push({name:sound, element:tempSound, type:audioType, played:true});
}
Go ahead and try this code. It is CH7EX9.html in the code distribution, or you can type in the program listing.
Other stuff you could do to improve the game
Since the next couple chapters introduce game concepts, we really shouldn’t go much further with Space Raiders. Still, if you were going to finish this game, these are the things you might consider doing:
Add a score.
Increase the aliens’ speed on each new level.
Collision-detect the aliens and the player.
Make an object pool for missiles and aliens.
Slow down firing with a wait() state or frame counter.
Add explosions.
Include a title sequence, level sequence, and end game sequence.
Add a looping soundtrack.
The final code for Space Raiders
Example 7-6 shows the final code for the Space Raiders game (CH7EX9.html).
Example 7-6. Space Raiders with optimized dynamic network sound and state loader
-->