75 lines
1.6 KiB
JavaScript
75 lines
1.6 KiB
JavaScript
class ScoreManager {
|
|
|
|
constructor() {
|
|
this.score = 0;
|
|
this.highScore = 0;
|
|
|
|
this.onChangeScoreListeners = [];
|
|
this.onChangeHighScoreListeners = [];
|
|
}
|
|
|
|
callListener(functionArray) {
|
|
if(functionArray.length > 0) {
|
|
for(let i = 0; i < functionArray.length; i++) {
|
|
functionArray[i](this.score);
|
|
}
|
|
}
|
|
}
|
|
|
|
addOnChangeScoreListener(onChangeFunction) {
|
|
this.onChangeScoreListeners.push(onChangeFunction);
|
|
}
|
|
|
|
removeOnChangeScoreListener(onChangeFunction) {
|
|
let itemIndex = this.onChangeScoreListeners.indexOf(onChangeFunction);
|
|
if(itemIndex > -1)
|
|
this.onChangeScoreListeners.splice(itemIndex, 1);
|
|
}
|
|
|
|
addOnChangeHighScoreListener(onChangeHighScoreFunction) {
|
|
this.onChangeHighScoreListeners.push(onChangeHighScoreFunction);
|
|
}
|
|
|
|
removeOnChangeHighScoreListener(onChangeHighScoreFunction) {
|
|
let itemIndex = this.onChangeHighScoreListeners.indexOf(onChangeHighScoreFunction);
|
|
if(itemIndex > -1)
|
|
this.onChangeHighScoreListeners.splice(itemIndex, 1);
|
|
}
|
|
|
|
removeAllListeners() {
|
|
this.onChangeScoreListeners = [];
|
|
this.onChangeHighScoreListeners = [];
|
|
}
|
|
|
|
|
|
getScore() {
|
|
return this.score;
|
|
}
|
|
|
|
getHighScore() {
|
|
return this.highScore;
|
|
}
|
|
|
|
|
|
plusScore(amount) {
|
|
this.setScore(this.score + amount);
|
|
}
|
|
|
|
minusScore(amount) {
|
|
this.plusScore(-1 * amount);
|
|
}
|
|
|
|
setScore(value) {
|
|
let beforeScore = this.score;
|
|
this.score = value;
|
|
|
|
// update score
|
|
if(beforeScore !== this.score)
|
|
this.callListener(this.onChangeScoreListeners);
|
|
|
|
// update high score
|
|
if(this.score > this.highScore)
|
|
this.callListener(this.onChangeHighScoreListeners);
|
|
}
|
|
|
|
} |