I'm using a game object that has different getters and methods within it. One of the parameters of my assignment is that the "playerDies" method has to subtract 1 from the lives if it is greater than zero and it cannot go below 0 (so it can't be -1 which is what is happening now). This topic is fairly new to me so I'm not sure what I can do to execute the subtraction only when there is a specific value. I've tried using an if-else statement but that resulted in the code not working. My code:
var game = {
lives: 3,
coins: 0,
get points() {
return this.coins * 10;
},
playerDies: function() {
return this.lives -= 1;
},
newGame: function() {
this.lives = 3;
this.coins = 0;
},
};
console.log("lives = " + game.lives); // should be 3
console.log("coins = " + game.coins); // should be 0
console.log("points = " + game.points); // should be 0
game.coins = 0;
console.log("points = " + game.points); // should be 20
game.playerDies();
console.log("lives = " + game.lives); // should be 2
game.playerDies();
game.playerDies();
game.playerDies();
console.log("lives = " + game.lives); // should be 0
game.newGame();
console.log("lives = " + game.lives); // should be 3
console.log("coins = " + game.coins); // should be 0
You can put if statement in your playerDies method
playerDies: function() {
if (this.lives > 0) {
return this.lives -= 1
}
return 0
}