예제 #1
0
    def combatPokemon(userObj):
        deSerial_pokArray = ast.literal_eval(userObj.pokCollection[0])

        dbSession = orm()
        pokSQLArr = []
        for pokUUID in deSerial_pokArray:
            pokSQL = dbSession.filterBy.get(tablename="pokemon", id=pokUUID)[0]
            myPokObj = pokemon(*pokSQL)
            pokSQLArr.append(myPokObj)

        if len(pokSQLArr):
            options = ['{} : {}'.format(p.name[0], p.id[0]) for p in pokSQLArr]
            form = [{
                "name": "choosePok",
                "type": "list",
                "message": "Pick a pokemon",
                "choices": options
            }]
            answer = prompt(form)
            pokemon_uuid = answer["choosePok"].split(':')[1][1:]

        userObj.setPokemon(pokemon_uuid)

        pokSQL = dbSession.filterBy.get(tablename="pokemon",
                                        id=pokemon_uuid)[0]
        newPokObj = pokemon(*pokSQL)

        return userObj, newPokObj
예제 #2
0
def navigation_func(*args):
	while True:
		username = args[1]['username']
		dbSession = orm()
		usrSQL = dbSession.filterBy.get(tablename="user", username=username)[0]
		usrObj = utilisateur(*usrSQL)
		myZone = int(usrObj.zone[0])
		pokSQLArr = dbSession.filterBy.get(tablename="pokemon")

		options = []
		for pok_ in pokSQLArr:
			pokObj_tmp = pokemon(*pok_)
			options.append(int(pokObj_tmp.zone[0]))

		pokMap = {str(i):str(options.count(i)) for i in range(1, 12)}
		pokMap[str(myZone)] = pokMap[str(myZone)] + '\033[92m'+ " & Me" + '\033[0m'
		baseMap = PrettyTable()

		pokCenter = args[1]['pokCenters']
		for j in range(1, 12 ,4):
			baseMap.add_row(["-----------"]*4)
			baseMap.add_row([pokMap[str(i)] + pokCenter[i-1]  if i<12 else "" for i in range(j, j+4)])
		baseMap = str(baseMap)
		baseMap = baseMap[[i for i, n in enumerate(baseMap) if n == '\n'][2]+1:]
		print(baseMap)


		pyMenus_nav = args[0]['NavigationMenu']
		answers = prompt(pyMenus_nav)
		navDict = {'up': max(myZone-4, 1), 'down': min(myZone+4, 11), 'left': max(1, myZone-1), 'right': min(11, myZone+1)}
		if answers['currentQ'] not in navDict.keys():
			return [1, "pass", ""]
		usrObj.move(navDict[answers['currentQ']])
		resetBanner()
예제 #3
0
def signup_func(*args):
	pyMenus = args[0]['signup']
	answers = prompt(pyMenus)
	userObj = utilisateur(answers['username'].lower(), answers['password'], coin=100, zone=randint(1, 11), xp=1, pokeball=1, berry=0, pokCollectionStr='[]',pokedex='[]')
	dbSession = orm(userObj)
	if not dbSession.add():
		return [1, "pass","L'inscription s'est terminée avec succès, essayez de vous connecter"]
	return [0, "pass", ""]
예제 #4
0
파일: user.py 프로젝트: Dellagi/pokemonApp
	def retirer(pokObj):
		""" Méthode permettant de retirer de la base un Pokemon.

		:param pokObj: objet Pokemon
		:type pokObj: str
		:return: table Pokemon filtrée du Pokemon retiré
		"""
		dbSession = orm()
		return dbSession.filterBy.delete(tablename="pokemon", id=pokObj.id[0])
예제 #5
0
	def wrapper(*args, **kw):
		dbSession = orm(object_= args[0])
		try:
			res = func(*args, **kw)
		finally:
			pKey = [k for k,v in res.__dict__.items() if k[0]!="_" and v[2]["PRIMARY KEY"]][0]
			updates_ = {k:v[0] for k, v in res.__dict__.items() if k[0]!="_" and '_protected' != k[-10:]}
			dbSession.update({pKey: getattr(res, pKey)[0]}, **updates_)
		return res
