Skip to content
Permalink
Browse files
Fix Bug #3: Power battles
This is another subtle bug that crops up frequently in many
different forms. The problem is that this line:

```
player_stats['power'] = player_stats['power'] - enemy_stats['power']
```

PERMANENTLY modifies the value of `player_stats['power']`.
It even modifies the variable *outside* of the function it is
inside. This is why it appears as though our player's power
is slowly draining away.

The fix is to change our code so that it doesn't modify
`player_stats`:

```
power_diff = player_stats['power'] - enemy_stats['power']
```

For much more detail on when and why functions can modify data
outside of themselves, see:

https://robertheaton.com/2014/02/09/pythons-pass-by-object-reference-as-explained-by-philip-k-dick/
  • Loading branch information
robert committed Dec 29, 2019
1 parent 0c2a122 commit a3311e0dec50ccdebc36b3cb047c2f2fa80da4d1
Showing 1 changed file with 2 additions and 2 deletions.
@@ -4,9 +4,9 @@ def player_has_enough_power_to_defeat_enemy(player_stats, enemy_stats):
# Subtract the enemy power from the
# player power and make sure that
# the difference is more than 5.
player_stats['power'] = player_stats['power'] - enemy_stats['power']
power_diff = player_stats['power'] - enemy_stats['power']

if player_stats['power'] > EXTRA_POWER_NEEDED_TO_DEFEAT_ENEMY:
if power_diff > EXTRA_POWER_NEEDED_TO_DEFEAT_ENEMY:
return True
else:
return False

0 comments on commit a3311e0

Please sign in to comment.