简体   繁体   English

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

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

I'm a bit new to Python programming and I'm trying to create a text-adventure game. 我对Python编程有点陌生,我正在尝试创建一个文字冒险游戏。 I assume I'm using ver 2.7.3? 我假设我使用的是2.7.3版?

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

I want to make an inventory system that has a max size. 我想制作一个具有最大尺寸的库存系统。 I'm currently using a list for my inventory. 我目前正在使用清单作为清单。

I also want to make some functions a one-time thing; 我还想使某些功能成为一回事。 where you can only select one item without choosing another. 您只能选择一项而不选择另一项。

Or maybe remove a function after it's been executed? 或者在执行完某个功能后将其删除?

I assume these have to do with classes, but I'm not really advanced on that whole thing. 我认为这些与类有关,但是我在整个事情上都不是很先进。 Here is a sample of my code/game. 这是我的代码/游戏的示例。 I would like the player to only select one weaponKind. 我希望玩家只选择一种武器种类。

Since I have a lot of while True loops, it's safe to say that the player can go back and choose another weaponKind . 由于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)

Here's some code to get your game started, that includes a nice class-based solution to your problem, and cleans up your code so that you don't have a bunch of random logic everywhere that will be illegible to you next week. 这是一些可以使您的游戏开始的代码,其中包括一个基于类的解决问题的好的解决方案,并清理您的代码,以使您到处都不会有一堆乱码,下周您将难以理解。 I'm sure there will be a gazillion things in here that you don't understand. 我敢肯定,这里会有大量您不了解的事物。 Google them all, and change arbitrary lines of code and run it to see what happens. 将它们全部搜索出来,然后更改任意代码行并运行它以查看会发生什么。 Enjoy! 请享用!

# 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.

相关问题 在Python unittest中,执行完TestCase中的所有测试后如何调用函数? - In Python unittest, how can I call a function after all tests in a TestCase have been executed? python中remove() function是怎么执行的? - How remove() function was executed in python? 如何在执行函数后获取函数的局部值? - How can I get the values of the locals of a function after it has been executed? 我怎么知道在Python中执行函数的地方? - How do I know where is a function was executed in Python? 如何判断是否已在Python中调用过函数? - How do I tell whether a function has been called in Python? 如果python“一行一行”运行文件,它如何在定义之前使用函数? - If python run the file "line after line" how can it use a function before it's been defined? 初学者 python 文字游戏,如何从已使用的列表中删除位置 - beginner python text game, how do I remove a location from a list that has already been used 在Python中,当执行`if`语句时,如何从函数返回值? - In Python, how do I return a value from a function when an `if` statement is executed? 如何在文件循环后删除文件-Python - How to remove a file after it has been loop through-Python python .get 函数添加了一个换行符,我该如何删除它? - python .get function adds a newline, how do i remove it?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM