PYTHON - 如何在执行功能后删除它?

时间:2016-10-09 19:27:02

标签: python python-2.7 adventure

我对Python编程有点新意,我试图创建一个文本冒险游戏。我假设我使用的是ver 2.7.3?

2.7.3(默认,2015年6月22日,19:33:41) [GCC 4.6.3]

我想制作一个具有最大尺寸的库存系统。我目前正在使用清单列表。

我也想让一些功能成为一次性的东西;您只能选择一个项目而不选择其他项目。

或者在执行之后删除功能?

我认为这些与课程有关,但我并没有在整个课程上取得进步。这是我的代码/游戏的示例。我希望玩家只选择一个武器。

由于我有很多while True个循环,因此可以放心地说玩家可以返回并选择另一个weaponKind

inventory = ['pen','apple']

import time

while True:

    a2 = raw_input("You begin to download it. The progress bar seems very small, so you decide you'd better do something as time passes. What will you do?" + '\n' + "==> Decide strife specibus" + '\n' + "==> Examine items in (on?) shelf." + '\n' + "==> Doodle on arm" + '\n' + "==> Check inventory" + '\n'+ "==> End game.").upper()
    if a2 == 'DOODLE ON ARM':
        print("You're a natural tattoo artist. Those stick figured dinosaurs rock.")
    if a2 == 'END':
        quit()
    if a2 == 'CHECK INVENTORY':
        print(inventory)
        continue
    if a2 == 'STRFE':
        strife = raw_input("You assume you have to fight monsters in this game. You've heard this is a real-life thing, no VR junk and whatnot. Where will you scour for a weapon? " + '\n' + "==> Scour in the kitchen." + '\n' + "==> Scour in your room. " + '\n' + "==> Scour in the yard.").upper()
        if strife == 'KITCHEN':
            while True:

                a2 = raw_input("You begin to download it. The progress bar seems very small, so you decide you'd better do something as time passes. What will you do?" + '\n' + "==> Decide strife specibus" + '\n' + "==> Examine items in (on?) shelf." + '\n' + "==> Doodle on arm" + '\n' + "==> Check inventory" + '\n'+ "==> End game.").upper()
                if a2 == 'DOODLE ON ARM':
                    print("You're a natural tattoo artist. Those stick figured dinosaurs rock.")
                if a2 == 'END':
                    quit()
                if a2 == 'CHECK INVENTORY':
                    print(inventory)
                    continue
                if a2 == 'STRFE':
                    strife = raw_input("You assume you have to fight monsters in this game. You've heard this is a real-life thing, no VR junk and whatnot. Where will you scour for a weapon? " + '\n' + "==> Scour in the kitchen." + '\n' + "==> Scour in your room. " + '\n' + "==> Scour in the yard." + '\n').upper()
                    if strife == 'KITCHEN':
                        while True:
                            kitchen = raw_input("You lazily go downstairs to the kitchen. There's a plate of *shudder* Betty Crocker cookies on the island. There's the cupboard full of kitchen supplies where your weapon will be. There's also the fridge. The window suggests it's a bit before noon. What will you do?" + '\n' + "==> Eat cookies" + '\n' + "==> Examine cupboard" + '\n' + "==> Open fridge." + '\n' + "==> Exit Kitchen" + '\n').upper()
                            if kitchen == 'EAT COOKIES':
                                print("You hesitate for a moment before grabbing a cookie. Curse that Crocker Corp and its manipulating ways!")
                                def cookie(food):
                                    cookie = food(name = 'BC cookie')
                                inventory.append('BC cookie')
                                print(inventory)
                                time.sleep(3)
                            if kitchen == 'EXAMINE CUPBOARD':
                                while True:
                                specibi = raw_input("There's a mixer, cheese grater, and knife." + '\n' + "> Choose mixer." '\n' + "> Choose knife." + '\n' + "> Choose grater." + '\n').upper()
                                if specibi == 'MIXER':
                                    def mixerKind(strife):
                                        mixerkind = strife(name = "BETTY CRACKER")
                                    inventory.append("BETTY CRACKER")
                                    print(inventory)
                                    time.sleep(3)
                                if specibi == 'KNIFE':
                                    def knifeKind(strife):
                                        knifeKind = strife(name = "BETTY CRACKER")
                                    inventory.append("Kitchen Knife")
                                    print(inventory)
                                    time.sleep(3)
                                    break
                            if kitchen == 'EXIT':
                                break
                    if strife == 'ROOM':
                        pers = raw_input("You find an item related to your interest in archery which is a ")
                        if pers == pers:
                            def originalKind(strife):
                                ogkind = strife(name = pers)
                            inventory.append(str(pers))
                            print(inventory)

1 个答案:

