Database Reference
In-Depth Information
def
def move ( character , direction ):
'''Move the character to a new location'''
# Remove character from current location
db . location . update (
{ '_id' : character [ 'location' ][ 'id' ] },
{ '$pull' : { 'players' : { 'id' : character [ '_id' ] } } })
# Add character to new location, retrieve new location data
new_location = db . location . find_and_modify (
{ '_id' : character [ 'location' ][ 'exits' ][ direction ] },
{ '$push' : { 'players' : {
'id' : character [ '_id' ],
'name' : character [ 'name' ] } } },
new = True )
character [ 'location' ] = new_location
db . character . update (
{ '_id' : character [ '_id' ] },
{ '$set' : { 'location' : new_location } })
Here, note that the code updates the old room, the new room, and the character document.
Since we're using $push and $pull operations to update the location collection, we don't
need to worry about race conditions.
Buy an Item
If the character wants to buy an item, we need to do the following:
1. Add that item to the character's inventory.
2. Decrement the character's gold.
3. Increment the shopkeeper's gold.
4. Update the room.
The following code does just that:
def
def buy ( character , shopkeeper , item_id ):
'''Pick up an item, add to the character's inventory, and transfer
payment to the shopkeeper
'''
price = db . item . find_one ({ '_id' : item_id }, { 'price' : 1 })[ 'price' ]
Search WWH ::




Custom Search