예제 #6
0
def portfolio_func(*args):
	username = args[1]['username']
	dbSession = orm()
	usrSQL = dbSession.filterBy.get(tablename="user", username=username)[0]
	usrObj = utilisateur(*usrSQL)
	portTemplate = "{}\n├── Coins\n│       └── {}\n├── Pokeballs\n│       └── {}\n├── Experience\n│       └── {}\n├── Berries\n│       └── {}"
	print(portTemplate.format(username, usrObj.coin[0], usrObj.pokeball[0], usrObj.xp[0], usrObj.berry[0]))
	input("Cliquez sur [Entrée] pour Go back to the main menu")
	return [1, "pass", ""]
예제 #7
0
파일: main.py 프로젝트: Dellagi/pokemonApp
def init_DB():
    from tqdm import tqdm
    sys.stdout.write('\033[92m' + "\r" + "[!] Loading ..." + '\033[0m' + '\n')

    APIsession = ApiClass()
    for pok_ in tqdm(APIsession.loadDB(120)):
        pokInfo = APIsession.get_pokemon(pok_['name'])
        pokObj = pokemon(name=pok_['name'],
                         typeArrayStr=json.dumps(pokInfo['types']),
                         movesArrStr=json.dumps(pokInfo['moves']),
                         xp=randint(100, 2000),
                         zone=randint(1, 11))
        dbSession = orm(pokObj)
        dbSession.add()
    print("[!] Pokemons were added to the database")

    dressNames = [
        'Michael', 'Christopher', 'Jessica', 'Matthew', 'Ashley', 'Jennifer',
        'Joshua', 'Amanda', 'Daniel', 'David', 'James', 'Robert', 'John',
        'Joseph', 'Andrew', 'Ryan', 'Brandon', 'Jason', 'Justin', 'Sarah',
        'William', 'Jonathan', 'Stephanie', 'Brian', 'Nicole', 'Nicholas',
        'Anthony', 'Heather', 'Eric', 'Elizabeth', 'Adam', 'Megan', 'Melissa',
        'Kevin', 'Steven', 'Thomas'
    ]
    dbSession = orm()
    pokSQL = dbSession.filterBy.get(tablename="pokemon")[:len(dressNames)]
    shuffle(pokSQL)
    for d in range(len(dressNames)):
        pokCollectionStr = json.dumps([pokSQL[d][0]])
        userObj = utilisateur(dressNames[d].lower(),
                              "fauxCompte",
                              coin=100,
                              zone=randint(1, 11),
                              xp=1500,
                              pokeball=randint(0, 20),
                              berry=randint(0, 20),
                              pokCollectionStr=pokCollectionStr,
                              pokedex='[]')
        dbSession = orm(userObj)
        dbSession.add()

    print("[!] Fake trainers are added to the database")
예제 #8
0
파일: utils.py 프로젝트: Dellagi/pokemonApp
def updateObj(obj_):
    dbSession = orm(obj_)
    pKey = [
        k for k, v in obj_.__dict__.items()
        if k[0] != "_" and v[2]["PRIMARY KEY"]
    ][0]
    updates_ = {
        k: v[0]
        for k, v in obj_.__dict__.items()
        if k[0] != "_" and '_protected' != k[-10:]
    }
    dbSession.update({pKey: getattr(obj_, pKey)[0]}, **updates_)
예제 #9
0
def signin_func(*args):
	for i in range(2):
		pyMenus = args[0]['signin']
		answers = prompt(pyMenus)
		hashed_pass_ = hashlib.sha1(answers['password'].encode('utf8')).hexdigest()
		dbSession = orm()
		usrSQL = dbSession.filterBy.get(tablename="user", username=answers['username'], hashed_pass_protected=hashed_pass_)
		if len(usrSQL):
			return [1, "state_manager['connected']=True;state_manager['username']='******';state_manager['currentMenu']='Menu2';"\
			.format(answers['username']), "[+] Bienvenue {}, tu es dans zone: {}".format(answers['username'], usrSQL[0][3])]
		sys.stdout.write('\033[91m' + "\r" + "[-] Réessayer s'il vous plaît" + '\033[0m' + '\n')
	return [0, "pass", "Échec d'identification"]
