function HeartManager() { this.countHearts = HeartManager.DEFAULT_COUNT; this.countMaxHearts = HeartManager.DEFAULT_COUNT; this.onChangeCountListeners = []; this.onChangeMaxCountListeners = []; this.onChangeGameOverListeners = []; } HeartManager.prototype.callListener = function(functionArray) { if(functionArray.length > 0) { for(var i = 0; i < functionArray.length; i++) { functionArray[i](this.score); } } } HeartManager.prototype.addOnChangeCountListener = function(onChangeFunction) { this.onChangeCountListeners.push(onChangeFunction); } HeartManager.prototype.removeOnChangeCountListener = function(onChangeFunction) { var itemIndex = this.onChangeCountListeners.indexOf(onChangeFunction); if(itemIndex > -1) this.onChangeCountListeners.splice(itemIndex, 1); } HeartManager.prototype.addOnChangeMaxCountListener = function(onChangeMaxFunction) { this.onChangeMaxCountListeners.push(onChangeMaxFunction); } HeartManager.prototype.removeOnChangeMaxCountListener = function(onChangeMaxFunction) { var itemIndex = this.onChangeMaxCountListeners.indexOf(onChangeMaxFunction); if(itemIndex > -1) this.onChangeMaxCountListeners.splice(itemIndex, 1); } HeartManager.prototype.addOnChangeGameOverListener = function(onChangeGameOverFunction) { this.onChangeGameOverListeners.push(onChangeGameOverFunction); } HeartManager.prototype.removeOnChangeHighScoreListener = function(onChangeGameOverFunction) { var itemIndex = this.onChangeGameOverListeners.indexOf(onChangeGameOverFunction); if(itemIndex > -1) this.onChangeGameOverListeners.splice(itemIndex, 1); } HeartManager.prototype.removeAllListeners = function() { this.onChangeCountListeners = []; this.onChangeMaxCountListeners = []; this.onChangeGameOverListeners = []; } HeartManager.prototype.setCount = function(amount) { var beforeCountHearts = this.countHearts; this.countHearts = amount; if(this.countHearts < 0) this.countHearts = 0; else if(this.countHearts > this.countMaxHearts) this.countHearts = this.countMaxHearts; if(beforeCountHearts !== this.countHearts) this.callListener(this.onChangeCountListeners); if(this.countHearts === 0) this.callListener(this.onChangeGameOverListeners); } HeartManager.prototype.getCount = function() { return this.countHearts; } HeartManager.prototype.setMaxCount = function(amount) { var beforeCountHearts = this.countMaxHearts; this.countMaxHearts = amount; if(this.countMaxHearts > HeartManager.HEART_MAX_COUNT) this.countMaxHearts = HeartManager.HEART_MAX_COUNT; if(beforeCountHearts !== this.countMaxHearts) this.callListener(this.onChangeMaxCountListeners); if(this.countHearts > this.countMaxHearts) this.setCount(this.countMaxHearts); } HeartManager.prototype.getMaxCount = function() { return this.countMaxHearts; } HeartManager.prototype.addHearts = function(amount) { this.setCount(this.countHearts + amount); } HeartManager.prototype.breakHearts = function(amount) { this.addHearts(-1 * amount); } HeartManager.DEFAULT_COUNT = 3; HeartManager.HEART_MAX_COUNT = 5;