答案 0 :(得分:4)

这里有一些代码可以让你的游戏开始,包括一个很好的基于类的解决方案来解决你的问题,并清理你的代码,这样你就没有一堆随机逻辑,这些逻辑在下周对你来说难以理解。我相信你在这里会有很多不明白的东西。谷歌他们所有,并改变任意代码行并运行它以查看会发生什么。享受!

# This is how I would solve your problem.  
# A room may have various activities that can be performed.... 
# the different types of activity will have different classes
# an activity will include any logic involved in performing the activity
# e.g. an "ItemChoiceActivity" will have a list of possible items,
# the logic of "only one can be chosen" is inherent to the class

class Activity(object):
    pass

class ItemChoiceActivity(Activity):
    '''Implements an activity in which the hero chooses one item from a list'''
    def __init__(self, description, items):
        # pass in a list of Item objects
        self.items = ChoiceList(items)
        self.description = description

    def run(self, hero):
        '''Running an activity gives the hero something to do, 
           then does something to that hero'''
        print self.items
        i = int(raw_input("Choose an item:"))
        hero.pickup_item(self.items[i])
        print hero, " has gained a ", self.items[i]

    def __str__(self):
        return self.description
    __repr__=__str__

# Rooms are a linked grid, sort of like a linked list
class Room(object):
    '''Implements a Room.  A Room has a textual description, and links to other rooms in the dungeon
    '''
    def __init__(self, description):
        self.description = description #e.g "You enter an empty room... There is a skeleton on the floor.... It stinks in here"
        self.other_room_descriptions = ChoiceList([])
        self.other_rooms = []
        self.activities = ChoiceList([])

    def add_link(self, other_room, link_description):
        ''' Add a link to another room in the dungeon.
            other_room := the other room to link to
            link_description := "north", "south", "secret passage behind the dumpster", etc.
        '''
        # you can iterate through these to describe the directions the hero can go
        self.other_rooms.append(other_room)
        self.other_room_descriptions.append(link_description)

    def add_activity(self, activity):
        self.activities.append(activity)

    def perform_activity(self, i, hero):
        self.activities[i].run(hero)
        self.activities.pop(i)

    def __str__(self):
        return self.description
    __repr__=__str__

class Item(object):
    def __init__(self, description):
        self.description = description #e.g "staff of healing +2"
    def __str__(self):
        return self.description
    __repr__ = __str__


class ChoiceList(list):
    '''Just a list of Items, or whatever, but has a nice string repr to display to user'''
    def __str__(self):
        this = ""
        for i in range(len(self)):
            this += str(i) + ": " + str(self[i]) + "\n"
        return this
    __repr__ = __str__


class Hero(object):
    def __init__(self, description):
        MAX_INVENTORY_SIZE = 10
        self.description = description
        self.inventory = ChoiceList([None]*MAX_INVENTORY_SIZE) #Have a static size list to do the standard 'inventory slots' type thing

    def pickup_item(self, item):
        '''Return true if pickup successful, false if no slots available
           this allows the game to handle the situation that the hero
           cannot hold the item... should be handled in the activity'''
        for i in range(len(self.inventory)):
            if self.inventory[i] is None:
                self.inventory[i] = item
                return True
        return False

    def drop_item(self, i):
        '''Drop item at index i... using indices, because that's probably how they will be represented to the user... e.g. user calls "list items" and they get a list 1:staff, 2:wand, etc., then they pick an item by it's index.
        Returns the item dropped'''
        item = self.inventory[i]
        self.inventory[i] = None
        return item

    def __str__(self):
        return self.description
    __repr__=__str__


class Game(object):
    def __init__(self, current_room, hero):
        self.current_room = current_room
        self.hero = hero
        self.options = ChoiceList(["Activity", "Move"])

    def main_loop(self):
        print self.current_room.description
        print self.options
        what_to_do = int(raw_input("What to do?"))
        if what_to_do == self.options.index("Activity"):
            print self.current_room.activities
            activity = int(raw_input("Choose an activity:"))
            self.current_room.perform_activity(activity, hero)
        elif what_to_do == self.options.index("Move"):
            print self.current_room.other_room_descriptions
            room = int(raw_input("Choose a room:"))
            self.current_room = self.current_room.other_rooms[room]


if __name__ == "__main__":
    room1 = Room("A really swell room.  Just great, really.")
    room1.add_activity(ItemChoiceActivity("Choose your first weapon", [Item('staff'), Item('pickle')]))
    room2 = Room("A dead end")
    room1.add_link(room2, "a door to the north")
    room2.add_link(room1, "a door to the south")
    hero = Hero("some redneck guy")

    game = Game(room1, hero)
    while True:
        game.main_loop()