1

I created a basic game as part of a learning exercise and I'd like to expand it as I learn more Python. The game is a pretty basic, text-based adventure game and some rooms let users pick up items.

I want to write those items to a text file as the user plays and then give the user an option to check his/her 'inventory' during the game. I can't get the syntax right that will enable the script to do the following:

  • Create a new text file when the user starts a game;
  • Write defined items to the text file as the user reaches that part of the game;
  • Create an option to view the inventory (I have an idea how to do this).

Here is an example of part of the script with my attempt at the code for this commented out:

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 if the full script would be useful. I ran a couple searches here and the question that comes closest to what I think I need is this one. I can't work out how to implement this effectively

One of my main challenges is working out how to get the script to create a new text file dynamically and then populate that text file with the items from the inventory.

Paul Jacobson
  • 75
  • 1
  • 9

2 Answers2

1

If you need to write to files in python use 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 will automatically handle exceptions and close file when you finish writing to it.

If you need to a list of defined items you can initialize a dictionary and keep it in the memory like this:

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

Define it in a separate module and import it when you need. Then you can access its values by key and write them to the inventory during the game.

I am not sure what exactly you mean by creating an option to view and inventory. Why not use raw_input() as you already do and check for word 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)

It will print out the contents of your inventory file.

Also note that if you plan to run your game in python3, then don't use raw_input() and use input() instead.

Nurjan
  • 5,184
  • 5
  • 30
  • 47
  • Terrific, thank you. That is very helpful. Would I need to execute the script and name the text file from the command line or will the script just create a text file with the name stated in `with open()`? – Paul Jacobson Jun 19 '17 at 10:27
  • @PaulJacobson If does file does not exist, `with open()` will create it automatically if you use parameter `w`. If it exists the file will rewritten. If you want to append to the existing file then you need to use option `a`. – Nurjan Jun 19 '17 at 10:29
1

You do not need to write to a text file if you use the singleton design pattern. It guarantees that a class always returns one unique instance of itself. Thus you can create a class called "PlayerInventory", and once it has been instanciated at least once, whenever and wherever in your code you try to instantiate your inventory class, it will always return the same instance.

If you wish to make your inventory persistent, so that a player can save a game and get his inventory back after closing the program, use the module called "pickle" to serialize your inventory object directly when exiting.


Example:

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

You can write this class in a separate file and import it whenever you need to access your inventory. Example usecase (assuming your wrote this class in a file called "inventory.py", which is contained in your main package called "mygame"):

from mygame.inventory import PlayerInventory

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

Somewhere else in you code, you might want to check if the player has enough gold to perform a certain action:

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 ...

Appending something to a list of items:

from mygame.inventory import PlayerInventory

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

Note that the import line is only necessary once per file if you put it at the very beggining !

Valentin B.
  • 512
  • 4
  • 16
  • I don't understand much of what you said but from what I do understand it looks like an interesting alternative approach. Thanks. – Paul Jacobson Jun 19 '17 at 10:24
  • Yes, I understand that if you are doing this as a learning exercise and do not necessarily know much about object oriented programming, this can be confusing ! I will add an example to illustrate the concept. – Valentin B. Jun 19 '17 at 12:33
  • I've taken a look at your github repo, as a friendly avice I would recommend splitting up your code in several source files, it will help structure and maintain it ! Good luck with your game, it looks like a good and fun idea to start learning python ! – Valentin B. Jun 19 '17 at 12:55
  • Thanks for your advice. As soon as I figure out how to do that and make it all work together I'll do that. – Paul Jacobson Jun 19 '17 at 13:26