Game Development Reference
In-Depth Information
lines long. If this happens, it's a good idea to break out some of that code into
separate functions. Let's consider the game world's update loop.
class World
{
bool _playerHasWonGame ¼ false;
public void Update()
{
Entity player ¼ FindEntity("Player");
UpdateGameCreatures();
UpdatePlayer(player);
UpdateEnvironment();
UpdateEffects();
Entity goldenEagle ¼ FindEntity("GoldenEagle");
if (player.Inventory.Contains(goldenEagle))
{
_playerHasWonGame ¼ true;
ChangeGameState("PlayerWinState");
}
}
// additional code
}
This loop isn't that bad, but the last piece of code looks a little untidy; it could be
moved into a separate function. To do this automatically, select the code as if
about to copy and paste it. Start the selection from the line Entity gold-
enEagle... to the closing brace of the if-statement. Now right-click.
The context menu will come up as in Figure 4.8; select Refactor, and then choose
Extract Method. You will be prompted to name the method. I chose Check-
ForGameOver . The selected code will then be removed and placed in a new
function; any variables that it uses will be passed in as arguments to the newly
created function. After the refactor, the code will look like the following:
bool _playerHasWonGame ¼ false;
public void Update()
{
Entity player ¼ FindEntity("Player");
 
Search WWH ::




Custom Search