Solution to 7ec8: Battling fighters
See code at solutions/code/tutorialquestions/question7ec8
There are many ways you could model this question. Take a look at my solution, check you understand it, and compare it with yours.
In my solution, I decided that dice rolling is the responsibility of the game engine,
not of a fighter, so I equipped GameEngine with a field generator of type Random,
used to generate random numbers. In addition, I made an instance method, rollDice(), which uses
generator to generate a random integer between 1 and 6.
By making generator private, I ensure that clients of GameEngine must
use the rollDice() method to simulate dice rolls: they cannot access the random number
generator directly. This means that I could use a different scheme for simulating dice rolling.
I could also easily modify GameEngine to log the number of times a dice has been rolled.
If generator was public, clients could bypass such a logging mechanism.
In the question, you were asked to reduce a fighter's stamina by 2 when a hit occurs. In my
solution I have documented this by defining a constant, DAMAGE_VALUE, inside
caclulateDamage. The constant is set to 2, and calculateDamage simply
returns DAMAGE_VALUE. This is slightly preferable to simply returning the magic
number 2, because the named constant adds additional documentation stating the purpose of this
value.
Because Fighter needs to roll dice (e.g. in calculateAttackScore),
in my solution every Fighter has a reference to a GameEngine object.
In my solution, Fighter objects use a log method of GameWorld
to log the progress of their battle. Currently, log is implemented by delegating
to System.out.println. To have the progress of a battle displayed in some other manner,
(e.g., on a web page) all I would need to do would be re-implement log in GameWorld.
While we will have multiple instances of Fighter, we might wish there to be a
single GameEngine object. This could be achieved using the singleton
pattern, as described in the lectures. Can you extend your or my solution to use the singleton
pattern, ensuring that it is not possible to create multiple game worlds?