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