2014-11-18 2 views
0

Я копирую код. Я написал в классе для текстового приключения, но он не действует так же, как код, который я написал в классе.Как удалить элементы из словаря

Проблема в том, что мои предметы не удаляются из моих «комнатных предметов», как они должны быть.

Я только начинающий так пожалуйста, попробуйте и держать его просто для меня :)

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"}, 
} 

roomDescriptions = { 
    "hallEnt":"The hallway continues east, the cave opening is to the north, there is an opening in the south wall, but its too high to reach, there are some snowboots on the ground.", 
    "hallMid":"To the east the hallway grows dark, there is a corridor to the south", 
    "snowRoom":"The room is a dead end except for a lit lamp on the ground", 
    "giantNature":"To the east you see a river, to the south is a wall with some strange lines on it", 
    "strangeWall":"It appears to be just a wall, there are some old lines on the wall but you can't make them out.", 
    "riverBank":"The river has giant lilypads floating on its surface, however there is only one safe path across them, jump on the wrong lilypad and you will go through it and be swept back to the riverbank.", 
    "lilyOne":"The lilypads all look the same, you can only guess which is the right direction", 
    "lilyTwo":"The lilypads all look the same, you can only guess which is the right direction", 
    "LilyThree":"The lilypads all look the same, you can only guess which is the right direction", 
    "LilyFour":"The lilypads all look the same, you can only guess which is the right direction", 
    "treasureRoom":"There is nothing in the room except for a pedistal with priceless treasures on top of it.", 
} 

roomEntrance = { 
    "hallEnt":"You are standing in the hallway entrance.", 
    "hallMid":"You walk to the middle of the hallway.", 
    "snowRoom":"You are standing in a room as white as can be, and it is snowing inside the room.", 
    "giantNature":"You walk into a gigantic forest with a river running through the middle", 
    "strangeWall":"You walk over to the strange wall.", 
    "riverBank":"You walk right up to the edge of the river.", 
    "lilyOne":"You jump onto the first lilypad.", 
    "lilyTwo":"You jump onto the second lilypad.", 
    "lilyThree":"You jump onto the third lilypad.", 
    "lilyFour":"You jump onto the fourth lilypad.", 
    "treasureRoom":"You land safely on the far bank of the river.", 
} 

dirs = ["north","south", "east", "west", "n", "s", "e", "w",] 

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

currentRoom = "hallEnt" 
invItems = [] 


print("You are standing in a dark cave entrance") 

while True: 
    playerInput = input("What do you want to do? ") 
    playerInput = playerInput.lower() 
    if playerInput == "quit": 
     break 

    elif playerInput == "look": 
     print(roomDescriptions[currentRoom]) 

    elif playerInput in dirs: 
     playerInput = playerInput[0] 
     if playerInput in roomDirections[currentRoom]: 
      currentRoom = roomDirections[currentRoom][playerInput] 
      print(roomEntrance [currentRoom]) 
     else: 
      print("You can't go that way") 


    elif playerInput == "lookdown": 
     print ("You see", roomItems[currentRoom]) 




    elif playerInput == "inventory" or playerInput == "inv": 
     print (invItems) 

    else: 
     if playerInput in roomItems[currentRoom]: 
      print("picked up", playerInput) 
      invItems.append(playerInput) 
      for i in range(0, len(roomItems[currentRoom]): 
       if playerInput == roomItems[currentRoom][i]: 
        del roomItems[currentRoom][i] 
        break 

     elif playerInput in invItems: 
      print("dropped", playerInput) 
      roomItems[currentRoom].append (playerInput) 
      for i in range (0, len(invItems)): 
       if playerInput == invItems[i]: 
        del invItems[i] 
        break 



     else: 
      print("I don't understand") 

ответ

1

Судя по тому, как он перебирает предметы комнаты, кажется, как он ожидает пункты номера, чтобы быть списком строк , Теперь они простые строки. Может быть, элементы должны выглядеть следующим образом:

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

Также стоит проверить метод списка remove, потому что она позволяет удалять вещи из списка без необходимости писать цикл вручную. Например:

invItems.remove(playerInput) 

Это, конечно, OK, чтобы написать, что цикл вручную один раз, чтобы понять, как это сделать, но после этого один раз, используя встроенные методы делает ваши большие программы легче читать.

Edit: Там также закрывающая скобка отсутствует в этой строке:

for i in range(0, len(roomItems[currentRoom]): 

Я нашел это, запустив сценарий. Ваша система не сообщает номер строки для ошибок?

+0

Первоначально у меня было это написано в соответствии с вашим первым предложением, это давало мне синтаксические ошибки во всем мире, и это добавит элементы в мои «invItems», просто не удалит их из «roomItems» – kebab

+0

@kebab: Тогда у вас не было это точно так же, как я предложил, потому что то, что я предложил, не имеет синтаксических ошибок. Возможно, вы забыли закрыть скобку, когда вы ее написали. –

+0

эта часть была на 100% правы, все скобки закрыты, поверьте, я уверен, что ошибки синтаксиса были вызваны чем-то еще дальше в коде, но я слишком новичок в кодировании. Я не могу сказать – kebab

Смежные вопросы