예제 #10
0
def dresseurFight_func(*args):
	username = args[1]['username']
	dbSession = orm()
	usrSQL = dbSession.filterBy.get(tablename="user", username=username)[0]
	usrObj = utilisateur(*usrSQL)
	myZone = int(usrObj.zone[0])

	usrSQLArr = dbSession.filterBy.get(tablename="user")
	dressDict = {}
	for usrSQL in usrSQLArr:
		usrObj = utilisateur(*usrSQL)
		if myZone == int(usrObj.zone[0]) and username != usrObj.username[0]:
			dressDict[usrObj.username[0]] = usrObj


	pyMenus_dressDict = args[0]['targetdressMenu']
	pyMenus_dressDict[0]['choices'] = dressDict.keys()

	answers = prompt(pyMenus_dressDict)

	pok_uuid = ast.literal_eval(dressDict[answers['currentQ']].pokCollection[0])[0]
	pokSQL = dbSession.filterBy.get(tablename="pokemon", id=pok_uuid)[0]
	targetPok_ = pokemon(*pokSQL)


	combatObj = combat(userObj=usrObj, enemyPokObj=targetPok_)
	resp = [1, 'pass']
	while resp[0]:
		
		if resp[1] == 'Capture':
			usrObj.Capture(targetPok_)
			if targetPok_.state[0] == 'Not Wild':
				input("Cliquez sur [Entrée] pour Go back to the main menu")
				return [1, "pass", ""]
		elif resp[1] == 'Escape':
			return [1, "pass", "You run out of the fight"]
		elif resp[1] == 'Print':
			print(resp[2])
		elif resp[1] == 'Table':
			fightStats = PrettyTable()
			fightStats.field_names = ['Name', 'Experience', 'Health']
			_  = [fightStats.add_row(r) for r in resp[2]]
			print(fightStats)
		resp = combatObj.call_menus_and_controle_comabt_flow()
		
	input("Cliquez sur [Entrée] pour Go back to the main menu")
	return [1, "pass", ""]
예제 #11
0
def myPokColl_func(*args):
	username = args[1]['username']
	dbSession = orm()
	usrSQL = dbSession.filterBy.get(tablename="user", username=username)[0]
	usrObj = utilisateur(*usrSQL)
	pokedexArr = ast.literal_eval(usrObj.pokCollection[0])
	if len(pokedexArr):
		pokObjArr = []
		for pokID in pokedexArr:
			pokSQL = dbSession.filterBy.get(tablename="pokemon", id=pokID)[0]
			pokObjArr.append(pokemon(*pokSQL))
		pyMenus = args[0]['pokedexMenu']
		pyMenus[0]['choices'] = [i.name[0] for i in pokObjArr]
		answers = prompt(pyMenus)
		showPok = [i for i in pokObjArr if answers['currentQ'] == i.name[0]][0]
		pokProfile_tree(showPok)
		input("Cliquez sur [Entrée] pour Go back to the main menu")
		return [1, "pass", ""]
	return [0, "pass", "Pokedex est vide"]
예제 #12
0
def pokecenter_func(*args):
	username = args[1]['username']
	dbSession = orm()
	usrSQL = dbSession.filterBy.get(tablename="user", username=username)[0]
	usrObj = utilisateur(*usrSQL)
	myZone = int(usrObj.zone[0])

	pokCenter = args[1]['pokCenters']
	if len(pokCenter[myZone-1]):
		pyMenus = args[0]['pokeCenterMenu']
		answers = prompt(pyMenus)
		if answers['currentQ'] in ['Baies', 'pokeballs']:
			quantity_ = [{'type': 'input', 'name': 'purchase',
					'message': 'Enter le nombre de {}'.format(answers['currentQ'])}]
			ansQuantity = prompt(quantity_)
			if answers['currentQ']=='Baies':
				usrObj.shop(num_pokebal=0, num_berry=int(ansQuantity['purchase']))
			else:
				usrObj.shop(num_pokebal=int(ansQuantity['purchase']), num_berry=0)
			time.sleep(2)
		return [1, "pass", ""]
	return [0, "pass", "No Pokecenter is available in this zone"]
