Life Simulation Game example
Here is an example of callback functions in the context of a life simulation game
class LifeSimulation {
// Public field
events = [];
// Public method
addEvent(event, callback) {
// Add the event and callback to the list of events
this.events.push({ event, callback });
}
runSimulation() {
console.log('Running simulation...');
for (const { event, callback } of this.events) {
// Check if the event has occurred
if (event()) {
// If the event has occurred, call the callback function
callback();
}
}
}
}
const sim = new LifeSimulation();
// This function will be called when the event occurs
function haveBaby() {
console.log('Congratulations, you had a baby!');
}
// Add the event and callback to the simulation
sim.addEvent(() => Math.random() < 0.1, haveBaby);
// Run the simulation
sim.runSimulation();
In this example, the LifeSimulation
class has a public method called addEvent
that adds an event and a callback function to a list of events. The runSimulation
method runs through the list of events, and calls the callback function for any event that has occurred.
The event in this example is a random event that occurs with a probability of 10%. The callback function is a function called haveBaby
that logs a message to the console.
The addEvent
method allows you to add any number of events and callbacks to the simulation, and the runSimulation
method will call the appropriate callback function for any event that has occurred.
Using callback functions in this way allows you to create a flexible and customizable life simulation game. You can add any number of events and callbacks to the simulation, and the callback functions can perform any action that you want to happen when the event occurs.
Last updated