Page 1 of 2 12 Last
  • Jump to page:
    #1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    31
    Rep Power
    1

    Text based game, adding rooms


    Code:
    #version 0.0.5
    class Game:
        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 ...")
    
        # Initialises variables
        def __init__(self):
            self.exit = False
    
            # Array of known commands
            self._commands = {
                'go': self._go,
                'quit': self._quit,
                "look" : self._look}
    
            # Array of go sub commands, used by _go
            self._commands_go = {"north": self._go_north,
                                 "south" : self._go_south,
                                 "east" : self._go_east,
                                 "west" : self._go_west,
                                 "up" : self._go_up,
                                 "down" : self._go_down}
            
            
        # Method for parsing command, if it gets "comamnd" returns ("command",None)
        @staticmethod
        def parse_command(string):
            index = string.find(' ')
            if index < 0:
                return (string, None)
            return (string[:index], string[index+1:])
    
        # This is main method; the only one which should be called from outside
        # It will just read data from input in never ending loop and parse commands
        def run(self):
            while self.exit != True:
                src = input('> ')
                (command,args) = Game.parse_command(src)
    
                # Do we have this command, execute it
                if command in self._commands:
                    self._commands[command](args)
                else:
                    print("huh?")
    
    
        #######################################################
        ############## All game commands go here ##############
        #######################################################
                    
        def _quit(self,args):
            self.exit = True
            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)")
    
        def _look(self,args):
            print("You see nothing but endless void stretching off in all directions")
    
        # movement handling, will get executed when user types 'go ...' and '...' will be in arg
        def _go(self,args):
            if args is None:
                print("please tell me more",)
                return False
    
            # splits sub command and arguments
            (command,args) = Game.parse_command(args)
            if command not in self._commands_go:
                print( "Sorry, I'm afraid I can't do that !")
                return False
    
            self._commands_go[command](args)
            return True
    
        # directions
        def _go_north(self, args):
            print("You wander of in the direction of north")
    
        def _go_south(self, args):
            print("You wander of in the direction of south")
    
        def _go_east(self, args):
            print("You wander of in the direction of east")
    
        def _go_west(self, args):
            print("You wander of in the direction of west")
    
        def _go_up(self, args):
            print("You wander of in the direction of up")
    
        def _go_down(self, args):
            print("You wander of in the direction of down")
    
    #runs the game
    game = Game()
    game.run()
    Ok so that is ALL of my code.
    im just wondering how can i add rooms in. each room has a number, soo ill need a global variable.

    not all directions can be chosen whilst in certain rooms, ill demonstrate this by an if statement as an example.
    Code:
    if room == 1:
    if user_input == "go_north":
    room == 2
    elif
    if user_input == "go_east":
    print ("you cannot go east because there is a brick wall.")
    pretty much yeah, i just need a room system any ideas?
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    191
    Rep Power
    2
    Make a new class called Room or similar. It should have attributes like area_description, possible_directions, etc. Then make a dictionary in your main class (or even a new class called WorldMap or something), keys will be coordinates like (0,0), (0,1) etc (or (0,0,0) if you also want up and down). Values will be the corresponding room instances. Also give your main class an attribute called current_coordinates (which will also be a coordinate pair) and current_map (which will be the room you are currently in obviously). When a player goes in a valid direction update their coordinate location appropriately and retrieve the corresponding room from the dict.

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

    Join Date
    May 2013
    Posts
    31
    Rep Power
    1
    Originally Posted by Mekire
    Make a new class called Room or similar. It should have attributes like area_description, possible_directions, etc. Then make a dictionary in your main class (or even a new class called WorldMap or something), keys will be coordinates like (0,0), (0,1) etc (or (0,0,0) if you also want up and down). Values will be the corresponding room instances. Also give your main class an attribute called current_coordinates (which will also be a coordinate pair) and current_map (which will be the room you are currently in obviously). When a player goes in a valid direction update their coordinate location appropriately and retrieve the corresponding room from the dict.

    -Mek
    sorry, im only a basic coder would u be able to give me an example or a template please?
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    191
    Rep Power
    2
    Here is a really trivial example (obviously room descriptions wouldn't be hard coded like this but you can probably get the idea):
    python Code:
     
    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)}
     
    class Room:
        def __init__(self,descript,dirs=list(DIRECTIONS.keys())):
            self.descript = descript
            self.available_dirs = dirs
     
    START_ROOM_TEXT = (
    """\nYou open your eyes and find yourself in on of the C Block computer labs ...
    or, rather, the remnants of it. There are certainly 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 ...""")
     
    UP_ROOM_TEXT = (
    """\nYou are above the start room.  How interesting.""")
     
    NORTH_ROOM_TEXT = """North of the start room; amazing."""
     
    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[(0,0,0)]
     
        def get_maps(self):
            maps = {(0,0,0):Room(START_ROOM_TEXT,["up","north"]),
                    (0,0,1):Room(UP_ROOM_TEXT,["down"]),
                    (0,1,0):Room(NORTH_ROOM_TEXT,["south"])}
            return maps
     
        def look(self,Obj):
            print(Obj.descript)
            if Obj == self.CurrentMap:
                print("\nYou can go {}.".format(self.CurrentMap.available_dirs))
     
        def change_map(self,direct):
            if direct in self.CurrentMap.available_dirs:
                for i in range(3):
                    self.current_loc[i]+=DIRECTIONS[direct][i]
                self.CurrentMap = self.map_dict[tuple(self.current_loc)]
                print(self.CurrentMap.descript)
            else:
                print("You can not go {}".format(direct))
     
        def process_command(self,command):
            com = command.lower().split()
            if len(com) == 1 and com[0]=="quit":
                print("You have given in to despair and collapse on the floor.")
                self.exit = True
            elif len(com) >= 1:
                if com[0] == "look":
                    self.look(self.CurrentMap)
                elif com[0] == "go":
                    try:
                        self.change_map(com[1])
                    except IndexError:
                        print("Where exactly are you going?")
     
        def run(self):
            self.look(self.CurrentMap)
            while self.exit != True:
                src = raw_input('> ')
                self.process_command(src)
     
    if __name__ == "__main__":
        #runs the game
        game = Game()
        game.run()

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

    Join Date
    May 2013
    Posts
    31
    Rep Power
    1
    Originally Posted by Mekire
    Here is a really trivial example (obviously room descriptions wouldn't be hard coded like this but you can probably get the idea):
    python Code:
     
    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)}
     
    class Room:
        def __init__(self,descript,dirs=list(DIRECTIONS.keys())):
            self.descript = descript
            self.available_dirs = dirs
     
    START_ROOM_TEXT = (
    """\nYou open your eyes and find yourself in on of the C Block computer labs ...
    or, rather, the remnants of it. There are certainly 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 ...""")
     
    UP_ROOM_TEXT = (
    """\nYou are above the start room.  How interesting.""")
     
    NORTH_ROOM_TEXT = """North of the start room; amazing."""
     
    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[(0,0,0)]
     
        def get_maps(self):
            maps = {(0,0,0):Room(START_ROOM_TEXT,["up","north"]),
                    (0,0,1):Room(UP_ROOM_TEXT,["down"]),
                    (0,1,0):Room(NORTH_ROOM_TEXT,["south"])}
            return maps
     
        def look(self,Obj):
            print(Obj.descript)
            if Obj == self.CurrentMap:
                print("\nYou can go {}.".format(self.CurrentMap.available_dirs))
     
        def change_map(self,direct):
            if direct in self.CurrentMap.available_dirs:
                for i in range(3):
                    self.current_loc[i]+=DIRECTIONS[direct][i]
                self.CurrentMap = self.map_dict[tuple(self.current_loc)]
                print(self.CurrentMap.descript)
            else:
                print("You can not go {}".format(direct))
     
        def process_command(self,command):
            com = command.lower().split()
            if len(com) == 1 and com[0]=="quit":
                print("You have given in to despair and collapse on the floor.")
                self.exit = True
            elif len(com) >= 1:
                if com[0] == "look":
                    self.look(self.CurrentMap)
                elif com[0] == "go":
                    try:
                        self.change_map(com[1])
                    except IndexError:
                        print("Where exactly are you going?")
     
        def run(self):
            self.look(self.CurrentMap)
            while self.exit != True:
                src = raw_input('> ')
                self.process_command(src)
     
    if __name__ == "__main__":
        #runs the game
        game = Game()
        game.run()

    -Mek
    Oh wow thankyou for showing me that, but why do i have to do coordinates, why cant i just give each room and unique number? theres only 12 rooms
  10. #6
  11. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    191
    Rep Power
    2
    You can easily do that too. Using coordinates just makes it more generic.

    -Mek
  12. #7
  13. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    31
    Rep Power
    1
    Originally Posted by Mekire
    You can easily do that too. Using coordinates just makes it more generic.

    -Mek
    im just having a bit of trouble of understanding your code, would u be able to help me on skype or something by any chance?
  14. #8
  15. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    191
    Rep Power
    2
    Every room has a specific coordinate location in my code. If the user enters a "go somewhere" command, the "somewhere" is passed to the function change_room. That function changes the coordinates of the player by using the global constant dictionary DIRECTIONS. It gets the value associated with the direction given (eg "north" will give you (0,1,0) and adds each of those components to the players current location. This way we don't have to write a separate function for each direction. This method of using dictionaries is a common way to avoid ugly inefficient if/elif/else blocks.

    What exactly is it that you are having trouble with?
    -Mek
  16. #9
  17. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    31
    Rep Power
    1
    Originally Posted by Mekire
    Every room has a specific coordinate location in my code. If the user enters a "go somewhere" command, the "somewhere" is passed to the function change_room. That function changes the coordinates of the player by using the global constant dictionary DIRECTIONS. It gets the value associated with the direction given (eg "north" will give you (0,1,0) and adds each of those components to the players current location. This way we don't have to write a separate function for each direction. This method of using dictionaries is a common way to avoid ugly inefficient if/elif/else blocks.

    What exactly is it that you are having trouble with?
    -Mek
    like i understand how it works, its just that im really having a bit of trouble implementing the code or using the code.
  18. #10
  19. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    31
    Rep Power
    1
    Originally Posted by jacobace
    like i understand how it works, its just that im really having a bit of trouble implementing the code or using the code.
    def change_map(self,direct):
    if direct in self.CurrentMap.available_dirs:
    for i in range(3):
    self.current_loc[i]+=DIRECTIONS[direct][i]
    self.CurrentMap = self.map_dict[tuple(self.current_loc)]
    print(self.CurrentMap.descript)
    else:
    print("You can not go {}".format(direct))

    i dont understand for example.
    you cant go north because theres a brick wall or something...
    but the user tries to go north, what stops or how does the code stop him from going north
  20. #11
  21. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    191
    Rep Power
    2
    The rooms have an attribute:
    Code:
    self.available_dirs = dirs
    When I first create and add the rooms to our dictionary I set this attribute:
    Code:
    def get_maps(self):
        maps = {(0,0,0):Room(START_ROOM_TEXT,["up","north"]),
                (0,0,1):Room(UP_ROOM_TEXT,["down"]),
                (0,1,0):Room(NORTH_ROOM_TEXT,["south"])}
        return maps
    Then in the function change_room there is the line:
    Code:
    if direct in self.CurrentMap.available_dirs:
    so if the direction is not in that list it tells you you can't go that way.

    -Mek
  22. #12
  23. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    31
    Rep Power
    1
    Originally Posted by Mekire
    The rooms have an attribute:
    Code:
    self.available_dirs = dirs
    When I first create and add the rooms to our dictionary I set this attribute:
    Code:
    def get_maps(self):
        maps = {(0,0,0):Room(START_ROOM_TEXT,["up","north"]),
                (0,0,1):Room(UP_ROOM_TEXT,["down"]),
                (0,1,0):Room(NORTH_ROOM_TEXT,["south"])}
        return maps
    Then in the function change_room there is the line:
    Code:
    if direct in self.CurrentMap.available_dirs:
    so if the direction is not in that list it tells you you can't go that way.

    -Mek
    im getting an error, and i dont understand how to fix it.
    Code:
    class Game:
        print("you wake up in a class...")
        # Initialises variables
        def get_maps(self):
            maps = {(0,0,0):Room(START_ROOM_TEXT,["up","north"]),
                    (0,0,1):Room(UP_ROOM_TEXT,["down"]),
                    (0,1,0):Room(NORTH_ROOM_TEXT,["south"])}
            return maps
    
        def __init__(self):
            self.exit = False
            self.map_dict = self.get_maps()
            self.current_loc = [0,0,0]
            self.CurrentMap = self.map_dict[(0,0,0)]
    
    
            # Array of known commands
            self._commands = {
                'go': self._go,
                'quit': self._quit,
                "look" : self._look}
    Traceback (most recent call last):
    File "/Users/jakebow11/Desktop/software project/MaliceInMuirfieland backup.py", line 147, in <module>
    game = Game()
    File "/Users/jakebow11/Desktop/software project/MaliceInMuirfieland backup.py", line 47, in __init__
    "look" : self._look}
    AttributeError: 'Game' object has no attribute '_look'


    Code:
    if __name__ == "__main__":
        #runs the game
        game = Game()
        game.run()
  24. #13
  25. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    191
    Rep Power
    2
    I'm not sure what you expect this to do,
    python Code:
    self._commands = {'go': self._go,
                      'quit': self._quit,
                      "look" : self._look}

    As it stands it tries to create a dictionary where for example, the key "go" has a value self._go. self._go has never been assigned though so it has no value and thus your error.

    -Mek

    Edit: Looking back at your code I see you did have a function _look. In my snippet it was called look though as there is no need for the psuedo-privacy here. Maybe you are still using the name I used.
    Last edited by Mekire; May 3rd, 2013 at 09:48 AM.
  26. #14
  27. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    191
    Rep Power
    2
    I believe this may be what you are looking for:
    python Code:
    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)}
     
    class Room:
        def __init__(self,descript,dirs=list(DIRECTIONS.keys())):
            self.descript = descript
            self.available_dirs = dirs
     
    START_ROOM_TEXT = (
    """\nYou open your eyes and find yourself in on of the C Block computer labs ...
    or, rather, the remnants of it. There are certainly 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 ...""")
     
    UP_ROOM_TEXT = (
    """\nYou are above the start room.  How interesting.""")
     
    NORTH_ROOM_TEXT = """North of the start room; amazing."""
     
    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[(0,0,0)]
     
            self.commands = {"go"   : self.go,
                             "quit" : self.quit,
                             "look" : self.look}
     
        def get_maps(self):
            maps = {(0,0,0):Room(START_ROOM_TEXT,["up","north"]),
                    (0,0,1):Room(UP_ROOM_TEXT,["down"]),
                    (0,1,0):Room(NORTH_ROOM_TEXT,["south"])}
            return maps
     
        def look(self,args=None):
            if not args:
                print(self.CurrentMap.descript)
                print("\nYou can go {}.".format(self.CurrentMap.available_dirs))
            else:
                #can we look at other stuff?
                print("Should I be able to see a {} from here?".format(args[0]))
     
        def go(self,args):
            direct = args[0] if args else None
            if direct:
                if direct in self.CurrentMap.available_dirs:
                    for i in range(3):
                        self.current_loc[i]+=DIRECTIONS[direct][i]
                    self.CurrentMap = self.map_dict[tuple(self.current_loc)]
                    print(self.CurrentMap.descript)
                else:
                    print("You can not go {}".format(direct))
            else:
                print("Where exactly are you going?")
     
        def quit(self,args):
            if not args:
                print("You have given in to despair and collapse on the floor.")
                self.exit = True
     
        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?")
     
        def run(self):
            self.look()
            while self.exit != True:
                src = raw_input('> ')
                self.process_command(src)
     
    if __name__ == "__main__":
        #runs the game
        game = Game()
        game.run()

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

    Join Date
    May 2013
    Posts
    31
    Rep Power
    1
    Originally Posted by Mekire
    I believe this may be what you are looking for:
    python Code:
    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)}
     
    class Room:
        def __init__(self,descript,dirs=list(DIRECTIONS.keys())):
            self.descript = descript
            self.available_dirs = dirs
     
    START_ROOM_TEXT = (
    """\nYou open your eyes and find yourself in on of the C Block computer labs ...
    or, rather, the remnants of it. There are certainly 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 ...""")
     
    UP_ROOM_TEXT = (
    """\nYou are above the start room.  How interesting.""")
     
    NORTH_ROOM_TEXT = """North of the start room; amazing."""
     
    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[(0,0,0)]
     
            self.commands = {"go"   : self.go,
                             "quit" : self.quit,
                             "look" : self.look}
     
        def get_maps(self):
            maps = {(0,0,0):Room(START_ROOM_TEXT,["up","north"]),
                    (0,0,1):Room(UP_ROOM_TEXT,["down"]),
                    (0,1,0):Room(NORTH_ROOM_TEXT,["south"])}
            return maps
     
        def look(self,args=None):
            if not args:
                print(self.CurrentMap.descript)
                print("\nYou can go {}.".format(self.CurrentMap.available_dirs))
            else:
                #can we look at other stuff?
                print("Should I be able to see a {} from here?".format(args[0]))
     
        def go(self,args):
            direct = args[0] if args else None
            if direct:
                if direct in self.CurrentMap.available_dirs:
                    for i in range(3):
                        self.current_loc[i]+=DIRECTIONS[direct][i]
                    self.CurrentMap = self.map_dict[tuple(self.current_loc)]
                    print(self.CurrentMap.descript)
                else:
                    print("You can not go {}".format(direct))
            else:
                print("Where exactly are you going?")
     
        def quit(self,args):
            if not args:
                print("You have given in to despair and collapse on the floor.")
                self.exit = True
     
        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?")
     
        def run(self):
            self.look()
            while self.exit != True:
                src = raw_input('> ')
                self.process_command(src)
     
    if __name__ == "__main__":
        #runs the game
        game = Game()
        game.run()

    -Mek
    oh ok yeah now i see what you mean, tyvm very much for your help and effort sorry if i was a bit annoying.
    also "src = raw_input('> ')" needed to be "src = input('> ')" it threw an error with raw_ at the start
Page 1 of 2 12 Last
  • Jump to page:

IMN logo majestic logo threadwatch logo seochat tools logo