In my Python escape game, I pick up a key in room 2, move to room 3, and drop it. The debug output still says the key is in room 2, and the room description doesn't show it on the floor. What kind of logic error should I look for?
Why does my key stay in room 2 after I pick it up and move?
Answers
Check the line key_location == player_position. That compares the two values and discards the result. It doesn't update anything.
Where you mean to move the key, use key_location = player_position instead. If that line is inside a function, make sure the updated value is returned to the caller or otherwise updates the state your game actually uses.
Reply to this answer
You can also simplify the state model. Treat key_location as the room where the key lies only when got_key is false. When the player drops it, set got_key to false and key_location to player_position. When describing a room, show the key only if it isn't being carried and its location matches the player's.
That way you don't need to update the key's room on every move while it's being carried. Just be consistent about what key_location means.
Reply to this answer
For tracking down bugs like this, step through pickup, movement and drop in a debugger. Watch player_position, got_key and key_location after each command. A small test for that exact sequence would also make it easier to catch a regression later.
An editor's warnings or a linter may flag a comparison used as a standalone statement, which is a useful clue when you meant to assign a value.
Reply to this answer
Add your answer
Answers are reviewed before publication.
8b~switchpouch_574:
That explains why the debug output never changed. I'll check where the updated value goes too.