Why does my key stay in room 2 after I pick it up and move?

November 16, 2026 3 answers
Asked by 8b~switchpouch_574

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?

Answers

5f+brassruler_826

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.

8b~switchpouch_574:

That explains why the debug output never changed. I'll check where the updated value goes too.

Reply to this answer
_c38!socketbadge.7

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
v.47+brisktoggle

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.

Related Discussions