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

2024-06-08 05:42:23 发布

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

作为学习练习的一部分,我创建了一个基本的游戏,我想随着我对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。我不知道如何有效地实施这一点

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


Tags: andoftheto用户脚本you游戏
2条回答

如果您需要在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()

如果使用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")

请注意,如果您将导入行放在最下面的位置,则每个文件只需要导入行一次

相关问题 更多 >

    热门问题