我創建了一個基礎遊戲作爲學習練習的一部分,我想在學習更多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。我不能工作了如何實現這種有效
我的一個主要挑戰是制定出如何讓腳本動態創建一個新的文本文件,然後填充從庫存項目的文本文件。
太棒了,謝謝。這非常有幫助。我是否需要執行腳本並從命令行命名文本文件,或者該腳本是否會創建一個文本文件,其名稱用'open()'表示? –
@PaulJacobson如果文件不存在,如果使用參數'w','with open()'會自動創建它。如果存在,文件將被重寫。如果你想追加到現有的文件,那麼你需要使用選項'a'。 – Nurjan