簡體   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