0

I'm trying to read the story of an adventure game from a file into a dictionary, then have the player dictate the advances through the game with either "next" or "back". The first function work's fine. And printing "print(room_dict[0])" will call the first room description.

def room(room_dict):
    with open("worlds\\rooms.txt", "r") as room_file:
        for line in room_file:
            room_key = int(line.strip())
            room_description = next(room_file).strip()
            room_dict[room_key] = room_description
        return room_dict

room_dict = {}
room = room(room_dict)

def room_interaction():
    print(room_dict[0])
    VALID = ("next", "back", "search")
    current = (room_dict[0])

    room_choice = input("What do you want to do?: ").lower()
    while room_choice not in VALID:
        room_choice = input("What do you want to do?: ").lower()
    if room_choice == "next":
        print(room_dict[current + 1])
        current = (room_dict[current + 1])
    elif room_choice == "back":
        print(room_dict[current - 1])
        current = (room_dict[current - 1])

The problem arises when I try to either add one or subtract one, I get the traceback:

File "C:\room interaction test.py", line 23, in room_interaction
    print(room_dict[current + 1])
TypeError: Can't convert 'int' object to str implicitly

I know the +1/-1 method probably isn't the best, but it's the simplest I could come up with on short notice. Any other ideas on how to move throughout a dictionary in this manner?

Gustav Bertram
  • 14,591
  • 3
  • 40
  • 65
user3027864
  • 81
  • 1
  • 10
  • If you can't convert _implicitly_ you could always convert explicitly... `print(str(room_dict[current + 1]))` – Ben Nov 30 '13 at 21:52
  • So this question got closed before I could answer, but your mistake lies here: `current = (room_dict[0])`. That means current is a room description, *not a room key*. What you actually want to do is `current = 0`. – Gustav Bertram Dec 01 '13 at 15:49
  • I edited the duplicate link to point at the canonical, but this question should really just be deleted - it's not clear what the intended logic actually was, and there was no attempt to debug. track down or *understand* the problem. – Karl Knechtel Jul 27 '22 at 03:23

1 Answers1

1

current is a string, yes? Then that's why it's complaining. For example, what would you expect:

"123" + 1

to return? The string "1231"? The string "124"? The integer 124 or 1231? Something else? Python refuses to guess: you have to spell out what you want. What I guess you want is:

print(room_dict[int(current) + 1])

But I don't really know - I'm guessing that current is the string representation of an integer, but you haven't said what it is.

Another possibility is that your logic is just confused, and you really intended to have an integer variable keeping track of the current room id, but are confusing that with the current room description.

Tim Peters
  • 67,464
  • 13
  • 126
  • 132