Add: HeartManager, HeartGauge
This commit is contained in:
@@ -0,0 +1,95 @@
|
||||
class HeartManager {
|
||||
|
||||
constructor() {
|
||||
this.countHearts = HeartManager.DEFAULT_MAX_COUNT;
|
||||
this.countMaxHearts = HeartManager.DEFAULT_MAX_COUNT;
|
||||
|
||||
this.onChangeHeartListeners = [];
|
||||
this.onChangeGameOverListeners = [];
|
||||
}
|
||||
|
||||
callListener(functionArray) {
|
||||
if(functionArray.length > 0) {
|
||||
for(let i = 0; i < functionArray.length; i++) {
|
||||
functionArray[i](this.score);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
addOnChangeHeartListener(onChangeFunction) {
|
||||
this.onChangeHeartListeners.push(onChangeFunction);
|
||||
}
|
||||
|
||||
removeOnChangeHeartListener(onChangeFunction) {
|
||||
let itemIndex = this.onChangeHeartListeners.indexOf(onChangeFunction);
|
||||
if(itemIndex > -1)
|
||||
this.onChangeHeartListeners.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.onChangeHeartListeners = [];
|
||||
this.onChangeGameOverListeners = [];
|
||||
}
|
||||
|
||||
|
||||
setHearts(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.onChangeHeartListeners);
|
||||
|
||||
if(this.countHearts === 0)
|
||||
this.callListener(this.onChangeGameOverListeners);
|
||||
}
|
||||
|
||||
setMaxHearts(amount) {
|
||||
this.countMaxHearts = amount;
|
||||
|
||||
if(this.countHearts > this.countMaxHearts)
|
||||
this.countHearts = this.countMaxHearts;
|
||||
}
|
||||
|
||||
getHearts() {
|
||||
return this.countHearts;
|
||||
}
|
||||
|
||||
addHearts(amount) {
|
||||
this.setHearts(this.countHearts + amount);
|
||||
|
||||
}
|
||||
|
||||
breakHearts(amount) {
|
||||
this.addHearts(-1 * amount);
|
||||
}
|
||||
|
||||
setScore(value) {
|
||||
let beforeScore = this.score;
|
||||
this.score = value;
|
||||
|
||||
// update score
|
||||
if(beforeScore !== this.score)
|
||||
this.callListener(this.onChangeHeartListeners);
|
||||
|
||||
// update high score
|
||||
if(this.score > this.highScore)
|
||||
this.callListener(this.onChangeGameOverListeners);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
HeartManager.DEFAULT_MAX_COUNT = 3;
|
||||
Reference in New Issue
Block a user