Я делаю текстовое приключение на питоне. Нужна помощь в проведении "инвентаризации"

Я делаю текстовое приключение на питоне. Он основан на ex41 в книге Learn Python the Hard Way, поэтому он чем-то похож. Мой вопрос, однако, не имеет ничего общего с этим упражнением. Я пытаюсь провести инвентаризацию, чтобы предмет можно было подобрать и использовать (например, ключ или лихорадку).

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

Теперь я пробую список, и когда предмет «подбирается», он добавляется в список инвентаря.

Как я могу сделать инвентарь или, по крайней мере, «поднять» предмет, а затем «использовать» его?

Строки кода, которые я считаю важными, это 18-20 (под def __init__(self, start)), 77 (под def cell(self)), 161-162 (под def janitor(self)).

from sys import exit
from random import randint
import time

prompt = '> '


class Game(object):

    def __init__(self, start):
        self.quips = [
            "Way to go, you died."   
            "Now you're dead.  Sweet.",
            "Well isn't this just peachy?  You're dead.  (It's not peachy.)"
                     ]
        self.start = start
        #self.smell = 0
        #self.Febreeze = False
        #self.key = False
        self.inventory = []

        #if self.smell >=2:
         #   return 'death'

    def play(self):
        next = self.start

        while True:
            print "\n-------"
            room = getattr(self, next)
            next = room()

    def death(self):
        print self.quips[randint(0, len(self.quips)-1)]
        exit(1)

    def intro(self):
        print "You wake up."
        print "You're in a dark cell."
        print "You have no idea who you are or where you are."
        print "The door is slightly open."
        print "You stagger through the door.  The light is blinding."
        print "You have just escaped imprisonment and you're on the run."
        return 'central_corridor'

    def central_corridor(self):
        print "In front of you is a long corridor with no doors on the side, but you think you can make out a door at the very end."
        print "Behind you is the cell that you have just escaped."

        next = raw_input(prompt)

        if "cell" in next:
            print "You decide to go back into your cell."
            return 'cell'
        elif "forward" in next:
            print "You travel down the corridor towards the door."
            return 'front_corridor'
        else:
            print "That command doesn't exist."
            return 'central_corridor'

    def cell(self):
        print "You're standing in the middle of a musty cell."
        print "There is a bed in the corner with a rotting mattress."
        print "Under the bed the bricks are loose."
        print "In the opposite corner there is a dirty toilet that implies that prison food is even worse than Taco Bell."
        print "There are some scratches on the wall next to the toilet."
        print "Behind you is an exit into the corridor."


        next = raw_input(prompt)

        if "toilet" in next:
            print "It'd probably be best if this toilet wasn't described."
            #self.smell = self.smell + 1
            return 'cell'
        elif "febreeze" in next and "Febreeze" in self.inventory #and self.Febreeze = True:
            print "You use the Febreeze on the toilet to get rid of the odor."
            print "Now you can go behind the toilet to read the rest of the scratches."
        elif "scratches" in next:
            print "The scratches on the wall seem to be tally marks.  It goes up to 123.  I wonder what it means."
            print "You see more scratches behind the toilet, but the stench is too much for you to handle."
            print "If only you could get rid of the smell..."
            #self.smell = self.smell + 1
            return 'cell'
        elif "bed" in next:
            print "There are various stains on the mattress.  Some of the springs are poking up into the mattress. Ouch."
            print "Buried between the wall and the mattress is a stuffed animal."
            return 'cell'
        elif "bricks" in next:
            print "You pull the bricks out of the floor and find a few pieces of toilet paper."
            print "There is a note written on them in what you hope is dried blood."
            print "The note reads:\n -------------------------\nthe closet!! the closet in the walls i'm not \nsure\twhich one it is but its defin-\nly in the hall. i hear it in the bricks!\n---------------------------"
            print "Hmm, maybe it's a hint or something."
        elif "corridor" in next:
            return 'central_corridor'
        else:
            print "I do not understand how to %s" % next
            return 'cell'

    def front_corridor(self):
        print "You are standing in front of a door."
        print "On the side of the door is a keypad."

        next = raw_input(prompt)

        if "keypad" in next:
            return 'keypad'
        elif "wall" in next:
            return 'wall'
        elif "back" in next:
            return 'central_corridor'
        else:
            print "I don't understand %s" % next
            return 'front_corridor'

    def wall(self):
        print "Which wall do you want to check?"

        next = raw_input(prompt)

        if "left" in next:
            return 'left'
        elif "right" in next:
            return 'right'
        elif "back" in next:
            return 'front_corridor'

    def right(self):
        print "You examine the wall carefully, running your fingers across each of the bricks."
        print "Unfortunately it doesn't look like anything of value is in this wall."
        print "Well, you just wasted some time."
        return 'wall'

    def left(self):
        print "You examine the wall carefully, running your fingers across each of the bricks."
        print "One of the bricks seems to be protruding from the wall."
        print "Do you push it?"

        next = raw_input(prompt)

        if next[0] == "y":
            print "A few of the bricks shift, revealing a secret door way."
            return 'janitor'
        elif next[0] == "n":
            print "You decide not to push the brick. Good thinking, it may have been a booby trap."
            return 'front_corridor'
        else:
            print "That doesn't exactly make sense..."
            return 'wall'

    def janitor(self):
        print "You are in a room filled with janitorial tools."
        print "On your left you see a few cans of Febreeze, a plunger and a Playboy magazine."

        next = raw_input(prompt)

        if "febreeze" in next:
            print "You pick up some Febreeze and put it in your back pocket."
            print "Maybe this will be useful somewhere down the line."
            self.inventory.append("Febreeze")
            #self.Febreeze = True
            return 'janitor'
        elif "plunger" in next:
            print "You try to pick up the plunger but it appears to be stuck in the ground."
            print "After tugging for a few minutes the handle comes out, leaving the rubber suction cup plastered to the floor."
            print "Who knows what's keeping it there."
            print "You decide not to touch it."
            return 'janitor'
        elif "playboy" in next:
            print "Well isn't that nice."
            print "These janitors certainly have good taste."
            return 'janitor'
        elif "back" in next:
            return 'front_corridor'
        else:
            print "Do WHAT with WHAT?"
            return 'janitor'

    def keypad(self):
        print "Above the keypad there is a sign that reads:\n-----------\nInput a 3 digit code.\nWarning: If code is incorrect 3 times, keypad will self-destruct.\n-----------"
        code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))
        guess = raw_input("Password: ")
        guesses = 0

        while guess != code and guesses < 2:
            print "BZZZZZEDD!"
            guesses += 1
            guess = raw_input("Password: ")

        if guess == code:
            print "The keypad beeps in acceptance.  Wow, that was a good guess"
            print "The door swings open."
            print "Behind the door is a long bridge suspended over a lake of lava."
            return 'bridge'
        elif "key" in guess and key == True:
            print "You flash your card key across the keypad."
            print "There is a beep as the door swings open."
            print "Behind the door is a long bridge suspended over a lake of lava."
            return 'bridge'
        else:
            print "The keypad buzzes one last time and then you hear a sickening melting"
            print "sound as the lock mechanism fuses together."
            print "There is a small clicking while the keypad countsdown."
            print "3"
            time.sleep(1)
            print "2"
            time.sleep(1)
            print "1"
            time.sleep(1)
            print "There is a large explosion and you are caught right in the middle of it."
            print "The fiery blast tears your skin from your body as you scream in agony."
            return 'death'

    def bridge(self):
        print "You carefully walk onto the bridge."
        print "One false move and you could be dead."
        print "Across the bridge is a door leading to the outside world."

        next = raw_input(prompt)

        if "jump" in next:
            print "You jump to your death."
            print "Probably not the best idea."
        elif "run" in next:
            print "You run"

