繁体   English   中英

PYTHON-函数执行后如何删除?

[英]PYTHON - How do I remove a function after it's been executed?

我对Python编程有点陌生,我正在尝试创建一个文字冒险游戏。 我假设我使用的是2.7.3版?

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

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

我还想使某些功能成为一回事。 您只能选择一项而不选择另一项。

或者在执行完某个功能后将其删除?

我认为这些与类有关,但是我在整个事情上都不是很先进。 这是我的代码/游戏的示例。 我希望玩家只选择一种武器种类。

由于while True循环的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)

这是一些可以使您的游戏开始的代码,其中包括一个基于类的解决问题的好的解决方案,并清理您的代码,以使您到处都不会有一堆乱码,下周您将难以理解。 我敢肯定,这里会有大量您不了解的事物。 将它们全部搜索出来,然后更改任意代码行并运行它以查看会发生什么。 请享用!

# 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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM