如何在用户运行脚本时用Python写入文本文件?

时间:2017-06-19 09:35:25

标签: python python-2.7

我创建了一个基本游戏作为学习练习的一部分,我想在我学习更多Python时扩展它。游戏是一个非常基本的,基于文本的冒险游戏,一些房间让用户拿起物品。

我想在用户播放时将这些项目写入文本文件,然后让用户选择在游戏过程中检查他/她的“库存”。我无法获得正确的语法,使脚本能够执行以下操作:

  • 用户启动游戏时创建新文本文件;
  • 当用户到达游戏的该部分时,将定义的项目写入文本文件;
  • 创建一个选项以查看库存(我知道如何执行此操作)。

以下是我尝试使用此注释的代码的脚本部分示例:

def room1_creep():
print "You slowly enter the room, and look around. In the opposite corner of the room, you see a ferocious looking bear. It doesn't seem to have seen you yet."
print "You make your way to the chest at the end of the room, checking to see whether the bear has seen you yet. So far, so good."
print "Just as you reach the treasure chest, you hear a roar from the bear that seems to have seen you. What do you do? Rush 'back' to the door or go for the 'treasure'?"

creep_choice = raw_input("You have two choices: 'back' or 'treasure'. > ")

if creep_choice == "back":
    print "You make a run for it. You feel the bear's hot breath on the back of your neck but you reach the door before it catches you."
    print "You slam the door closed behind you and you find yourself back in the passage."
    return entrance()
elif creep_choice == "treasure":
    print "You manage to grab a few handfuls of gold coins before the bear stabs its claws into you and sprint for the exit."
    # inv = open("ex36_game_txt.txt", 'w')
    # line3 = raw_input("10 gold coins")
    # inv.write(line3)
    # inv.write("\n")
    # inv.close()
    # I also want to add "gold coins" to a text file inventory that the script will add to.
    print "You manage to slam the door closed just as the bear reaches it. It howls in frustration and hunger."
    return middle()
else:
    room1_indecision()

My script is on GitHub如果完整脚本有用。我在这里进行了几次搜索,最接近我认为我需要的问题是this one。我无法弄清楚如何有效地实施这个

我面临的主要挑战之一是如何让脚本动态创建新的文本文件,然后使用清单中的项目填充该文本文件。

2 个答案:

答案 0 :(得分:1)

如果你需要在python中使用with open(...)写入文件:

...

elif creep_choice == "treasure":
    print "You manage to grab a few handfuls of gold coins before the bear stabs its claws into you and sprint for the exit."
    with open("ex36_game_txt.txt", 'w') as inv:
        line3 = "10 gold coins"
        inv.write(line3)

    # I also want to add "gold coins" to a text file inventory that the script will add to.
    print "You manage to slam the door closed just as the bear reaches it. It howls in frustration and hunger."
    return middle()

...

with open将在您完成写入后自动处理异常并关闭文件。

如果您需要一个已定义项目的列表,您可以初始化一个字典并将其保存在内存中,如下所示:

list_of_items = {item0: "...", item1: "...", ...}

在单独的模块中定义它并在需要时导入它。然后,您可以通过键访问其值,并在游戏过程中将它们写入清单。

我不确定通过创建查看和库存选项的具体含义。为什么不像您现在一样使用raw_input()并检查单词inventory

options = ('1. Inventory.\n'
           '2. Save.\n'
           '3. Exit.\n')

option = raw_input("Choose an option: {}".format(options))

if option == "Inventory":

    with open("ex36_game_txt.txt", "r") as inv:
        for item in inv:
            print(inv)

它会打印出您的库存文件的内容。

另请注意,如果您计划在python3中运行游戏,请不要使用raw_input()并使用input()代替。

答案 1 :(得分:1)

如果使用singleton design pattern.,则无需写入文本文件。它保证类始终返回其自身的唯一实例。因此,您可以创建一个名为“PlayerInventory”的类,一旦它至少实例化一次,无论何时何地在您的代码中尝试实例化您的库存类,它将始终返回相同的实例。

如果您希望让您的广告资源保持不变,以便玩家可以在关闭程序后保存游戏并恢复其库存,请使用名为“pickle”的模块在退出时直接序列化您的广告资源对象。

示例:

class PlayerInventory(object):

    _instance = None

    def __new__(class_, *args, **kwargs):
        if not isinstance(class_._instance, class_):
             class_._instance = object.__new__(class_, *args, **kwargs)
             # you need to initialize your attributes here otherwise they will be erased everytime you get your singleton
             class_._instance.gold_coins = 0
             class_._instance.magic_items = []
             # etc... whatever stuff you need to store !
        return class_._instance

您可以在单独的文件中编写此类,并在需要访问库存时导入该类。示例用例(假设您在名为“inventory.py”的文件中编写了此类,该文件包含在名为“mygame”的主程序包中):

from mygame.inventory import PlayerInventory

# Adding coins to inventory
if has_won_some_gold:
    PlayerInventory().gold_coins += 10

您的代码中的其他地方,您可能想要检查玩家是否有足够的黄金来执行某项操作:

from mygame.inventory import PlayerInventory

if PlayerInventory().gold_coins < 50:

    print "Unfortunately, you do not possess enough wealth for this action..."

else:
    # Whatever you wish ...

将某些内容添加到项目列表中:

from mygame.inventory import PlayerInventory

if player_picked_up_sword:
    print "Got: 1 bastard sword"
    PlayerInventory().magic_items.append("bastard sword")

请注意,如果您将文件放在非常小的位置,则每个文件只需要一次导入行!