def delete (self, idJeu=None): """ Supprimer un jeu selon l'id """ try: #Si id jeu est précisé if idJeu is not None : #Un seul jeu cle = ndb.Key('Jeux', idJeu) #Suppression des ses heros ndb.delete_multi(Hero.query(ancestor=cle)) #Suppression du jeu cle.delete() else: #Suppression de tous les heros ndb.delete_multi(Hero.query().fetch(keys_only=True)) #Suppression de tous les jeux ndb.delete_multi(Jeux.query().fetch(keys_only=True)) #No content self.response.set_status(204) except (db.BadValueError, ValueError, KeyError): logging.error('%s', traceback.format_exc()) self.error(400) except Exception: logging.error('%s', traceback.format_exc()) self.error(500)
def scrapeHeroes(): #24 heroes for h in range(1, 25): tempurl = baseurl + '/hero/' + str(h) req = urllib.request.Request(tempurl, headers={'User-Agent': 'Mozilla/5.0'}) thejson = urllib.request.urlopen(req, context=context) data_bytes = thejson.read().decode('utf-8') data = json.loads(data_bytes) Hero_id = data['id'] name = data['name'] description = data['description'] role_name = data['role']['name'] abilities_list = data['abilities'] b = False name_str = '' ulti = '' for i in abilities_list: if i['is_ultimate']: ulti = i['name'] else: if not b: name_str += i['name'] b = True else: name_str += ', ' name_str += i['name'] # print(str(Hero_id) + " " + name + "\n" + description + "\n"+ name_str + "\n"+ ulti ) hero = Hero(Hero_id, name, description, role_name, name_str, ulti) db.session.add(hero) db.session.commit()
def createandread(): if request.method=='POST': herodata1=request.get_json() if herodata1 is None: raise APIException ("You need to specify the request body as a json object ", status_code=400) if "first_name" not in herodata1: raise APIException ("You need to specify first name", status_code=400) if "last_name" not in herodata1: raise APIException ("You need to specify last name", status_code=400) if "email" not in herodata1: raise APIException ("You need to specify email", status_code=400) if "password" not in herodata1: raise APIException ("You need to specify password", status_code=400) if "zip_code" not in herodata1: raise APIException ("You need to specify zipcode", status_code=400) if "phone" not in herodata1: raise APIException ("You need to specify phone number", status_code=400) if "share_phone" not in herodata1: raise APIException ("You need to specify share_phone", status_code=400) herodata2=Hero(first_name=herodata1["first_name"],last_name=herodata1["last_name"],email=herodata1["email"],password=herodata1["password"],zip_code=herodata1["zip_code"],phone=herodata1["phone"],share_phone=herodata1["share_phone"]) db.session.add(herodata2) db.session.commit() return "posted it",200 else: herodata3=Hero.query.all() herodata4=list(map(lambda x: x.serialize(),herodata3)) print(herodata4) return jsonify(herodata4),200
class App: def __init__(self): pyxel.init(255, 255, caption='Spooky and Frightening') self.one_bit = One_Bit() self.hero = Hero() pyxel.run(self.update, self.draw) def update(self): if pyxel.btnp(pyxel.KEY_Q): pyxel.quit() self.update_player() def update_player(self): if self.hero.state[5:] == 'right' or self.hero.state[5:] == 'left': self.hero.state = 'idle' + '_' + self.hero.state[5:] if pyxel.btn(pyxel.KEY_D): # player is moving right self.hero.state = 'walk_right' self.hero.x = min(self.hero.x + 2, pyxel.width - 20) return if pyxel.btn(pyxel.KEY_A): # player is moving left self.hero.state = 'walk_left' self.hero.x = max(self.hero.x - 2, 0) return if pyxel.btn(pyxel.KEY_W): self.hero.state = 'walk_up' self.hero.y = max(self.hero.y - 2, -10) return if pyxel.btn(pyxel.KEY_S): self.hero.state = 'walk_down' self.hero.y = min(self.hero.y + 2, pyxel.height - 20) return def draw(self): pyxel.cls(7) pyxel.pal(1, 0) pyxel.text(200, 230, 'x: {}\ny: {}'.format(self.hero.x, self.hero.y), 1) self.one_bit.draw() self.hero.draw()
def parse_hero(data) -> Hero: id = data['id'] name = data['name'] description = data['description'] picture_url = data['thumbnail']['path'] picture = fetch_thumbnail(picture_url) return Hero(id=id, name=name, description=description, picture=picture)
def test_creation_of_treasure(self): c = "levels_and_treasures/level1.txt" d = Dungeon(c) h = Hero(name="Pesho", title="The Great One", health=100, mana=10, mana_regeneration_rate=30) d.spawn(h) d.create_treasures("levels_and_treasures/treasures.txt") self.assertEqual(len(d.treasures), 9)
def test_spawn_with_hero(self): c = "levels_and_treasures/level1.txt" d = Dungeon(c) h = Hero(name="Pesho", title="The Great One", health=100, mana=10, mana_regeneration_rate=30) d.spawn(h) answer = d.hero.known_as() self.assertEqual("Pesho known as The Great One", answer)
def delete(self): """ Permet de supprimer tous ce qui est présent sur la dataStore. Entités jeux et Hero """ # Suppression de tous les heros. ndb.delete_multi(Hero.query().fetch(keys_only=True)) # Suppression de tous les jeux. ndb.delete_multi(Jeux.query().fetch(keys_only=True)) self.response.set_status(204)
def generate_hero(heroes): """Generates hero data while iterating through given hero list. Yields a tuple containing the hero's name and a dictionary containing their information. """ total_heroes = len(heroes) for i, hero in enumerate(heroes): hero = Hero(hero) print(f"{i + 1} of {total_heroes} - {hero.name} data gathered") yield (hero.name.lower(), { "details": hero.details, "abilities": hero.abilities })
def test_get_abilities(self): """ Compare number of scraped abilities to true number of abilities. """ self.maxDiff = None for hero, num_abilities in self.heroes_abilities.items(): test_hero = Hero(hero) test_num_abilities = len(test_hero.abilities) with self.subTest(num_abilities=num_abilities): self.assertEqual( num_abilities, test_num_abilities, f"{hero.title()} has {num_abilities} " f"abilities, not {test_num_abilities}.")
def __new__(cls): cls.mutex.acquire() if cls.dbiInstance is None: cls.user = User.User() cls.combatmatch = CombatMatch.CombatMatch() cls.combatnews = CombatNews.CombatNews() cls.usermap = UserMap.UserMap() cls.hero = Hero.Hero() cls.item = Item.Item() cls.heroconfig = HeroConfig.HeroConfig() cls.setting = Setting.Setting() cls.skillconfig = SkillConfig.SkillConfig() cls.filetable = fileTable.fileTable() cls.dbiInstance = super(DBI, cls).__new__(cls) cls.mutex.release() return cls.dbiInstance
def encounter(): form = HeroStats() if form.validate_on_submit(): hstam = int(form.hstam.data) hskill = int(form.hskill.data) hluck = int(form.hluck.data) estam = int(form.estam.data) eskill = int(form.eskill.data) print load_user hstats = Hero(hstam=hstam, hskill=hskill, hluck=hluck, user_id=load_user) estats = Enemy(estam=estam, eskill=eskill, user_id=load_user) db.session.add(hstats) db.session.add(estats) db.session.commit() return redirect(url_for('fight')) return render_template('encounter.html', form=form)
def hero(_name, page=1): _hero = Hero.get_by_name(_name) if _hero is None: abort(404) # TODO: This is focken slow _replays = _hero.replays.\ order_by(Replay.id.desc()).\ paginate(page, current_app.config["REPLAYS_PER_PAGE"], False) return render_template("dota/hero.html", title=u"{} - Dotabank".format(_hero.localized_name), meta_description=u"Replays archived for {}".format(_hero.localized_name), hero=_hero, replays=_replays, page=page)
def hero(_name, page=1): _hero = Hero.get_by_name(_name) if _hero is None: abort(404) # TODO: This is focken slow _replays = _hero.replays.\ order_by(Replay.id.desc()).\ paginate(page, current_app.config["REPLAYS_PER_PAGE"], False) return render_template("dota/hero.html", title=u"{} - Dotabank".format(_hero.localized_name), meta_description=u"Replays archived for {}".format( _hero.localized_name), hero=_hero, replays=_replays, page=page)
def _heroes_data(): hero_ids = [h.id for h in g.all_heroes] _heroes_and_count = db.session.query( ReplayPlayer.hero_id, db.func.count(ReplayPlayer.replay_id) ).\ group_by(ReplayPlayer.hero_id).\ filter(ReplayPlayer.hero_id.in_(hero_ids)).\ order_by(db.func.count(ReplayPlayer.replay_id).desc()).\ all() _heroes = [] for hero_id, count in _heroes_and_count: _hero = Hero.get_by_id(hero_id) _hero.count = count _heroes.append(_hero) return _heroes
def _heroes_data(): hero_ids = [h.id for h in g.all_heroes] _heroes_and_count = db.session.query( ReplayPlayer.hero_id, db.func.count(ReplayPlayer.replay_id) ).\ group_by(ReplayPlayer.hero_id).\ filter(ReplayPlayer.hero_id.in_(hero_ids)).\ order_by(db.func.count(ReplayPlayer.replay_id).desc()).\ all() _heroes = [] for hero_id, count in _heroes_and_count: _hero = Hero.get_by_id(hero_id) _hero.count = count _heroes.append(_hero) return _heroes
def play_game(): print( 'Controls:\n-Move up - w\n-Move down - s\n-Move left - a\n-Move right - d\n-Cast a spell out of fight - j\n' ) hero_name = input('What\'s your name? ') hero = Hero(name=hero_name, title='Vagabond', health=100, mana=100, mana_regeneration_rate=2) weapon = Weapon(name='Wooden sword', damage=10) hero.equip(weapon) quit = False for i in range(1, 4): file_name = f'levels_and_treasures/level{i}.txt' dungeon = Dungeon(file_name) dungeon.create_treasures('levels_and_treasures/treasures.txt') dungeon.spawn(hero) print(f'{hero.known_as()} entered dungeon {i}') dungeon.print_map() while hero.is_alive() and not dungeon.hero_is_at_gateway(): if get_player_move(dungeon): dungeon.print_map() if not hero.is_alive(): print('GAME OVER') quit = True break hero.level_up() if i != 3 and not ask_to_continue(): quit = True break if not quit: print('Congratulations, you won the game! :)')
def test_get_details(self): """ Compare keys of scraped details to keys of universal/required details. """ universal_details_keys = { "name", "age", "occupation", "baseofoperations", "affiliation", "role", "health" } for hero in self.heroes_abilities.keys(): test_hero = Hero(hero) test_details_keys = test_hero.details.keys() with self.subTest(hero=hero): self.assertTrue( universal_details_keys.issubset(test_details_keys), "Missing required details for {0}: {1}".format( hero.title(), universal_details_keys.difference(test_details_keys)))
def put(self): # with open('jeux.json') as file: # jeux_dict = json.load(file) # json.dumps(jeux_dict) #Ouverture du fichier jeux.json présent dans le même repertoire json_file = open('jeux.json') jeux_dict = json.load(json_file) lstJeux = jeux_dict['Data']['Game'] #Boucle sur les jeux for game in lstJeux: cle = ndb.Key('Jeux', game['id']) jeuxRetour = Jeux(key=cle) jeuxRetour.gameTitle = game['GameTitle'] #formats de date differents try: jeuxRetour.releaseDate = datetime.strptime((game['ReleaseDate']), '%m/%d/%Y') except ValueError: pass jeuxRetour.platform = game['Platform'] if(game.has_key('Hero')): lstHeros = game['Hero'] heroTemp = Hero() if(isinstance(lstHeros, basestring)): lstTemp = [] lstTemp.append(lstHeros) heroTemp.nom = lstTemp jeuxRetour.lstHero = lstTemp else: heroTemp.nom = lstHeros jeuxRetour.lstHero = lstHeros heroTemp.put() jeuxRetour.lstHero = heroTemp.nom #Push le jeu dans le datastore jeuxRetour.put() self.response.set_status(201)
def test_take_mana(self): h = Hero(name="Pesho", title="The Great One", health=100, mana=10, mana_regeneration_rate=30) h.curr_mana = 0 h.take_mana(5) self.assertEqual(h.curr_mana, 5)
def add_heroes_to_globals(): g.all_heroes = sorted(Hero.get_all(), key=lambda h: h.name)
def parse(self, response): for hero in response.xpath( '//body//span[@class="character_icon"]/a/@href'): yield response.follow( 'http://dota.wikia.com' + str(hero.extract()), self.parse) # yield {'heroe': 'http://dota.wikia.com' + str(hero.extract())} names = [] lore = '' for skill in response.xpath('//body//div[@title="Dota 2"]/table/tr'): skill_names = skill.xpath('//td[1]/b/text()') for name in skill_names.extract(): if 'Ability Name' not in name and name not in names: names.append(name) descs = response.xpath( '//body//div[@title="Dota 2"]/table/tr/td[2]').extract()[1:] descs = [re.sub('<.*?>', '', x) for x in descs] self.log(descs) for lore_found in response.xpath('//body//div[@title="Lore"]'): value = lore_found.xpath('//p[2]').extract() lore = ' '.join(value).strip().replace(' ', '').replace('\n', '') if len(lore) < 20: value = lore_found.xpath('//p[3]').extract() lore = ' '.join(value).strip().replace(' ', '').replace('\n', '') lore = re.sub('<.*?>', '', lore) hero_type = response.xpath( '//body//tr[contains(td, " Attributes")]').extract()[0] if 'Agility' in hero_type: hero_type = 'Agility' if 'Intelligence' in hero_type: hero_type = 'Intelligence' if 'Strength' in hero_type: hero_type = 'Strength' hero_name = response.url.split('/')[-1] hero = Hero() hero.lore = lore hero.name = hero_name hero.type = hero_type session.add(hero) session.commit() mongo_skills = [] mongo_hero = {'lore': lore, 'name': hero_name, 'type': hero_type} i = 0 for name in names: db_skill = Skill() db_skill.name = name db_skill.description = descs[i] db_skill.hero_id = hero.id session.add(db_skill) mongo_skills.append({ 'name': name, 'description': descs[i], }) i += 1 mongo_hero['skills'] = mongo_skills heroes.insert_one(mongo_hero) session.commit() session.close()
def add_heroes_to_globals(): g.all_heroes = sorted(Hero.get_all(), key=lambda h: h.name)
def __init__(self): pyxel.init(255, 255, caption='Spooky and Frightening') self.one_bit = One_Bit() self.hero = Hero() pyxel.run(self.update, self.draw)
def test_take_healing(self): h = Hero(name="Pesho", title="The Great One", health=100, mana=10, mana_regeneration_rate=30) h.take_damage(70) h.take_healing(30) self.assertEqual(60, h.curr_health)
def test_is_alive(self): h = Hero(name="Pesho", title="The Great One", health=100, mana=10, mana_regeneration_rate=30) h.take_damage(120) self.assertEqual(False, h.is_alive())
def test_equip(self): h = Hero(name="Pesho", title="The Great One", health=100, mana=10, mana_regeneration_rate=30) w = Weapon(name="GUN", damage=35) h.equip(w) self.assertEqual(h.equiped_weapon.name, "GUN")
def test_learn(self): h = Hero(name="Pesho", title="The Great One", health=100, mana=10, mana_regeneration_rate=30) s = Spell(name="Abrakadabra", damage=50, mana_cost=20, cast_range=4) h.learn(s) self.assertEqual(h.equiped_spell.name, "Abrakadabra")
def test_known_as(self): h = Hero(name="Pesho", title="The Great One", health=100, mana=10, mana_regeneration_rate=30) answer = h.known_as() self.assertEqual("Pesho known as The Great One", answer)
def test_can_cast(self): h = Hero(name="Pesho", title="The Great One", health=100, mana=10, mana_regeneration_rate=30) s = Spell(name="Abrakadabra", damage=50, mana_cost=2, cast_range=4) h.learn(s) self.assertEqual(True, h.can_cast())