def test_delete_hero(self): """Test delete hero""" # Criando o heroi hero = self.create_hero('Joker', 'dc') # excluindo o heroi Hero.delete(hero.id) # consultando se o heroi foi mesmo excluido self.assertIsNone(Hero.get_hero(hero.id))
def delete(self, hero_id): """Delete hero""" try: Hero.delete(hero_id) return {'message': 'Hero deleted'} except Exception as error: return { 'message': 'Error on delete hero', 'details': str(error) }, 500
def get(self): """Get heroes""" try: # Fazendo a consulta no banco de dados heroes = Hero.get_heroes(request.args.get('cursor')) # Montando a resposta, por enquanto iremos deixar o cursor vazio response = { 'cursor': None, 'heroes': [] } # Vamos percorer os herois e transformar em json for hero in heroes: response['heroes'].append(hero.to_dict()) # Adicionando o cursor no resultado da consulta if len(response['heroes']) == 16: response['cursor'] = response['heroes'][-1]['id'] return response except Exception as error: return { 'message': 'Error on get heroes', 'details': str(error) }, 500
def test_update_hero(self): """Test update hero""" # Criando o heroi hero = self.create_hero('Hero', 'dc') # Enviando a requisição para obter o heroi params = { 'hero': { 'name': 'Hawkwoman', 'description': hero.description, 'universe': hero.universe, 'imageUrl': 'https://exitoina.uol.com.br/media/_versions/mulher_gaviao_3_widexl.jpg' } } response = self.app.post(path='/hero/{0}'.format(hero.id), json=params) # Resposta da requisição self.assertEqual(response.status_code, 200) # Obtendo o heroi atualizado para conferir o novo nome hero_updated = Hero.get_hero(hero.id) self.assertEqual(hero_updated.name, 'Hawkwoman')
def test_hero_initialize(): test_dice = Dice([0]) test_hero = Hero(test_dice) assert test_hero.hp == hero_config.BASE_HP assert test_hero.sp == hero_config.BASE_SP assert test_hero.dp == 0
def __init__(self, map): """ init of the parents + define the image and the scale of the Graphical Hero Args: map """ self.map = map pygame.sprite.Sprite.__init__(self) Hero.__init__(self, self.map) hero_image = pygame.image.load(MC_GYVER_FILE).convert() self.hero_img = pygame.transform.scale( hero_image, (int(SPRITE_HEIGTH), int(SPRITE_WIDTH))) self.rect = self.hero_img.get_rect() start_pos = self.map.get_start self.rect.x = start_pos.getx self.rect.y = start_pos.gety self.old_x = 0 self.old_y = 0
def create_hero(hero_name, universe): hero = Hero() hero.name = hero_name hero.description = '{0} description'.format(hero_name) hero.universe = universe hero.save() return hero
def create(cls, params): """""" if not params.get('name'): return {'error': str('name is required')}, 400 if not params.get('universe'): return {'error': str('universe is required')}, 400 hero = Hero() hero.name = cls.title_case(params.get('name')) hero.image_url = cls.title_case(params.get('imageUrl')) hero.description = cls.title_case(params.get('description')) hero.universe = cls.title_case(params.get('universe')) hero.save() return hero.to_dict()
def get(self, hero_id): """Get hero""" try: hero = Hero.get_hero(hero_id) if hero: return hero.to_dict() return {'message': 'Hero not found'}, 404 except Exception as error: return {'message': 'Error on get hero', 'details': str(error)}, 500
def __init__(self): pygame.init() self.laby = Laby() self.hero = Hero(self.laby) self.needle = Item("needle", self.laby) self.ether = Item("Ether", self.laby) self.tube = Item("Tube", self.laby) self.screen = pygame.display.set_mode((480, 520)) self.title_screen = title_screen self.logo_screen = logo_screen self.background = pygame.Surface((710, 700)) self.background.fill((255, 255, 255)) self.start_img = start self.end_img = end self.wall = walls for wall in self.laby.walls: x, y = wall self.background.blit(self.wall, (x * sprite_size, y * sprite_size)) self.path = paths for path in self.laby.paths: x, y = path self.background.blit(self.path, (x * sprite_size, y * sprite_size)) self.end_pos = end for end_pos in self.laby.end: x, y = end_pos self.background.blit(self.end_pos, (x * sprite_size, y * sprite_size)) self.allsprites = pygame.sprite.Group() self.allsprites.add(ItemSprite(self.needle, needle)) self.allsprites.add(ItemSprite(self.ether, ether)) self.allsprites.add(ItemSprite(self.tube, tube)) self.allsprites.add(HeroSprite(self.hero)) pygame.display.update()
def test_save_and_get_hero(self): """Test save and get hero""" # Criando o novo heroi new_hero = Hero() new_hero.name = 'Superman' new_hero.description = 'Superman' new_hero.universe = 'dc' new_hero.save() # Obtendo o heroi pelo id hero = Hero.get_hero(new_hero.id) self.assertEqual(hero.name, 'Superman') self.assertEqual(hero.id, new_hero.id)
def test_blacksmith_quest(self): hero = Hero(name="Pigbear") hero.journal.quest_paths.append(self.meet_the_blacksmith_path) assert len(hero.handlers) == 0 # I'm not sure if this should be 1 here. hero.current_location = self.blacksmith self.db.session.add(hero) self.db.session.commit() assert len(hero.handlers) == 1 trigger_id = hero.handlers[0].trigger.id handler_id = hero.handlers[0].id assert hero.journal.current_quest_paths[0].id != self.meet_the_blacksmith_path.id # Now for the Engine. engine = Engine(self.db) engine.spawn( 'move_event', hero, description="{} visits {}.".format(hero.name, self.blacksmith.url) ) self.rebuild_instance() hero = self.db.session.query(Hero).filter_by(name="Pigbear").one() assert handler_id == hero.handlers[0].id assert len(hero.handlers) == 1 assert trigger_id != hero.handlers[0].trigger.id # assert len(hero.triggers) == 1 engine.spawn( 'buy_event', hero, description="{} buys a/an {}.".format(hero.name, "Sword.") ) self.rebuild_instance() hero = self.db.session.query(Hero).filter_by(name="Pigbear").one() assert hero.handlers == []
def delete(self, hero_id): """Delete hero""" try: hero = Hero.delete(hero_id) if not hero: return {'message': 'Hero deleted'}, 200 return {'message': 'Hero not found'}, 404 except Exception as error: return { 'message': 'Error on delete hero', 'details': str(error) }, 500
def post(self, hero_id): """Update a hero""" try: hero = Hero.get_hero(hero_id) if not hero: return {'message': 'Hero not found'}, 404 HeroModule.update(hero, request.json['hero']) return hero.to_dict() except Exception as error: return { 'message': 'Error on update hero', 'details': str(error) }, 500
def create(params): """ Create a new hero :param dict params: Request dict params :return Hero: Hero created """ hero = Hero() hero.name = params['name'] hero.description = params['description'] hero.imageUrl = params['imageUrl'] hero.universe = params['universe'] HeroModule.format_hero_params(hero) HeroModule.valid_hero_params(hero) hero.save() return hero
def get_heroes_from_db(): conn = sqlite3.connect(DB_DIR) cursor = conn.cursor() query = 'select id, name, hp, defence, speed, recovery, mind, path from Hero' cursor.execute(query) db_heroes = cursor.fetchall() query = ''' select name, power, speed, cost, type, sacrifice, range, user from Move ''' cursor.execute(query) db_moves = cursor.fetchall() heroes = {} moves = [] for db_hero in db_heroes: hero_id, name, hp, defence, speed, recovery, mind, img_path = db_hero hero = Hero(name, hp, defence, speed, recovery, mind, img_path) heroes[hero_id] = hero for db_move in db_moves: name, power, speed, cost, type_, sacrifice, range_, user = db_move assert range_ in ('target', 'area', 'self', 'self area') power = power if power else 0 move = Attack(name, power, speed, cost, sacrifice, type_, range_) moves.append((user, move)) for hero_id, move in moves: hero = heroes[hero_id] if move.speed is None: move.speed = hero.speed move.initial_speed = hero.speed hero.add_move(move) return list(heroes.values())
def test_get_heroes(self): """Test get heroes""" # Aqui vamos fazer um loop e criar 20 herois for index in range(1, 21): self.create_hero('Hero {0}'.format(index), 'marvel') # Chamando o metodo para obter os herois heroes = Hero.get_heroes() # Percorrendo todos os herois e transformando eles em dict(json) heroes_dict = [hero.to_dict() for hero in heroes] # Consultando a quantidade de item que retornou self.assertEqual(len(heroes_dict), 16) for hero in heroes_dict: self.assertTrue(hero['name'].startswith('Hero'))
def post(self, hero_id): """Update a hero""" try: hero_update = Hero.get_hero(hero_id) if hero_update: return hero_update.to_dict() HeroModule.update(hero_update, request.json['hero']) except Exception as error: return { 'message': 'Error on update hero', 'details': str(error) }, 500
def post(self, hero_id): """Update a hero""" try: if not request.is_json or 'hero' not in request.json: return {'message': 'Bad request'}, 400 hero_update = Hero.get_hero(hero_id) hero = HeroModule.update(hero_update, request.json['hero']) return hero except Exception as error: return { 'message': 'Error on update hero', 'details': str(error) }, 500
def test_create_hero_with_formatted_description(self): params = { 'hero': { 'name': 'SUPERMAN', 'description': ' hero description ', 'universe': 'DC', 'imageUrl': 'https://image.com.br/image.jpg' } } response = self.app.post(path='/heroes', json=params) self.assertEqual(response.status_code, 200) # Obtendo o heroi no banco de dados para conferir a descrição hero_updated = Hero.get_hero(response.get_json()['id']) self.assertEqual(hero_updated.description, 'Hero description')
def test_delete_hero(self): """Test delete hero""" # Criando o heroi hero = self.create_hero('Hero', 'DC') # Enviando a requisição para excluir o heroi response = self.app.delete(path='/hero/{0}'.format(hero.id)) # Resposta da requisição self.assertEqual(response.status_code, 200) # Conferindo a mensagem que voltou self.assertEqual(response.get_json(), {'message': 'Hero deleted'}) # Obtendo o heroi diretamente no banco de dados para conferir se foi # excluido mesmo self.assertIsNone(Hero.get_hero(hero.id))
def get(self): """Get heroes""" try: heroes = Hero.search_heroes(request.args.get('name')) response = { 'heroes': [], } # Vamos percorer os herois e transformar em json for hero in heroes: response['heroes'].append(hero.to_dict()) if heroes: return response['heroes'] return {'message': 'Hero not found'}, 404 except Exception as error: return {'message': 'Bad request, param name is required'}, 400
def test_create_hero_with_name_formatted(self): """Test create hero with uppercase name and blank spaces""" params = { 'hero': { 'name': ' SUPERMAN ', 'description': 'Hero description', 'universe': 'DC', 'imageUrl': 'https://image.com.br/image.jpg' } } response = self.app.post(path='/heroes', json=params) self.assertEqual(response.status_code, 200) # Obtendo o heroi no banco de dados para conferir o nome hero_updated = Hero.get_hero(response.get_json()['id']) self.assertEqual(hero_updated.name, 'Superman')
def get(): """Get top heroes""" try: heroes = Hero.get_top_heroes() heroes_dict = [] for hero in heroes: heroes_dict.append(hero.to_dict()) shuffle(heroes_dict) return {'heroes': heroes_dict[:4]} except Exception as error: return { 'message': 'Error on get top heroes', 'details': str(error) }, 500
def get(self): """Get top heroes""" try: heroes = Hero.get_top_heroes() heroes_dict = [] for hero in heroes: heroes_dict.append(hero.to_dict()) # Falta embaralhar a lista de herois antes de retornar quatro itens random.shuffle(heroes_dict) return {'heroes': heroes_dict[:4]} except Exception as error: return { 'message': 'Error on get top heroes', 'details': str(error) }, 500
def get(self): """Get heroes""" try: heroes = Hero.search_heroes(request.args.get('name')) response = { 'heroes': [], } for hero in heroes: response['heroes'].append(hero.to_dict()) if response['heroes']: return response['heroes'] return {'message': 'Bad request, param name is required'}, 400 except Exception as error: return { 'message': 'Error on get heroes', 'details': str(error) }, 500
def main(): """ parse parameters. The init is done here : - The map object remain the same in text or graphic mode --> instantiated at the begining and once - the hero and the output (text or graphic) mode are also instantiated here (toto is for the film 'toto le heros') """ args = parse_arguments() map = Map(MAP_FILE) if args.text: clear() toto = Hero(map) game_text(map, toto) else: clear() pygame.init() screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGTH)) toto = HeroGraph(map) game_graphic(map, toto, screen)
def start(self): ''' Setting up the elements of the game ''' # We set up all the elements labyrinthe = Map() labyrinthe.load_map_data('map.csv') df = labyrinthe.create_dataframe() labyrinthe.items_random_position() start = list(labyrinthe.start) mcgyver = Hero(int(start[0].position[0] / CELL_SIZE), int(start[0].position[1] / CELL_SIZE), HERO_CELL, 'hero.png') interface.display_map(labyrinthe) interface.display_items(labyrinthe) interface.display_text_zone1() # We bring the hero to life running = True while running: interface.display_hero(mcgyver) interface.pyg_events(mcgyver, labyrinthe)
def test_update_hero(self): """Test update hero""" # Criando o heroi com o nome hero hero = self.create_hero('Hero', 'DC') # Enviando a requisição para atualizar nome do heroi para "Hawkwoman" params = { 'hero': { 'name': 'Hawkwoman', 'description': hero.description, 'universe': hero.universe, 'imageUrl': 'https://gartic.com.br/imgs/mural/ti/tica_/pantera-negra.png' } } response = self.app.post(path='/hero/{0}'.format(hero.id), json=params) # Resposta da requisição self.assertEqual(response.status_code, 200) # Obtendo o heroi atualizado para conferir o novo nome hero_updated = Hero.get_hero(hero.id) self.assertEqual(hero_updated.name, 'Hawkwoman')
def test_get_hero_not_found(self): """Test get hero not found""" hero = Hero.get_hero('ID_TEST') self.assertIsNone(hero)
def test_1(): map = Map("ressource/map01.txt") assert len(map.start) == 1 assert len(map.goal) == 1 toto = Hero(map) toto.position = map.start[0] assert toto.position.getx == 0 assert toto.position.gety == 0 toto.move('left') # outside the map assert toto.position.getx == 0 assert toto.position.gety == 0 toto.move('up') # outside the map assert toto.position.getx == 0 assert toto.position.gety == 0 toto.move('right') # in the wall assert toto.position.getx == 0 assert toto.position.gety == 0 toto.move('down') # OK assert toto.position.getx == 1 # new x assert toto.position.gety == 0 map.items.append(Position(5, 5)) # put an Item in the list len_items = len(map.items) toto.position = Position(4, 5) # put the hero near the item toto.move('down') # move onto the new items print('coucou {}'.format(toto.position)) assert len_items == len( map.items) + 1 # the item has been removed from the list