Thread: Game objects

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

    Join Date
    May 2013
    Posts
    31
    Rep Power
    2

    Game objects


    ok soo 2 things:
    im looking at implementing 12 items.
    ok soo each items obviously has to be in a room which i believe may have to be done by the coordinates instead of a room number, they each have to have a weight, and whether they are hidden or not which can be represented by a boolean variables (true, false). and a description of the object. 3 commands needs to be registered examine, which then requires the item. get which then required the item, and drop which then requires the item. the player can only hold 4 objects and cannot exceed the weight of 10. however some of the objects weigh 100 (which cant be picked up) an example of this is. and there are more the one item in certainr poms

    object : debris, room location 1 or (0, 0, 0), hidden true, description ("lots of foul smelling garbage")
    object : abacus, room location 1 or (0, 0, 0), hidden false, description ("dont ask me").

    also something i was interested in was playing a wave file. ive had a few looks at how to do this on many websites but sadly no success, i need it to play upon "quit" the game which should be easy to find. the audio file name is "audio.wave" and is from queen- we are the champions it plays "no time for losers, cause are the champions" i thought it would be a bit funny.

    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())
    
    #defines overides for later use when in maze etc.
    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.shh = 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,
                             "restore" : self.restore,
                             "vocab" : self.vocab}
     
        #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
        #defines save.
        def save(self,args):
            if args:
                data = {"room" : self.current_loc,
                        "mode" : self.shh}
                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")
        #defines the restore (load)
        def restore(self,args):
            if args:
                try:
                    with open(args[0],'rb') as myfile:
                        data = pickle.load(myfile)
                    self.shh = data["mode"]
                    self.current_loc = data["room"]
                    self.change_it(True)
                except IOError:
                    print("Sorry, file not found.\n")
            else:
                print("Please enter 'restore' followed by your filename.\n")
    
        #defines the vocab command.
        def vocab(self,args):
            print ("go north, south, east, west, up ,down\nlook quit vocab exits shh\nverbose save restore")
        
        #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 shh mode
        def change_shh(self,args):
            if self.shh == True:
                print ("you're already in shh mode")
            else:
                print("Short-hand mode activated.")
    
                self.shh = True
        #changes to verbose mode
        def change_verbose(self,args):
            if self.shh == False:
                print("you're already in verbose mode")
            else:
                print("Verbose mode activated.")
                self.shh = False
    
        
        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.shh:
                    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 ...")
    
        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.shh 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) ...")
    
        #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
    2
    Well regardless of what you do you will probably have to make your room classes significantly more detailed. Are room descriptions going to change after you get an item or will the description stay static? How will whether or not your player has an item in his possession be processed? If you have a key for instance you will need additional game logic within the pertinent room to check if the pertinent door can be opened.

    How you actually implement the objects entirely depends on how complicated you want them to be. In the simplest case you could simply have a self.inventory attribute for your game and append a string corresponding to the item name. If you want weight and your hidden status you might actually consider creating an item class with corresponding attributes.

    I think your rooms should at the very least gain a new attribute that would be a list of items in that room. When your player picks up an object, you would pop it from the rooms list and add it to the players list. The reverse for dropping.

    As for playing music you can probably find some library to fit your needs. I don't find myself needing to play music in text based applications.

    -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
    Well regardless of what you do you will probably have to make your room classes significantly more detailed. Are room descriptions going to change after you get an item or will the description stay static? How will whether or not your player has an item in his possession be processed? If you have a key for instance you will need additional game logic within the pertinent room to check if the pertinent door can be opened.

    How you actually implement the objects entirely depends on how complicated you want them to be. In the simplest case you could simply have a self.inventory attribute for your game and append a string corresponding to the item name. If you want weight and your hidden status you might actually consider creating an item class with corresponding attributes.

    I think your rooms should at the very least gain a new attribute that would be a list of items in that room. When your player picks up an object, you would pop it from the rooms list and add it to the players list. The reverse for dropping.

    As for playing music you can probably find some library to fit your needs. I don't find myself needing to play music in text based applications.

    -Mek
    no the room will stay the same and atm there is no need for doing anything with the items, but yes i see what you mean by creating at item class.

    and yes i tried the library, thats how i originally thought of doing it but i could never get it to work however its not an essential part of it, it was only just a thought.

    anyways ill give it a try, i see what you mean and a thought just came to my head on the logic and how i would do it so ill give it a try.

IMN logo majestic logo threadwatch logo seochat tools logo