Database Reference
In-Depth Information
def
def get_weapons_for_display ( character , item_index ):
'''Given a character document, return a 'weapons' value
suitable for display'''
result = dict ( left = None , right = None , both = None )
for
for piece iin character [ 'weapons' ]:
item = describe_item ( item_index [ piece [ 'id' ]])
result [ piece [ 'hand' ]] = item
return
return result
In order to actually display the weapons, then, we'd use the following code:
>>>
>>> armor = get_weapons_for_display ( character , item_index )
Extract Character Attributes, Inventory, and Room Information for
Display
In order to display information about the character's attributes, inventory, and surroundings,
we also need to extract fields from the character state. In this case, however, the schema just
defined keeps all the relevant information for display embedded in those sections of the doc-
ument. The code for extracting this data, then, is the following:
>>>
>>> attributes = character [ 'character' ]
>>>
>>> inventory = character [ 'inventory' ]
>>>
>>> room_data = character [ 'location' ]
Pick Up an Item from a Room
In our game, suppose the player decides to pick up an item from the room and add it to their
inventory. In this case, we need to update both the character state and the global location state:
def
def pick_up_item ( character , item_index , item_id ):
'''Transfer an item from the current room to the character's inventory'''
item = item_index [ item_id ]
character [ 'inventory' ] . append ( item )
db . character . update (
{ '_id' : character [ '_id' ] },
{ '$push' : { 'inventory' : item },
'$pull' : { 'location.inventory' : { '_id' : item [ 'id' ] } } })
Search WWH ::




Custom Search