Skip to content
Snippets Groups Projects
player.py 4.33 KiB
Newer Older
from game_object import GameObject
from game import Game, Location
	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
					password : str,
					location : Location = None
				):
		super().__init__(Player.generateId())
		self.username = username
		self.password = password

		# 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))

			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,
				count: int = 1):
		if isinstance(item, 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())