Search code examples
pythontext-based

How to code item interaction in text adventure


I am building a text adventure in python and I would like to have my items affect things in the game, for example, a passageway is too dark to walk down, unless the player holds a lamp in their inventory.

What would be the best way to code this based off my code already?

---This is my rooms and directions to connecting rooms---

rooms = ["hallEnt", "hallMid", "snowRoom", "giantNature", "strangeWall", "riverBank"]
roomDirections = {
    "hallEnt":{"e":"hallMid"},
    "hallMid":{"s":"snowRoom", "e":"giantNature", "w":"hallEnt"},
    "snowRoom":{"n":"hallMid"},
    "giantNature":{"s":"strangeWall", "e":"riverBank", "w":"hallMid"},
    "strangeWall":{"s":"hallOuter", "e":"riverBank", "n":"giantNature"},
    "riverBank":{"e":"lilyOne", "w":"giantNature"},
    "lilyOne":{"e":"lilyTwo", "w":"riverBank", "n":"riverBank", "s":"riverBank"},
    "lilyTwo":{"e":"riverBank", "w":"lilyThree", "n":"riverBank", "s":"riverBank"},
    "lilyThree":{"e":"riverBank", "w":"lilyFour", "n":"riverBank", "s":"riverBank"},
    "lilyFour":{"e":"riverBank", "w":"treasureRoom", "n":"riverBank", "s":"riverBank"},
    "treasureRoom":{"w":"hallEnt"},

---and here are my items and their room locations.---

roomItems = {
    "hallEnt":["snowboots"],
    "snowRoom":["lamp"],
    "treasureRoom":["treasure"],
    }

Another example of my query, I dont want the player to be able to get from "hallMid" to "giantNature" by going (e)ast, unless they hold the "lamp" in their invItems.


Solution

  • You might want to look into using nested if statements that run each time you enter a room, especially if the effects are passive. Assuming you are storing the value of items with a 1 or 0, you could do this:

    lamp = 0
    rooms = ["hallEnt", "hallMid", "snowRoom", "giantNature", "strangeWall", "riverBank"]
    room = rooms[0]
    
    if lamp == 1:
            connected_room = ["hallMid", "snowRoom"]
            print "You are currently inside the " + room + "."
            print "You can see " + connected_room[0] + " and " + connected_room[1] + " in the distance."
    else:
            connected_room = ["snowRoom"]
            print "You are currently inside the " + room + "."
            print "You can see the " + connected_room[0] +  " in the distance."