2017-06-19 143 views
1

我創建了一個基礎遊戲作爲學習練習的一部分,我想在學習更多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。我不能工作了如何實現這種有效

我的一個主要挑戰是制定出如何讓腳本動態創建一個新的文本文件,然後填充從庫存項目的文本文件。

回答

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

+0

太棒了,謝謝。這非常有幫助。我是否需要執行腳本並從命令行命名文本文件,或者該腳本是否會創建一個文本文件,其名稱用'open()'表示? –

+0

@PaulJacobson如果文件不存在,如果使用參數'w','with open()'會自動創建它。如果存在,文件將被重寫。如果你想追加到現有的文件,那麼你需要使用選項'a'。 – Nurjan

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") 

注意,在導入線只有每一次FIL必要é如果你把它放在非常開始的地方!

+0

我不太瞭解你說的內容,但從我的理解中可以看出,這看起來像是一種有趣的替代方法。謝謝。 –

+0

是的,我明白如果你是在做這個學習練習,並不一定知道很多關於面向對象的編程,這可能會讓你感到困惑!我將增加一個例子來說明這個概念。 –

+0

我已經看了一下你的github回購,作爲一個友善的建議,我會建議把你的代碼分成幾個源文件,這將有助於結構和維護!祝你的遊戲好運,開始學習python看起來像個好主意! –

相關問題