#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    31
    Rep Power
    2

    Save/load text based game in python


    im running mac, python 3 btw.
    i need a save/load game which to be honest i really have no idea how to do, ive only seen examples for windows using the "shelve" located at a page below, soo im confused on how to use on mac, but it also has to be compatible with windows.
    http://inventwithpython.com/blog/2012/05/03/implement-a-save-game-feature-in-python-with-the-shelve-module/

    my current variables are
    current room
    mode

    later ill need to implement items (which i should be able to do from seeing how the room/location are done).

    Code:
    #array of directions
    DIRECTIONS = {"north": ( 0, 1, 0),
                  "south": ( 0,-1, 0),
                  "east" : ( 1, 0, 0),
                  "west" : (-1, 0, 0),
                  "up"   : ( 0, 0, 1),
                  "down" : ( 0, 0,-1)}
     
    ALL_DIRECTIONS = list(DIRECTIONS.keys())
     
    class Room:
        def __init__(self,descript,dirs=None,override_dirs=None):
            self.descript = descript
            if dirs == None:
                self.available_dirs = ALL_DIRECTIONS[:]
            else:
                self.available_dirs = dirs
            if override_dirs == None:
                self.override_dirs = {}
            else:
                self.override_dirs = override_dirs
            self.seen = False
     
     
    #desciptions of every room
    room1 = ("\nC block lab","There is nothing but debris here. You have fond memories of happier hours,\nsitting on stools, hunched over computer terminals. Now, not even the terminals remain.\n")
    room2 = ("\nBalcony","The balcony has seen better days. Most of it has collapsed - rusting steel \nbars jut out from crumbling concrete. Oddly enough, the stairs seem ok.\n")
    room3 = ("\nCourtyard","The C Block courtyard appears to be locked tight. You notice, however, \nthat someone has sawn off some of the bars of the Western gate.\n")
    room4 = ("\nLoading Bay","This is where stores are delivered. The enormous dumpster, you remember \nbeing here, is strangely absent. The concrete her appears to have deep gouges in it.\n")
    room5 = ("\nQuad","The Quad is the center of the school. There is a large gray metal box attached \nto the wall of the library.\n")
    room6 = ("\nB Block Lab","Once full of gleaming terminals, this large room is now empty except for \nan enormous dumpster that appears to have crashed through the ceiling from the floor above. There is a door east.\n")
    room7 = ("\nB Block Quad","This is the B Block Quad. The sun is shining, the birds are singing ... \nIt strikes you as being a wonderful sort of day.\n")
    room8 = ("\nCorridors","The crazy grounds committee has planted a row of hedges here ... \nYou are surrounded by enormous green conifers ... paths lead off in all directions\n")
    room9 = ("\nCorridors","The crazy grounds committee has planted a row of hedges here ... \nYou are surrounded by enormous green conifers ... paths lead off in all directions\n")
    room10 = ("\nCorridors","The crazy grounds committee has planted a row of hedges here ... \nYou are surrounded by enormous green conifers ... paths lead off in all directions\n")
    room11 = ("\nCorridors","The crazy grounds committee has planted a row of hedges here ...\n You are surrounded by enormous green conifers ... paths lead off in all directions\n")
    room12 = ("","You open your eyes to find you have fallen asleep in Software Design again.\nEverything is as it should be - except somehow better.")
    room13 = ("","Was it all really just a dream ? Or are you dreaming now Neo ... Who cares !\nSomehow the experience has given you the answer you needed to finish your last programming assignment\nfor the year. That means a well-earned rest is imminent. Or possibly some free time to write that adventure game you always wanted to write.")
     
    class Game:
        # Initialises variables
        def __init__(self):
            self.exit = False
            self.map_dict = self.get_maps()
            self.current_loc = [0,0,0]
            self.CurrentMap = self.map_dict[tuple(self.current_loc)]
            self.ssh = False
            self.commands = {"go"   : self.go,
                             "quit" : self.quitgame,
                             "look" : self.look,
                             "exits": self.exits,
                             "shh"  : self.change_shh,
                             "verbose" : self.change_verbose}
     
        #defines where each room is on the map and overides
        def get_maps(self):
            maps = {(0,0,0):Room(room1,["west"]),
                    (-1,0,0):Room(room2,["east","down"]),
                    (-1,0,-1):Room(room3,["west","up"]),
                    (-2,0,-1):Room(room4,["south","east"]),
                    (-2,-1,-1):Room(room5,["north","east","west"]),
                    (-1,-1,-1):Room(room6,["east", "west"]),
                    (0,-1,-1):Room(room7,["north","south","east","west","up","down"]),
                    (-3,-1,-1):Room(room8,["north","south","east","west"],{"south":(-4,-1,-1)}),
                    (-3,0,-1):Room(room9,["north","south","east","west"],{"north":(-3,0,-1),"south":(-4,-1,-1),"east":(-4,0,-1),"west":(-3,-1,-1)}),
                    (-4,0,-1):Room(room10,["north","south","east","west"],{"north":(-3,0,-1),"east":(-4,0,-1),"west":(-4,0,-1)}),
                    (-4,-1,-1):Room(room11,["north","south","east","west"],{"north":(-3,0,-1),"south":(-4,-1,-1),"east":(-4,0,-1),"west":(-4,0,-1)}),
                    (1,-1,-1):Room(room12,["north","south","east","west","up","down"],{"north":(-5,-5,-5),"south":(-5,-5,-5),"east":(-5,-5,-5),"west":(-5,-5,-5),"up":(-5,-5,-5),"down":(-5,-5,-5)}),
                    (-5,-5,-5):Room(room13,[])}
            return maps
     
        #when the user inputs "look" it just prints output.
        def look(self,args=None):
           if not args:
            print("You see nothing but endless void stretching off in all directions ...")
     
        #when the user inputs exits, the game prints out a list of valid directions where it can go
        def exits(self,args=None):
           if not args:
              print("You can go {}.".format(self.CurrentMap.available_dirs))
    
        #changes to ssh mode
        def change_shh(self,args):
            print("Short-hand mode activated.")
            self.ssh = True
        #changes to verbose mode
        def change_verbose(self,args):
            print("Verbose mode activated.")
            self.ssh = False
    
        #defines go.
        def go(self,args):
            if direct in self.CurrentMap.override_dirs:
                self.current_loc = list(self.CurrentMap.override_dirs[direct])
                change_it()
            #fixes an error where "sorry, im afraid i cant do that" would appear at wrong times.
            elif direct in DIRECTIONS and "all" in self.CurrentMap.override_dirs:
                self.current_loc = list(self.CurrentMap.override_dirs["all"])
                change_it()
            #changes the room coordinations
            elif direct in self.CurrentMap.available_dirs:
                for i in range(3):
                    self.current_loc[i]+=DIRECTIONS[direct][i]
                change_it()
            #if no valid directions are input then print this
            else:
                if direct not in self.CurrentMap.available_dirs:
                    print("Sorry, I'm afraid I can't do that !")
        def change_it():
            self.CurrentMap = self.map_dict[tuple(self.current_loc)]
            print(self.CurrentMap.descript[0])
            if not self.CurrentMap.seen or not self.ssh:
                print(self.CurrentMap.descript[1])
                self.CurrentMap.seen = True
            #if room = [-5,-5,-5] (room 13) then end the game.
                if self.current_loc == [-5,-5,-5]:
                    self.exit = True
                    go direct = args[0] if args else None
        #if first word is recognised but there is no second input then print this
        else:
            print("Please tell me more ...")
     
        #if user inputs quit then changes self.exit to True which ends the game.
        def quitgame(self,args):
            if not args:
                print("OK ... but a small part of you may never leave until you have personally saved Muirfieland from the clutches of evil .. Bwahahahahahah (sinister laugh) ...")
                self.exit = True
        #if input is not in any commands then print huh
        def process_command(self,command):
            com = command.lower().split()
            if com and com[0] in self.commands:
                self.commands[com[0]](com[1:])
            else:
                print("Huh?")
     
        #run the game and defines the user input.
        def run(self):
            print("You open your eyes and find yourself in on of the C Block computer labs ... or, rather, the remnants of it. There are certain ly no terminals here, just a pile of debris ... it reminds you of the aftermath of the 1997 Year 12 muck up - the one where they set fire to the electricity transformer causing the entire street to be blacked-out for three days. As you stand up, you start to wonder how you got here ... the stench of decay soon changes that thought to one of getting out ...")
            while self.exit != True:
                src = input('> ')
                self.process_command(src)
            input("\nPress enter to exit.")
     
    if __name__ == "__main__":
        #runs the game
        game = Game()
        game.run()
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    194
    Rep Power
    3
    Pickle would probably be the easiest way to do this although some people don't like it. In this case your needs are fairly simple so it should more than suffice.

    Just import pickle and do something like this:
    python Code:
    def save_data(self,filename):
        data = {"room" : self.current_loc,
                "mode" : self.shh}
        with open(filename,'wb') as myfile:
            pickle.dump(data,myfile)
     
    def load_data(self,filename):
        with open(filename,'rb') as myfile:
            data = pickle.load(myfile)
        self.shh = data["mode"]
        self.current_loc = data["room"]
    If your game later needs an inventory or whatever this should be easily extendable too.

    -Mek
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    31
    Rep Power
    2
    Originally Posted by Mekire
    Pickle would probably be the easiest way to do this although some people don't like it. In this case your needs are fairly simple so it should more than suffice.

    Just import pickle and do something like this:
    python Code:
    def save_data(self,filename):
        data = {"room" : self.current_loc,
                "mode" : self.shh}
        with open(filename,'wb') as myfile:
            pickle.dump(data,myfile)
     
    def load_data(self,filename):
        with open(filename,'rb') as myfile:
            data = pickle.load(myfile)
        self.shh = data["mode"]
        self.current_loc = data["room"]
    If your game later needs an inventory or whatever this should be easily extendable too.

    -Mek
    wow i didnt realise it was that simple, like thats what i thought but everything i noticed was for windows.
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    31
    Rep Power
    2
    Originally Posted by jacobace
    wow i didnt realise it was that simple, like thats what i thought but everything i noticed was for windows.
    Code:
    import pickle
    #array of directions
    DIRECTIONS = {"north": ( 0, 1, 0),
                  "south": ( 0,-1, 0),
                  "east" : ( 1, 0, 0),
                  "west" : (-1, 0, 0),
                  "up"   : ( 0, 0, 1),
                  "down" : ( 0, 0,-1)}
     
    ALL_DIRECTIONS = list(DIRECTIONS.keys())
     
    class Room:
        def __init__(self,descript,dirs=None,override_dirs=None):
            self.descript = descript
            if dirs == None:
                self.available_dirs = ALL_DIRECTIONS[:]
            else:
                self.available_dirs = dirs
            if override_dirs == None:
                self.override_dirs = {}
            else:
                self.override_dirs = override_dirs
            self.seen = False
     
     
    #desciptions of every room
    room1 = ("\nC block lab","There is nothing but debris here. You have fond memories of happier hours,\nsitting on stools, hunched over computer terminals. Now, not even the terminals remain.\n")
    room2 = ("\nBalcony","The balcony has seen better days. Most of it has collapsed - rusting steel \nbars jut out from crumbling concrete. Oddly enough, the stairs seem ok.\n")
    room3 = ("\nCourtyard","The C Block courtyard appears to be locked tight. You notice, however, \nthat someone has sawn off some of the bars of the Western gate.\n")
    room4 = ("\nLoading Bay","This is where stores are delivered. The enormous dumpster, you remember \nbeing here, is strangely absent. The concrete her appears to have deep gouges in it.\n")
    room5 = ("\nQuad","The Quad is the center of the school. There is a large gray metal box attached \nto the wall of the library.\n")
    room6 = ("\nB Block Lab","Once full of gleaming terminals, this large room is now empty except for \nan enormous dumpster that appears to have crashed through the ceiling from the floor above. There is a door east.\n")
    room7 = ("\nB Block Quad","This is the B Block Quad. The sun is shining, the birds are singing ... \nIt strikes you as being a wonderful sort of day.\n")
    room8 = ("\nCorridors","The crazy grounds committee has planted a row of hedges here ... \nYou are surrounded by enormous green conifers ... paths lead off in all directions\n")
    room9 = ("\nCorridors","The crazy grounds committee has planted a row of hedges here ... \nYou are surrounded by enormous green conifers ... paths lead off in all directions\n")
    room10 = ("\nCorridors","The crazy grounds committee has planted a row of hedges here ... \nYou are surrounded by enormous green conifers ... paths lead off in all directions\n")
    room11 = ("\nCorridors","The crazy grounds committee has planted a row of hedges here ...\n You are surrounded by enormous green conifers ... paths lead off in all directions\n")
    room12 = ("","You open your eyes to find you have fallen asleep in Software Design again.\nEverything is as it should be - except somehow better.")
    room13 = ("","Was it all really just a dream ? Or are you dreaming now Neo ... Who cares !\nSomehow the experience has given you the answer you needed to finish your last programming assignment\nfor the year. That means a well-earned rest is imminent. Or possibly some free time to write that adventure game you always wanted to write.")
     
    class Game:
        # Initialises variables
        def __init__(self):
            self.exit = False
            self.map_dict = self.get_maps()
            self.current_loc = [0,0,0]
            self.CurrentMap = self.map_dict[tuple(self.current_loc)]
            self.ssh = False
            self.commands = {"go"   : self.go,
                             "quit" : self.quitgame,
                             "look" : self.look,
                             "exits": self.exits,
                             "shh"  : self.change_shh,
                             "verbose" : self.change_verbose,
                             "save" : self.save,
                             "load" : self.load}
     
        #defines where each room is on the map and overides
        def get_maps(self):
            maps = {(0,0,0):Room(room1,["west"]),
                    (-1,0,0):Room(room2,["east","down"]),
                    (-1,0,-1):Room(room3,["west","up"]),
                    (-2,0,-1):Room(room4,["south","east"]),
                    (-2,-1,-1):Room(room5,["north","east","west"]),
                    (-1,-1,-1):Room(room6,["east", "west"]),
                    (0,-1,-1):Room(room7,["north","south","east","west","up","down"]),
                    (-3,-1,-1):Room(room8,["north","south","east","west"],{"south":(-4,-1,-1)}),
                    (-3,0,-1):Room(room9,["north","south","east","west"],{"north":(-3,0,-1),"south":(-4,-1,-1),"east":(-4,0,-1),"west":(-3,-1,-1)}),
                    (-4,0,-1):Room(room10,["north","south","east","west"],{"north":(-3,0,-1),"east":(-4,0,-1),"west":(-4,0,-1)}),
                    (-4,-1,-1):Room(room11,["north","south","east","west"],{"north":(-3,0,-1),"south":(-4,-1,-1),"east":(-4,0,-1),"west":(-4,0,-1)}),
                    (1,-1,-1):Room(room12,["north","south","east","west","up","down"],{"north":(-5,-5,-5),"south":(-5,-5,-5),"east":(-5,-5,-5),"west":(-5,-5,-5),"up":(-5,-5,-5),"down":(-5,-5,-5)}),
                    (-5,-5,-5):Room(room13,[])}
            return maps
     
        #when the user inputs "look" it just prints output.
        def look(self,args=None):
           if not args:
            print("You see nothing but endless void stretching off in all directions ...")
     
        #when the user inputs exits, the game prints out a list of valid directions where it can go
        def exits(self,args=None):
           if not args:
              print("You can go {}.".format(self.CurrentMap.available_dirs))
    
        #changes to ssh mode
        def change_shh(self,args):
            print("Short-hand mode activated.")
            self.ssh = True
        #changes to verbose mode
        def change_verbose(self,args):
            print("Verbose mode activated.")
            self.ssh = False
    
        def save(self,savedata):
            data = {"room" : self.current_loc,
                    "mode" : self.shh}
            with open(savedata,'wb') as myfile:
                pickle.dump(data,myfile)
         
        def load(self,savedata):
            with open(savedata,'rb') as myfile:
                data = pickle.load(myfile)
            self.shh = data["mode"]
            self.current_loc = data["room"] 
    
        def go(self,args):
            def change_it():
                self.CurrentMap = self.map_dict[tuple(self.current_loc)]
                print(self.CurrentMap.descript[0])
                if not self.CurrentMap.seen or not self.ssh:
                    print(self.CurrentMap.descript[1])
                self.CurrentMap.seen = True
                #if room = [-5,-5,-5] (room 13) then end the game.
                if self.current_loc == [-5,-5,-5]:
                    self.exit = True
            direct = args[0] if args else None
            if direct:
                if direct in self.CurrentMap.override_dirs:
                    self.current_loc = list(self.CurrentMap.override_dirs[direct])
                    change_it()
                #fixes an error where "sorry, im afraid i cant do that" would appear at wrong times.
                elif direct in DIRECTIONS and "all" in self.CurrentMap.override_dirs:
                    self.current_loc = list(self.CurrentMap.override_dirs["all"])
                    change_it()
                #changes the room coordinations
                elif direct in self.CurrentMap.available_dirs:
                    for i in range(3):
                        self.current_loc[i]+=DIRECTIONS[direct][i]
                    change_it()
                #if no valid directions are input then print this
                else:
                    if direct not in self.CurrentMap.available_dirs:
                        print("Sorry, I'm afraid I can't do that !")
            #if first word is recognised but there is no second input then print this
            else:
                print("Please tell me more ...")
     
        #if user inputs quit then changes self.exit to True which ends the game.
        def quitgame(self,args):
            if not args:
                print("OK ... but a small part of you may never leave until you have personally saved Muirfieland from the clutches of evil .. Bwahahahahahah (sinister laugh) ...")
                self.exit = True
        #if input is not in any commands then print huh
        def process_command(self,command):
            com = command.lower().split()
            if com and com[0] in self.commands:
                self.commands[com[0]](com[1:])
            else:
                print("Huh?")
     
        #run the game and defines the user input.
        def run(self):
            print("You open your eyes and find yourself in on of the C Block computer labs ... or, rather, the remnants of it. There are certain ly no terminals here, just a pile of debris ... it reminds you of the aftermath of the 1997 Year 12 muck up - the one where they set fire to the electricity transformer causing the entire street to be blacked-out for three days. As you stand up, you start to wonder how you got here ... the stench of decay soon changes that thought to one of getting out ...")
            while self.exit != True:
                src = input('> ')
                self.process_command(src)
            input("\nPress enter to exit.")
     
    if __name__ == "__main__":
        #runs the game
        game = Game()
        game.run()
    ive made a file called savedata its currently in the same folder is the python file is in. im getting this error.
    Traceback (most recent call last):
    File "/Users/jakebow11/Desktop/0.7.5/test.py", line 162, in <module>
    game.run()
    File "/Users/jakebow11/Desktop/0.7.5/test.py", line 156, in run
    self.process_command(src)
    File "/Users/jakebow11/Desktop/0.7.5/test.py", line 147, in process_command
    self.commands[com[0]](com[1:])
    File "/Users/jakebow11/Desktop/0.7.5/test.py", line 96, in save
    "mode" : self.shh}
    AttributeError: 'Game' object has no attribute 'shh'

    edits ive made to original code. in line 56/55 I've added "save, load" to the list of recognised commands, ive also changed the names from "save_data" to just "save" and ive also import pickle
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    194
    Rep Power
    3
    Probably my fault actually.

    In your Game class __init__ the attribute is called self.ssh.

    In the functions I wrote for you above, I wrote self.shh.

    You should probably do yourself a favor and just rename the variable self.short_hand. Much more self documenting and easier to remember.

    -Mek
  10. #6
  11. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    31
    Rep Power
    2
    Originally Posted by Mekire
    Probably my fault actually.

    In your Game class __init__ the attribute is called self.ssh.

    In the functions I wrote for you above, I wrote self.shh.

    You should probably do yourself a favor and just rename the variable self.short_hand. Much more self documenting and easier to remember.

    -Mek
    no dw its not your fault you tried to do what was best, i wouldve seen the ssh problem but i fixed it earlier that day and i must not have saved it.

    File "/Users/jakebow11/Desktop/0.7.5/test.py", line 150, in save
    with open(savedata,'wb') as myfile:
    TypeError: invalid file: []

    i seem to be getting that error now. do you think it might be because its an rtf file and not a txt file
  12. #7
  13. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    194
    Rep Power
    3
    According to that error the argument savedata you are passing is an empty list; not a file name:

    python Code:
    savedata = []
     
    with open(savedata,'wb') as myfile:
        pass
    Code:
    TypeError: invalid file: []
    savedata should be a filename string like:
    python Code:
    savedata = "mysavedata.txt"
     
    with open(savedata,'wb') as myfile:
        pass

    -Mek
  14. #8
  15. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    31
    Rep Power
    2
    Originally Posted by Mekire
    According to that error the argument savedata you are passing is an empty list; not a file name:

    python Code:
    savedata = []
     
    with open(savedata,'wb') as myfile:
        pass
    Code:
    TypeError: invalid file: []
    savedata should be a filename string like:
    python Code:
    savedata = "mysavedata.txt"
     
    with open(savedata,'wb') as myfile:
        pass

    -Mek
    ok so this is my "save" function
    Code:
        def save(self,savedata):
            savedata = "savedata.txt"
            data = {"room" : self.current_loc,
                    "mode" : self.shh}
            with open(savedata,'wb') as myfile:
                pickle.dump(data,myfile)
                pass
    the data that is saved is
    }q(Xroomq]q(JˇˇˇˇKJˇˇˇˇeXmodequ.
    is it meant to be like that?

    also load isnt doing anything, it doesnt throw any error, but it doesnt load the location/mode and im assuming because the saved data is like that.
    Code:
        def load(self,savedata):
            savedata = "savedata.txt"
            with open(savedata,'rb') as myfile:
                data = pickle.load(myfile)
            self.shh = data["mode"]
            self.current_loc = data["room"]
  16. #9
  17. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    194
    Rep Power
    3
    The pickled file looks fine. Pickle files are not human readable (in general). Don't bother looking at it. You need to confirm whether or not your room is actually changed after a load. Remember that simply changing the users self.current_loc doesn't actually change the map. The part that usually changes your map is in your go method. After loading you need to make this change the room. You will also have to add something to make it redisplay the current room description immediately after loading.

    Also you don't need to pass savedata as an argument if you are just going to define it in the function. My intention was that your game could handle multiple saves. You would pass the required save file name based on whatever. You could even parse it as part of the user command. This way your game could support multiple people playing it who weren't necessarily all at the same point in the game.

    -Mek
  18. #10
  19. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    31
    Rep Power
    2
    Originally Posted by Mekire
    The pickled file looks fine. Pickle files are not human readable (in general). Don't bother looking at it. You need to confirm whether or not your room is actually changed after a load. Remember that simply changing the users self.current_loc doesn't actually change the map. The part that usually changes your map is in your go method. After loading you need to make this change the room. You will also have to add something to make it redisplay the current room description immediately after loading.

    Also you don't need to pass savedata as an argument if you are just going to define it in the function. My intention was that your game could handle multiple saves. You would pass the required save file name based on whatever. You could even parse it as part of the user command. This way your game could support multiple people playing it who weren't necessarily all at the same point in the game.

    -Mek
    sorry yes it does work, and its been working the problem was it just dude set the coordinates to the coordinates that were saved.

    the mode seems to be saving/loading properly but the room isn't. soo how would i set the room to load properly? because i cant do

    self.current_loc = self.current_loc

    nor can i do

    self.current_loc = data

    but saving it as

    "room" : self.current_loc

    and loading it as

    self.current_loc = data["room"]

    should work should it?
  20. #11
  21. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    194
    Rep Power
    3
    python Code:
    import pickle
     
    #array of directions
    DIRECTIONS = {"north": ( 0, 1, 0),
                  "south": ( 0,-1, 0),
                  "east" : ( 1, 0, 0),
                  "west" : (-1, 0, 0),
                  "up"   : ( 0, 0, 1),
                  "down" : ( 0, 0,-1)}
     
    ALL_DIRECTIONS = list(DIRECTIONS.keys())
     
    class Room:
        def __init__(self,descript,dirs=None,override_dirs=None):
            self.descript = descript
            if dirs == None:
                self.available_dirs = ALL_DIRECTIONS[:]
            else:
                self.available_dirs = dirs
            if override_dirs == None:
                self.override_dirs = {}
            else:
                self.override_dirs = override_dirs
            self.seen = False
     
     
    #desciptions of every room
    room1 = ("\nC block lab","There is nothing but debris here. You have fond memories of happier hours,\nsitting on stools, hunched over computer terminals. Now, not even the terminals remain.\n")
    room2 = ("\nBalcony","The balcony has seen better days. Most of it has collapsed - rusting steel \nbars jut out from crumbling concrete. Oddly enough, the stairs seem ok.\n")
    room3 = ("\nCourtyard","The C Block courtyard appears to be locked tight. You notice, however, \nthat someone has sawn off some of the bars of the Western gate.\n")
    room4 = ("\nLoading Bay","This is where stores are delivered. The enormous dumpster, you remember \nbeing here, is strangely absent. The concrete her appears to have deep gouges in it.\n")
    room5 = ("\nQuad","The Quad is the center of the school. There is a large gray metal box attached \nto the wall of the library.\n")
    room6 = ("\nB Block Lab","Once full of gleaming terminals, this large room is now empty except for \nan enormous dumpster that appears to have crashed through the ceiling from the floor above. There is a door east.\n")
    room7 = ("\nB Block Quad","This is the B Block Quad. The sun is shining, the birds are singing ... \nIt strikes you as being a wonderful sort of day.\n")
    room8 = ("\nCorridors","The crazy grounds committee has planted a row of hedges here ... \nYou are surrounded by enormous green conifers ... paths lead off in all directions\n")
    room9 = ("","You open your eyes to find you have fallen asleep in Software Design again.\nEverything is as it should be - except somehow better.")
    room10 = ("","Was it all really just a dream ? Or are you dreaming now Neo ... Who cares !\nSomehow the experience has given you the answer you needed to finish your last programming assignment\nfor the year. That means a well-earned rest is imminent. Or possibly some free time to write that adventure game you always wanted to write.")
     
    class Game:
        # Initialises variables
        def __init__(self):
            self.exit = False
            self.map_dict = self.get_maps()
            self.current_loc = [0,0,0]
            self.CurrentMap = self.map_dict[tuple(self.current_loc)]
            self.short_hand = False
            self.commands = {"go"   : self.go,
                             "quit" : self.quitgame,
                             "look" : self.look,
                             "exits": self.exits,
                             "short": self.change_short_hand,
                             "long" : self.change_verbose,
                             "load" : self.load,
                             "save" : self.save}
     
        #defines where each room is on the map and overides
        def get_maps(self):
            maps = {(0,0,0):Room(room1,["west"]),
                    (-1,0,0):Room(room2,["east","down"]),
                    (-1,0,-1):Room(room3,["west","up"]),
                    (-2,0,-1):Room(room4,["south","east"]),
                    (-2,-1,-1):Room(room5,["north","east","west"]),
                    (-1,-1,-1):Room(room6,["east", "west"]),
                    (0,-1,-1):Room(room7),
                    (-3,-1,-1):Room(room8,["north","south","east","west"],{"south":(-4,-1,-1)}),
                    (-3,0,-1):Room(room8,["north","south","east","west"],{"north":(-3,0,-1),"south":(-4,-1,-1),"east":(-4,0,-1),"west":(-3,-1,-1)}),
                    (-4,0,-1):Room(room8,["north","south","east","west"],{"north":(-3,0,-1),"east":(-4,0,-1),"west":(-4,0,-1)}),
                    (-4,-1,-1):Room(room8,["north","south","east","west"],{"north":(-3,0,-1),"south":(-4,-1,-1),"east":(-4,0,-1),"west":(-4,0,-1)}),
                    (1,-1,-1):Room(room9,None,{"all":(-5,-5,-5)}),
                    (-5,-5,-5):Room(room10,[])}
            return maps
     
        def save(self,args):
            if args:
                data = {"room" : self.current_loc,
                        "mode" : self.short_hand}
                try:
                    with open(args[0],'wb') as myfile:
                        pickle.dump(data,myfile)
                    print("Game saved as {}\n".format(args[0]))
                except IOError:
                    print("Invalid filename\n")
            else:
                print("Please enter 'save' followed by your filename.\n")
     
        def load(self,args):
            if args:
                try:
                    with open(args[0],'rb') as myfile:
                        data = pickle.load(myfile)
                    self.short_hand = data["mode"]
                    self.current_loc = data["room"]
                    self.change_it(True)
                except IOError:
                    print("Sorry, file not found.\n")
            else:
                print("Please enter 'load' followed by your filename.\n")
     
        #when the user inputs "look" it just prints output.
        def look(self,args=None):
           if not args:
            print("You see nothing but endless void stretching off in all directions ...")
     
        #when the user inputs exits, the game prints out a list of valid directions where it can go
        def exits(self,args=None):
           if not args:
              print("You can go {}.".format(self.CurrentMap.available_dirs))
     
        #changes to short_hand mode
        def change_short_hand(self,args):
            print("Short-hand mode activated.")
            self.short_hand = True
        #changes to verbose mode
        def change_verbose(self,args):
            print("Verbose mode activated.")
            self.short_hand = False
     
        #defines go.
        def go(self,args):
            direct = args[0] if args else None
            if direct:
                if direct in self.CurrentMap.override_dirs:
                    self.current_loc = list(self.CurrentMap.override_dirs[direct])
                    self.change_it()
                #fixes an error where "sorry, im afraid i cant do that" would appear at wrong times.
                elif direct in DIRECTIONS and "all" in self.CurrentMap.override_dirs:
                    self.current_loc = list(self.CurrentMap.override_dirs["all"])
                    self.change_it()
                #changes the room coordinations
                elif direct in self.CurrentMap.available_dirs:
                    for i in range(3):
                        self.current_loc[i]+=DIRECTIONS[direct][i]
                    self.change_it()
                #if no valid directions are input then print this
                else:
                    if direct not in self.CurrentMap.available_dirs:
                        print("Sorry, I'm afraid I can't do that !")
            #if first word is recognised but there is no second input then print this
            else:
                print("Please tell me more ...")
     
        def change_it(self,load=False):
            self.CurrentMap = self.map_dict[tuple(self.current_loc)]
            print(self.CurrentMap.descript[0])
            if not self.CurrentMap.seen or not self.short_hand or load:
                print(self.CurrentMap.descript[1])
                self.CurrentMap.seen = True
            #if room = [-5,-5,-5] (room 13) then end the game.
                if self.current_loc == [-5,-5,-5]:
                    self.exit = True
     
        #if user inputs quit then changes self.exit to True which ends the game.
        def quitgame(self,args):
            if not args:
                print("OK ... but a small part of you may never leave until you have personally saved Muirfieland from the clutches of evil .. Bwahahahahahah (sinister laugh) ...")
                self.exit = True
        #if input is not in any commands then print huh
        def process_command(self,command):
            com = command.lower().split()
            if com and com[0] in self.commands:
                self.commands[com[0]](com[1:])
            else:
                print("Huh?")
     
        #run the game and defines the user input.
        def run(self):
            print("You open your eyes and find yourself in on of the C Block computer labs ... or, rather, the remnants of it. There are certain ly no terminals here, just a pile of debris ... it reminds you of the aftermath of the 1997 Year 12 muck up - the one where they set fire to the electricity transformer causing the entire street to be blacked-out for three days. As you stand up, you start to wonder how you got here ... the stench of decay soon changes that thought to one of getting out ...")
            while self.exit != True:
                src = input('> ')
                self.process_command(src)
            input("\nPress enter to exit.")
     
    if __name__ == "__main__":
        #runs the game
        game = Game()
        game.run()
    Code:
    >>> 
    You open your eyes and find yourself in on of the C Block computer labs ... or, rather, the remnants of it. There are certain ly no terminals here, just a pile of debris ... it reminds you of the aftermath of the 1997 Year 12 muck up - the one where they set fire to the electricity transformer causing the entire street to be blacked-out for three days. As you stand up, you start to wonder how you got here ... the stench of decay soon changes that thought to one of getting out ...
    > go west
    
    Balcony
    The balcony has seen better days. Most of it has collapsed - rusting steel 
    bars jut out from crumbling concrete. Oddly enough, the stairs seem ok.
    
    > go down
    
    Courtyard
    The C Block courtyard appears to be locked tight. You notice, however, 
    that someone has sawn off some of the bars of the Western gate.
    
    > save spammy
    Game saved as spammy
    
    > go east
    Sorry, I'm afraid I can't do that !
    > exits
    You can go ['west', 'up'].
    > go up
    
    Balcony
    The balcony has seen better days. Most of it has collapsed - rusting steel 
    bars jut out from crumbling concrete. Oddly enough, the stairs seem ok.
    
    > go west
    Sorry, I'm afraid I can't do that !
    > go east
    
    C block lab
    There is nothing but debris here. You have fond memories of happier hours,
    sitting on stools, hunched over computer terminals. Now, not even the terminals remain.
    
    > load
    Please enter 'load' followed by your filename.
    
    > load cheese
    Sorry, file not found.
    
    > load spammy
    
    Courtyard
    The C Block courtyard appears to be locked tight. You notice, however, 
    that someone has sawn off some of the bars of the Western gate.
    
    > quit
    OK ... but a small part of you may never leave until you have personally saved Muirfieland from the clutches of evil .. Bwahahahahahah (sinister laugh) ...
    
    Press enter to exit.
    >>>
    -Mek

IMN logo majestic logo threadwatch logo seochat tools logo