Video casino game example
Here is an example of how closures can be used in the context of a video casino game:
function createSlotMachine() {
let credits = 0;
return {
insertCoin: function() {
credits++;
},
play: function() {
if (credits > 0) {
// generate random number and determine winnings
let winnings = Math.floor(Math.random() * 50);
credits += winnings;
console.log(`Congratulations, you won ${winnings} credits!`);
} else {
console.log('You must insert a coin before you can play.');
}
},
getCredits: function() {
return credits;
}
}
}
let slotMachine = createSlotMachine();
slotMachine.insertCoin();
slotMachine.play(); // may output "Congratulations, you won X credits!"
console.log(slotMachine.getCredits()); // displays the number of credits the player has
In this example, the createSlotMachine
function creates a new slot machine object with three methods: insertCoin
, play
, and getCredits
. The insertCoin
and play
methods are closures that maintain a reference to the credits
variable, which is defined in the outer function. This allows the insertCoin
and play
methods to access and modify the credits
variable even after the createSlotMachine
function has returned.
The getCredits
method returns the value of the credits
variable. This method is not a closure, since it does not reference any variables from the outer function.
When the slotMachine
object is created, the player can insert coins, play the slot machine, and check their credits using the insertCoin
, play
, and getCredits
methods. The credits
variable is private to the slot machine object and cannot be accessed or modified directly from outside the object. This use of a closure helps to encapsulate the state of the slot machine and protect it from tampering.
Last updated