Skip to content

Instantly share code, notes, and snippets.

@jaburns
Created February 18, 2015 00:13
Show Gist options
  • Save jaburns/31f0dfa1af8656de3759 to your computer and use it in GitHub Desktop.
Save jaburns/31f0dfa1af8656de3759 to your computer and use it in GitHub Desktop.
Sound detector
'use strict';
var playerModes = require('../../game/player').modes;
/**
* This module exports a single function that checks a game state and
* its latest diff for game sound triggers and plays the appropriate
* sounds on the provided AudioPlayer object.
*/
var soundChecks = {
'sound_throw': [projectileExistenceChanged(true, 'axe', true)],
'sound_shoot': [projectileExistenceChanged(true, 'laser', true)],
'sound_hit': [somePlayerStateChanged('alive', true, false)],
'sound_jump': [somePlayerStateChanged('mode', playerModes.STANDING, playerModes.JUMPING)],
'sound_slam': [somePlayerStateChanged('mode', playerModes.DROPKICK, null)],
'sound_dash': [somePlayerStateChanged('mode', null, playerModes.DROPKICK)],
'sound_die': [thisPlayerStateChanged('alive', true, false)],
'sound_rekt': [{after:100, event:thisPlayerStateChanged('alive', true, false)}]
};
module.exports = function(audioPlayer, state0, state1, playerId) {
for (var k in soundChecks) {
for (var i = 0; i < soundChecks[k].length; ++i) {
var checker = soundChecks[k][i];
if (typeof checker === 'function') {
if (checker(state0, state1, playerId)) {
audioPlayer.playSound(k);
}
}
else if (checker.event(state0, state1, playerId)) {
setTimeout(audioPlayer.playSound.bind(audioPlayer, k), checker.after);
}
}
}
}
// If `created` is true then check for a matching newly created projectile, otherwise
// check for a projectile which has just been destroyed.
function projectileExistenceChanged(created, type, owned) {
return function(state0, state1, playerId) {
var filter = {type: type};
if (owned) filter.ownerId = playerId;
var ids = _.map([state0, state1], function(state) {
return _.chain(state.projectiles)
.filter(filter)
.pluck('id')
.value();
});
return _.difference(ids[created ? 1 : 0], ids[created ? 0 : 1]).length > 0;
}
}
function somePlayerStateChanged(property, oldValue, newValue) {
return function(state0, state1, playerId) {
return _.chain(Object.keys(state1.players))
.map(playerStateCheck.bind(null, property, oldValue, newValue, state0, state1))
.any()
.value();
}
}
function thisPlayerStateChanged(property, oldValue, newValue) {
return playerStateCheck.bind(null, property, oldValue, newValue);
}
function playerStateCheck(property, oldValue, newValue, state0, state1, playerId) {
oldValue = oldValue !== null ? oldValue : state0.players[playerId][property];
newValue = newValue !== null ? newValue : state1.players[playerId][property];
return _.chain([state0.players[playerId], state1.players[playerId]])
.pluck(property)
.isEqual([oldValue, newValue])
.value();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment