The Complex class
The object classes will all be kept in a single file called game_classes.py. Each class will be added to the bottom of the file and tested / demonstrated in the "if name == 'main':" block.
These are items that require some form of interaction. In our case they are the safe, which requires a combination, the vending machine, which requires the coin, and the book which only requires opening, but we need the player to be able to read the cover of the book before they open it and read the contents. In the event that it becomes too difficult to implement anything in the class methods we can always deal with it in the game engine.
The class diagram for the complex class is:
Complex class |
---|
name open_desc closed_desc state trigger
|
|
The Python code for the class:
class Complex():
'''
Class to define all Complex objects within the game.
Complex object are those that can be manipulated or have to be opened
Attributes:
name: str
open_desc: str
closed_desc: str
trigger: str
contents: list
open: bool (overloaded)
Methods:
get_desc(): Used to return description. This may be a complicated process in some functions
'''
def __init__(self, name, open_desc, closed_desc, trigger):
self.name = name
self.open_desc = open_desc # Desc when closed.
self.closed_desc = closed_desc # Desc when opened
self.trigger = trigger # Something to test for when user tries to open
self.contents = [] # Starts empty. We can put items into it.
self.open = False # Starts off closed
def get_desc(self):
if self.open == False: # If container is closed
return self.closed_desc # return the closed desc
else:
ret_str = self.open_desc + '\n' # Start a return string, note CR
if len(self.contents) == 0: # If container is empty
ret_str += 'It is empty.' # Say "it's empty"
else:
for item in self.contents: # If there is stuff in here,
ret_str += 'There is a ' + item.name + ' here.\n' # List each item in turn.
return ret_str
The code to test the class is:
if __name__ == '__main__':
safe = Complex('safe',
'The safe is small but sturdy with a combination lock on the door.',
'The safe is open.',
'5 4 94')
print(safe.get_desc())
# The safe is small but sturdy with a combination lock on the door.
user_input = '5 4 94'
if user_input == safe.trigger:
safe.open = True
print(safe.get_desc())
# The safe is open.
# It is empty.
Last modified: 07 April 2024