PYTHON如何在函数执行后删除它?

2024-05-17 11:14:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python编程有点陌生,我正在尝试创建一个文本冒险游戏。我想我用的是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)

Tags: thetoinyoua2inputrawif
1条回答
网友
1楼 · 发布于 2024-05-17 11:14:46

下面是一些代码来让你的游戏开始,其中包括一个很好的基于类的解决方案,你的问题,并清理你的代码,这样你就不会有一堆随机逻辑无处不在,你将难以辨认下周。我相信这里会有无数你不懂的东西。用Google搜索它们,然后修改任意代码行并运行它来查看发生了什么。好好享受!你知道吗

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

相关问题 更多 >