Displaying the links
Currently when we instantiate (create) a room, we pass the room id to the creator. Now that room id also identifies the source room, so we can add the code to retrieve the links to the Room class.
The Link class
The links need somewhere to store them, and as the direction will be unique for each room, we will use a Dictionary.
The Link class will store the room id (source room id), where the link goes (destination id), the direction and the description of the link.
class Link():
def __init__(self,sourceID,destinationID,direction,description):
self.sourceID=sourceID
self.destinationID=destinationID
self.direction=direction
self.description=description
# Getters and Setters
def get_sourceID(self):
return self.sourceID
def get_destinationID(self):
return self.destinationID
def get_direction(self):
return self.direction
def get_description(self):
return self.description
Adding Links to the Room class
So the first modification is to the creator:
def __init__(self,room_id,acursor):
sql="SELECT * FROM rooms where roomID=%s "
roomID=(str(room_id),)
acursor.execute(sql,roomID)
myresult = acursor.fetchall()
for x in myresult:
self.roomID=x[0]
self.name=x[1]
self.description=x[2]
self.linked_rooms = {}
# Add linked rooms
sql="select destinationRoomID,direction,description from links where sourceRoomID=%s"
acursor.execute(sql,roomID)
myresult = acursor.fetchall()
for x in myresult:
newLink=Link(self.roomID,x[0],x[1],x[2])
self.linked_rooms[newLink.get_direction()]=newLink
def get_details(self):
print(self.get_name())
print("======")
print(self.get_description())
for direction in self.linked_rooms:
link=self.linked_rooms[direction]
print("There is " + link.get_description()+" to the "+direction)
Now additional changes will need to be made as we continue development, especially once we get to moving between rooms, and when this progresses to being a web application.
Testing the changes
Using the existing testroom.py code, you can examine the rooms by changing the room ID here:
aroom=Room(1,mycursor)
print(aroom.get_details())
aroom=Room(2,mycursor)
print(aroom.get_details())
Dining Hall ====== A room containing pale Scandinavian furniture There is a discrete door to the North There is a grand door to the west None >>>
aroom=Room(3,mycursor)
print(aroom.get_details())
Ballroom ====== A room whose floor is covered in brightly coloured balls. There is a grand door to the east None >>>
Next, moving between rooms.
aroom=Room(2,mycursor)
print(aroom.get_details())
aroom=Room(3,mycursor)
print(aroom.get_details())
References
https://www.w3schools.com/python/python_dictionaries.asp