In order to stop the player from being able to get into parts of your maps until they satisfy parts of the puzzles, it may be useful to lock rooms until a puzzle has been solved. For this functionality we need to:
create a locked flag attribute in Room class
create a lock and unlock method to control the lock
in the move method, add a condition to control if movement to that room is allowed.
lock the locked rooms
create a way to unlock the locked room
Create a locked flag
in room.py
class Room():
number_of_rooms = 0
def __init__(self, room_name):
self.name = room_name
self.description = None
self.linked_rooms = {}
self.character = None
self.item = None
# add attribute here
self.locked = False #by default the room is created unlocked
Room.number_of_rooms = Room.number_of_rooms + 1
2. Create a lock and unlock method
in room.py
def get_character(self):
return self.character
def get_item(self):
return self.item
def set_item(self, item_name):
self.item = item_name
# add the method to lock the room
def lock(self):
self.locked = True
# add the method to unlock the room
def unlock(self):
self.locked = False
def describe(self):
print( self.description )
3. Edit the move method
in room.py
def move(self, direction):
if direction in self.linked_rooms:
# add the if condition that only allow movement if the linked_room.locked is False
if not self.linked_rooms[direction].locked:
return self.linked_rooms[direction]
else:
print("The door is locked")
return self
else:
print("You can't go that way")
return self
4. Lock the locked rooms
in main.py
kitchen.link_room(dining_hall, "south")
dining_hall.link_room(kitchen, "north")
dining_hall.link_room(ballroom, "west")
ballroom.link_room(dining_hall, "east")
# under the linking of the rooms, lock the rooms that should be locked
ballroom.lock()
5. Unlock with key
in main.py
cheese = Item("cheese")
cheese.set_description("A large and smelly block of cheese")
ballroom.set_item(cheese)
book = Item("book")
book.set_description("A really good book entitled 'Knitting for dummies'")
dining_hall.set_item(book)
# place a key in kitchen to pickup and place in backpack
key = Item("key")
key.set_description("A tarnished skeleton key")
kitchen.set_item(key)
current_room = kitchen
current_room = kitchen
backpack = []
dead = False
while dead == False:
# add a checking backpack section to game loop
if key in backpack:
ballroom.unlock()
print("\n")
current_room.get_details()
inhabitant = current_room.get_character()
Unlock by defeating character
in main.py
current_room = kitchen
backpack = []
dead = False
while dead == False:
# add a character check section to game loop
if dining_hall.character == None:
ballroom.unlock()
print("\n")
current_room.get_details()
inhabitant = current_room.get_character()