The Player 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.
The Player object tracks the players location and inventory. It handles the players movements as well as what they are carrying.
The class diagram is:
Player class |
---|
|
|
The Python code for the class is:
class Player():
'''
Class to define the Player object within the game.
Attributes:
row: int
col: int
items: list
Methods:
do_move() # Used to change the players location.
get_invnetory() # Used to list the objects the player is carrying.
'''
def __init__(self, init_row, init_col):
self.row = init_row
self.col = init_col
self.items = []
def do_move(self, direction):
if direction == 'north':
self.row = self.row + 1
if direction == 'south':
self.row = self.row - 1
if direction == 'east':
self.col = self.col + 1
if direction == 'west':
self.col = self.col - 1
def get_inventory(self):
for item in self.items:
print(f'You have a {item.name}.\n')
def get_location(self):
return [self.row, self.col]
For now, we will just test the movement function. The other functions have been tested in other objects.
if __name__ == '__main__':
player = Player(1, 1)
print(player.get_location()) # [1, 1]
player.do_move('north')
print(player.get_location()) # [2, 1]
player.do_move('east')
print(player.get_location()) # [2, 2]
player.do_move('south')
print(player.get_location()) # [1, 2]
player.do_move('west')
print(player.get_location()) # [1, 1]
Last modified: 07 April 2024