Vehicular simulation game example
Here is an example of how you might use the concept of passing functions in the context of a vehicular simulation game
In this example, we have a Vehicle
object with two methods: accelerate
and decelerate
. The accelerate
method increases the speed
of the Vehicle
object by a given amount, while the decelerate
method decreases the speed
of the Vehicle
object by a given amount. Both methods also ensure that the speed
of the Vehicle
object stays within the range 0 to maxSpeed
.
We then create two objects based on the Vehicle
object: Car
and Bike
. The Car
object has a name
of "Car" and a maxSpeed
of 120, while the Bike
object has a name
of "Bike" and a maxSpeed
of 60.
We can then use the accelerate
and decelerate
methods on the Car
and Bike
objects to change their speeds. As the example code shows, the Car
object's speed is increased to 30 when we call Car.accelerate(30)
, and then increased to 100 when we call Car.accelerate(80)
. The Bike
object's speed is increased to 30 when we call Bike.accelerate(30)
, and then decreased to 10 when we call Bike.decelerate(20)
Last updated