Fix the Game State Bug
Advanced · Fix the bug · from Python Copy vs Deepcopy: Why Your "Copy" Isn't Really a Copy
From the lesson: Python Copy vs Deepcopy: Why Your "Copy" Isn't Really a Copy
Imagine you have a folder full of photos. You make a copy of the folder and give it to a friend. But here's the catch - only the folder is new. The photos inside are the same physical photos, shared by both folders. If your friend draws a mustache on one, your photo has the mustache too.
Read the lessonThis game saves a checkpoint of the player's state, then the player picks up an item. But when we load the checkpoint, the item is already there! Fix the code so the checkpoint is a truly independent snapshot.
Expected output:
Checkpoint inventory: ['sword', 'shield']
Current inventory: ['sword', 'shield', 'potion']player = {
'name': 'Hero',
'hp': 100,
'inventory': ['sword', 'shield'],
}
# Save checkpoint
checkpoint = player.copy()
# Player picks up a potion
player['inventory'].append('potion')
print(f"Checkpoint inventory: {checkpoint['inventory']}")
print(f"Current inventory: {player['inventory']}")
More Copy and Deepcopy exercises
- Predict the Output: Assignment AliasingBeginner
- Make an Independent CopyBeginner
- Predict the Output: Shallow Copy TrapIntermediate
- Safe Copy of Nested DataIntermediate
All Python exercises · 50 practice problems · Data Structures quiz