예제 #13
0
    def __init__(self, userObj=None, enemyPokObj=None, combat_id=None):
        #self.finished = [[True, False][0 if combat_id else 1], "BOOLEAN",  {"PRIMARY KEY": False, "NOT NULL": True}]
        if combat_id:
            # this for recontructing objects in case of the user try to continue a started match
            dbSession = orm()
            resSQL = dbSession.filterBy.get(tablename="combat",
                                            id=combat_id)[0]
            userIDSql, pok1IDSql, pok2IDSql = resSQL[1], resSQL[2], resSQL[3]

            userSQL = dbSession.filterBy.get(tablename="user",
                                             username=userIDSql)[0]
            userObj = utilisateur(*userSQL)
            userObj.setPokemon(pok1IDSql)

            pokSQL = dbSession.filterBy.get(tablename="pokemon",
                                            id=pok2IDSql)[0]
            enemyPokObj = pokemon(*pokSQL)

            self.__init__(userObj, enemyPokObj)

        else:
            if not ('_utilisateur__setPokemon' in userObj.__dict__.keys()):
                self.combatPokemon(userObj)
            self.id = [
                combat_id if combat_id else str(uuid.uuid4()), "VARCHAR(255)",
                {
                    "PRIMARY KEY": True,
                    "AUTOINCREMENT": False,
                    "NOT NULL": True
                }
            ]
            self.stateCombat = [
                "ON", "VARCHAR(255)", {
                    "PRIMARY KEY": False,
                    "AUTOINCREMENT": False,
                    "NOT NULL": True
                }
            ]
            self.userID = [
                userObj.username[0], "VARCHAR(255)", {
                    "PRIMARY KEY": False,
                    "AUTOINCREMENT": False,
                    "NOT NULL": True
                }
            ]
            self.userPokID = [
                userObj._setPokemon, "VARCHAR(255)", {
                    "PRIMARY KEY": False,
                    "AUTOINCREMENT": False,
                    "NOT NULL": True
                }
            ]
            self.enemyPokId = [
                enemyPokObj.id[0], "VARCHAR(255)", {
                    "PRIMARY KEY": False,
                    "AUTOINCREMENT": False,
                    "NOT NULL": True
                }
            ]
            ###Private attributes###
            self._userObj = userObj
            self._enemyPokObj = enemyPokObj
예제 #14
0
    def call_menus_and_controle_comabt_flow(self):
        apiObj = ApiClass()
        options = ['Escape', 'Change your pokemon', 'Capture', 'Attack']
        dbSession = orm()
        pokSQL = dbSession.filterBy.get(tablename="pokemon",
                                        id=self.userPokID[0])[0]
        PokObj = pokemon(*pokSQL)

        if PokObj.hp[0] <= 0:
            return [0, 'Print', "You lost"]
        elif self._enemyPokObj.hp[0] <= 0:
            return [0, 'Print', "You won"]

        pokMoves_1 = ast.literal_eval(PokObj.moves[0])
        pokMoves_2 = ast.literal_eval(self._enemyPokObj.moves[0])
        pokMovesFinal = {}
        for m in pokMoves_1 + pokMoves_2:
            if m not in pokMovesFinal.keys():
                #pokMovesFinal[m] = apiObj.get_move(m)['accuracy']
                pokMovesFinal[m] = 100
            if len(pokMovesFinal.keys()) > 10:
                break

        form = [{
            "name": "currentQ",
            "type": "list",
            "message": "Choose",
            "choices": options
        }]
        answer = prompt(form)

        if answer['currentQ'] == 'Change your pokemon':
            self._userObj, PokObj = self.combatPokemon(self._userObj)
            self.userPokID[0] = self._userObj._setPokemon
            return [1, 'pass']

        elif answer['currentQ'] == 'Escape':
            return [0, 'pass']

        elif answer['currentQ'] == 'Capture':
            return [1, 'Capture']

        else:

            moves_ = [i for i in pokMoves_1 if i in pokMovesFinal.keys()]

            options = [i for i in moves_]
            form = [{
                "name": "currentQ",
                "type": "list",
                "message": "Choose a move",
                "choices": options
            }]
            answers = prompt(form)

            bias_ = pokMovesFinal[answers['currentQ']]
            bias_Arr = [True] * bias_ + [False] * (100 - bias_)
            if random.choice(bias_Arr) or 1:
                PokObj.attack(self._enemyPokObj)
                self._enemyPokObj.attack(PokObj)
                return [1, 'Table', [[PokObj.name[0], PokObj.xp[0], PokObj.hp[0]],\
                 [self._enemyPokObj.name[0], self._enemyPokObj.xp[0], self._enemyPokObj.hp[0]]]]