a_game = Game("intro")
a_game.play()

person Ivan Kelber    schedule 25.11.2011    source источник
comment
Для текстовой приключенческой игры должна работать куча логических значений. Вы пытались выяснить, почему их значения сбрасываются обратно на false?   -  person millimoose    schedule 25.11.2011
comment
Как это оказывается не работает? Пробовали ли вы вставлять операторы печати, чтобы увидеть, какие значения будут после того, как вы возьмете предмет, а затем после того, как вы покинете комнату?   -  person Dan Breslau    schedule 26.11.2011
comment
в конечном итоге было бы более идиоматично использовать набор для реализации инвентаризации (вместо list). Вы можете использовать add и remove для добавления и удаления элементов. Оператор in работает и для list, как я понимаю...   -  person moooeeeep    schedule 26.11.2011


Ответы (3)


Кажется, ваш подход работает нормально, но у вас есть пара ошибок. В cell() вам нужен : после оператора elif "febreeze"... (до начала комментария). Кроме того, в конце этого блока elif вам нужно return 'cell'. С этими изменениями я могу взять Febreeze и использовать его.

person David    schedule 25.11.2011

Если вы определяете инвентарь как список (это то, что я сделал), вы можете сделать:

    class Attributes:
        def __init__(self, inventory):
            self.inventory = inventory

    Player = Attributes([])
    Player.inventory.append("Febreeze")

Квадратные скобки составляют инвентарь, а «добавить» добавляет к нему Febreeze.

person user2426782    schedule 28.05.2013

если вы попытались определить его как список, например (предполагая, что это на python)

def inventory[]
    inventory.append
add item (inventory)

не могу вспомнить как добавить в инвентарь но есть основы

person theflashplayer9    schedule 14.05.2013