Newer
Older
from game_object import GameObject
from game import Game, Location
import json
import time
class Player(GameObject):
COUNT = 0
KEY_USERNAME = 'username'
KEY_PASSWORD = 'password'
KEY_CURRENTLOCATION = 'location'
KEY_ITEMS = 'items'
KEY_OFFERS = 'offers'
"""Creates a Player object, for logging in purposes
Attributes:
game -- the Game object related to the player
username -- the Player's username, for identification purposes
password -- the Player's password
location -- the Player's avatar's current position in the map
"""
def __init__(self,
username : str,
password : str,
location : Location = None
):
super().__init__(Player.generateId())
self.username = username
self.password = password
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# some protos
self.token = None
self.items = []
self.offers = []
if not location:
# new user implied
self.currentLocation = Location(0, 0)
else:
# user already exists in db
self.currentLocation = location
self.__loadProperties()
def __loadProperties(self):
with pymongo.MongoClient().get_database(Game.DB_NAME) as db:
cursor = db.get_collection(Game.DB_COLLECTION_USERS).find({'username': self.username})
if cursor.count() == 1:
userDict = cursor.next()
__loadItems(db, userDict)
__loadOffers(db, userDict)
else:
if cursor.count() == 0:
raise LookupError('player not found: {}'.format(self.username))
else: # some error: multiple users found
raise LookupError('multiple players found for {}:{}'.format(self.username, cursor.count()))
def __loadItems(self, db, userDict):
if 'items' in userDict:
for item in enumerate(userDict['items']):
self.items.append(Item(id = item['id'], count = item['count']))
else:
# initialize empty inventory
db.get_collection(Game.DB_COLLECTION_USERS).update(
{
'_id': obj['_id']
},
{
'$set': {
'items': []
}
}
)
def __loadOffers(self, db, userDict):
if 'offers' in userDict:
for offer in enumerate(userDict['offers']):
self.offers.append()
else:
# initialize empty inventory
db.get_collection(Game.DB_COLLECTION_USERS).update(
{
'_id': obj['_id']
},
{
'$set': {
'offers': []
}
}
)
def getInventory(self):
inventory = []
for item in enumerate(self.items):
for count in range(item.count):
inventory.append(item.id)
return inventory
def moveTo(self,
x : int = None,
y : int = None,
location : Location = None):
if x is int and y is int:
if x in range(0, self.game.map.width) and y in range(0, self.game.map.height):
self.currentLocation.x = x
self.currentLocation.y = y
else: raise ValueError('Position out of bounds: ({},{})'.format(x, y))
elif location is Location:
if location.x in range(0, self.game.map.width) and y in range(0, self.game.map.height):
self.currentLocation = location
else:
raise ValueError('Position out of bounds: ({},{})'.format(location.x, location.y))
else:
raise ValueError('Invalid parameter')
def takeItem(self,
x : int = None,
y : int = None,
location : Location = None,
offerId : str = None):
if (x and y) or location:
# take item at position x, y
if not (x and y):
x = location.x
y = location.y
return self.game.map.locations[x][y]
elif offerId is str:
# do lookup
pass
else:
raise TypeError('Invalid parameter')
def addItem(self,
item: Item = None,
itemId: string = None,
count: int = 1):
if isinstance(item, Item):
self.items.append(item)
elif isinstance(id, str) and isinstance(count, int):
self.items.append(Item(id = itemId, count = count))
else:
raise TypeError('Invalid parameter')
def getTradebox(self):
return self.offers
def mixItems(self,
item1: Item,
item2: Item):
pass
def makeOffer(self,
offer: Item,
demand: Item):
pass
def cancelOffer(self, offerId: str):
pass
def acceptOffer(self, offerId: str):
pass
@classmethod
def generateId(self):
Player.COUNT += 1
return "P-{:03d}".format(Player.COUNT)
@classmethod
def __generateToken(self, username, password):
assert isinstance(self.password, str) and isinstance(self.username, str)
text = username
text += ':'
text += password
text += str(int(time.time()))
return bcrypt.hashpw(text.encode(), bcrypt.gensalt())