예제 #15
0
		superAgainst = list(set(itertools.chain(*[self.__typesOrder__[t] for t in deSerial_Self])))
		if len([self.__typesOrderArr__[i] for i in superAgainst if self.__typesOrderArr__[i] in deSerial_enemyObj]):
			enemyObj.hp[0] = max(enemyObj.hp[0]-10, 0)
		return enemyObj





if __name__ == "__main__":

	pika = dummyPokemonClass(name="Pikachu", typeArrayStr=json.dumps(['paper', 'some different type that loses in front of all others']), movesArrStr=json.dumps(["move1", "move2"]), xp=1300, zone=9)
	crocodil = dummyPokemonClass(name="Crocordil", typeArrayStr=json.dumps(['rock']), movesArrStr=json.dumps(["move1", "move2"]), xp=1300, zone=9)


	dbSession = orm(pika)
	dbSession.add():

	dbSession = orm(crocodil)
	if not dbSession.add():
		print("{} Added successfully".format(crocodil.name[0]))



	#Attack example
	print(pika.hp[0], crocodil.hp[0])
	crocodil = pika.attack(crocodil)
	print(pika.hp[0], crocodil.hp[0])


	'''
예제 #16
0
def pokeDetector_func(*args):
	username = args[1]['username']
	dbSession = orm()
	usrSQL = dbSession.filterBy.get(tablename="user", username=username)[0]
	usrObj = utilisateur(*usrSQL)
	myZone = int(usrObj.zone[0])
	pokSQLArr = dbSession.filterBy.get(tablename="pokemon", zone=myZone, state='Wild')

	options, pokObjArr = [], []
	pok_uuid = []
	for pok_ in pokSQLArr:
		pokObj_tmp = pokemon(*pok_)
		pokObjArr.append(pokObj_tmp)
		options.append(pokObj_tmp.name[0])
		pok_uuid.append(pokObj_tmp.id[0])

	usrObj.pokedex[0] = json.dumps(pok_uuid)
	updateObj(usrObj)

	pyMenus_pokArr = args[0]['targetpokeMenu']
	pyMenus_pokArr[0]['choices'] = options

	answers_1 = prompt(pyMenus_pokArr)

	pyMenus_action = args[0]['fightPok']
	answers_2 = prompt(pyMenus_action)
	if answers_2['currentQ'] == 'Info':
		targetPok_ = [i for i in pokObjArr if answers_1['currentQ'] == i.name[0]][0]
		pokProfile_tree(targetPok_)
		input("Cliquez sur [Entrée] pour Go back to the main menu")
		return [1, "pass", ""]

	elif answers_2['currentQ'] == 'Capture':
		targetPok_ = [i for i in pokObjArr if answers_1['currentQ'] == i.name[0]][0]
		usrObj.Capture(targetPok_)
		input("Cliquez sur [Entrée] pour Go back to the main menu")
		return [1, "pass", ""]

	elif answers_2['currentQ'] == 'Fight':
		targetPok_ = [i for i in pokObjArr if answers_1['currentQ'] == i.name[0]][0]

		combatObj = combat(userObj=usrObj, enemyPokObj=targetPok_)
		resp = [1, 'pass']
		while resp[0]:
			
			if resp[1] == 'Capture':
				usrObj.Capture(targetPok_)
				if targetPok_.state[0] == 'Not Wild':
					input("Cliquez sur [Entrée] pour Go back to the main menu")
					return [1, "pass", ""]
			elif resp[1] == 'Escape':
				return [1, "pass", "You run out of the fight"]
			elif resp[1] == 'Print':
				print(resp[2])
			elif resp[1] == 'Table':
				fightStats = PrettyTable()
				fightStats.field_names = ['Name', 'Experience', 'Health']
				_  = [fightStats.add_row(r) for r in resp[2]]
				print(fightStats)
			resp = combatObj.call_menus_and_controle_comabt_flow()

		input("Cliquez sur [Entrée] pour Go back to the main menu")
		return [1, "pass", ""]

	else:
		targetPok_ = [i for i in pokObjArr if answers_1['currentQ'] == i.name[0]][0]
		usrObj.Capture(targetPok_)
		input("Cliquez sur [Entrée] pour Go back to the main menu")
		return [1, "pass", ""]