def client(server_address, local_player): global battle, pokemon_client, pokemon_server, player player = local_player battle = Battle(client = True) pokemon_client = Pokemon.create_pokemon() xml = xml_pokemon.generate(pokemon_client, pokemon_server) response = requests.post('http://' + server_address + ':5000/battle', data = xml, headers={'Content-Type': 'application/xml'}) not_first_round = False while response.status_code == 200: if not_first_round: server_hp = pokemon_server.hp dummy, pokemon_server = xml_pokemon.parse(response.content.decode('utf-8')) print (pokemon_client.name + " inflicted " + str(server_hp - pokemon_server.hp) + " points of damage in " + pokemon_server.name + "!") battle.print_battle_status(pokemon_client, pokemon_server) if battle.battle_ended(pokemon_client, pokemon_server): return client_hp = pokemon_client.hp pokemon_client, dummy = xml_pokemon.parse(response.content.decode('utf-8')) print (pokemon_server.name + " inflicted " + str(client_hp - pokemon_client.hp) + " points of damage in " + pokemon_client.name + "!") battle.print_battle_status(pokemon_client, pokemon_server) if battle.battle_ended(pokemon_client, pokemon_server): return else: pokemon_client, pokemon_server = xml_pokemon.parse(response.content.decode('utf-8')) battle.print_battle_status(pokemon_client, pokemon_server) if player == "user": option = pokemon_client.perform_attack_client() elif player == "ai": option = pokemon_client.perform_attack_client_ai(pokemon_server) xml = xml_pokemon.generate(pokemon_client, pokemon_server) response = requests.post('http://' + server_address + ':5000/battle/attack/' + option, data = xml, headers={'Content-Type': 'application/xml'}) not_first_round = True
def run(self): if not self.canRun(): return False battle = Battle(self.game, 601, self.fleet) spot, enemy = battle.go() Log.i('Enemy fleet: ' + str(enemy)) if (enemy == [1, 1, 14, 14, 14]) or (enemy == []): Log.i('CV detected, retreat') self.game.restart() return True battle.start(5) newShip, hp = battle.chase() battle.quit() Log.i('Battle result:') for ship in self.fleet.ships: Log.i(' %s Lv:%d HP:%d/%d' % (ship.getName(), ship.lv, ship.hp, ship.maxHp)) if newShip is None: Log.i('No ship got') elif newShip.getName() in self.dismantleList or self.game.isDormFull(): Log.i('Dismantle ' + newShip.getName()) newShip.dismantle() else: Log.i('Got ship ' + newShip.getName()) self.fleet.fill() return True
def knight_journey(filename): battle = Battle(filename) result = battle.fightImplementation() return result[0]
def start_battle(self): try: self.poke_cliente = Pokemon(request.data, xml=True) except etree.XMLSyntaxError as e: print('Erro de sintaxe no XML: ', e) abort(422) if len(sys.argv) == 3: poke = Pokemon(sys.argv[2]) elif len(sys.argv) == 2: poke = Pokemon(sys.stdin) self.poke_server = poke self.battle = Battle() self.ai = AI() first = self.battle.get_first(self.poke_server, self.poke_cliente) if first is self.poke_server: choice = self.battle.make_choice(self.poke_server, self.poke_cliente, self.ai) self.battle.attack(self.poke_server, self.poke_cliente, choice) self.battle.all_alive(self.poke_server, self.poke_cliente) xml = self.poke_cliente.to_XML('<battle_state></battle_state>') xml = self.poke_server.to_XML(xml) else: xml = self.poke_server.to_XML(request.data) return xml, 200
def run(self): if not self.fleet.isReady(): return AutoE4.Error self.battle = Battle(self.game, 9916, self.fleet) spot, enemy = self.battle.go() Log.i('Spot: ' + str(spot)) Log.i('Enemy fleet: ' + str(enemy)) if spot != 991602: return AutoE4.Pit self.newShips = [None, None, None] for i in range(3): if i != 0: self.battle.go() self.battle.engage(2) self.newShips[i], hp = self.battle.giveUp() Log.i('Got %s at spot %d' % (self.newShips[i].getName() if self.newShips[i] is not None else 'nothing', i)) Log.i(self.fleet.printHp()) for ship in self.fleet.ships: if ship.isBroken(): self.end() return AutoE4.Broke self.end() return AutoE4.OK
def main(argv): foe = Monster('scyter', 123, 0, 100, 100) ally = Monster('bulbasaur', 1, 0, 100, 100) battle = Battle(foe, ally) att = Attack('splash', 0, 100, False, True) for effect in att.effects(): sys.stdout.write(effect(battle)) sys.stdout.write('\n')
def main(): p1 = Pokemon(client.get_pokemon(3), 50) p2 = Pokemon(client.get_pokemon(6), 50) battle = Battle(p1, p2) battle.make_move(p1.moves[0])
def generate_battle(): timestamp = int(time.time()) board = Board(piece_shape_set_generate()) battle = Battle(timestamp, 20, 5, board) for player_id in range(4): assert battle.try_join_player(timestamp, player_id, {"user_id": player_id}) return battle
def test_battle_process(): start_timestamp = 1510000000 board = Board(piece_shape_set_generate()) battle = Battle(start_timestamp, 5, 2, board) for player_id in range(4): assert battle.try_join_player(start_timestamp, player_id, {"user_id": player_id}) assert battle.try_drop_piece(start_timestamp, 0, 0, Position())
def attack(self, battle_element): at, df, wp, map, pos = battle_element battle = Battle(at, df, wp, df.item[0], map, pos) res = battle.battle() del battle obj = self.person[at.pid] action = self._sequential_move(self.select, self.dst) obj.do(action + CallFunc(self._battle_scene, res) + CallFunc(self.clear_map) + CallFunc(self.take_turn))
def simulate(): print(request.get_json(force=True)) trainer_data = request.get_json(force=True) trainer_teams = [ TrainerAI(trainer['trainer'], trainer['team'], trainer['side'], '', 3) for trainer in trainer_data ] sim_battle = Battle("SINGLE", trainer_teams) run_battle(sim_battle) return
def request(self, messages): data = [x for x in self.battles if self.room in str(x)] battle_tier = re.search("battle-(.+)-(\d+)", self.room).group(1) if len(data) == 0: # new battle self.battles.append(Battle(battle_tier, self.room, self)) print("NEW BATTLE") self.battles[-1].run(messages) else: pass
def start_battle(self, heat, lifelines): # health, attack, trait, speed, weakness, state_of_matter slow_print('Starting battle!') if not heat.get('starting_level', None): heat['starting_level'] = 10 # TODO: maybe only battles need to create enemies enemy1 = Enemy.create_enemy_of_level(heat['starting_level']) enemy2 = Enemy.create_enemy_of_level(heat['starting_level']) battle = Battle(self, [enemy1, enemy2], heat, lifelines) battle.start()
def test_user_leave(): timestamp = get_timestamp() board = Board(piece_shape_set_generate()) battle = Battle(timestamp, 20, 5, board) assert battle.try_join_player(timestamp, 0, {"user_id": 0}) assert battle.try_join_player(timestamp, 1, {"user_id": 1}) assert battle.try_join_player(timestamp, 2, {"user_id": 2}) battle.remove_player(timestamp, 2) assert battle.try_join_player(timestamp, 2, {"user_id": 3}) assert battle.try_join_player(timestamp, 3, {"user_id": 4}) assert battle.started
def battle(self): battle = Battle(self.ph, self.eh) bres = battle.battleLoop() if bres == 0: print("You died...") print("\n\n") self.printGameOver() elif bres == 1: print("You won!!!") elif bres == 2: print("You ran away...") else: print("Battle broken")
def battle(self, defender: Nation, attacker: Nation): battleInfo = "" battleInfo = battleInfo + attacker.name + " has attacked " + defender.name + "!\n" battle = Battle(attacker, defender) battleInfo = battleInfo + defender.name + " lost " + str( battle.outcome[1]) + " soldiers\n" battleInfo = battleInfo + attacker.name + " lost " + str( battle.outcome[0]) + " soldiers\n" return battleInfo
def __init__(self): self.map = map_of_game.Game_Map() self.view = View() self.hero = character.Hero() self.boss = character.Boss() self.skeltons = character.Skeleton() self.view.display_map(self.map.board) self.boss_position() self.skeletons_position() self.battle = Battle(self.hero, self.boss) self.input_event() self.view.display_hero_down(72 + self.hero.x_pos * self.view.size, 72 + self.hero.y_pos * self.view.size) self.view.root.mainloop()
def knight_journey_to_file(filename, case): battle = Battle(filename) result = battle.fightImplementation() print("Fighter Elrond’s Code : " + result[0]) print("Fighter HP : " + str(result[1])) print("------------------------------------------------") if result[0] == "": appendTextFile("./result.txt", str(case) + " " + "LOSE" + " " + str(result[1])) else: appendTextFile("./result.txt", str(case) + " " + str(result[0]) + " " + str(result[1]))
def test___conduct_combat(self): t1 = Army() t2 = Army() battle = Battle() formation = 0 # Test if combat is conducted correctly and returns appropriate result for empty p1 army and all Archer p2 army # Assumes __assign_army is working correctly t1._Army__assign_army("", 0, 0, 0, formation) t2._Army__assign_army("", 0, 10, 0, formation) try: self.assertTrue( battle._Battle__conduct_combat(t1, t2, formation) == 2, "Gladiatorial 0,0,0 0,10,0 failed") except AssertionError as e: self.verificationErrors.append(str(e))
def main(): player = Player() printIntro() choice = 'yes' no = ['no', 'n'] yes = ['yes', 'y', 'ye'] while player.getPurse() > 0 and choice not in no: print "You have", player.getPurse(), "in your pouch.\n" battle = Battle() print "\nThe next battle is between %s and %s.\n" % ( battle.warrior1.getName(), battle.warrior2.getName()) announceWarriors(battle.warrior1, battle.odds1, battle.warrior2, battle.odds2) print "\nDo you want to bet?\n\n" player.getChoice(battle.warrior1, battle.warrior2) winner, odds = battle.battle() if winner == player.getPick(): player.updatePurse("win", player.getBet(), odds) else: player.updatePurse("lose", player.getBet(), odds) print "\nWould you like to bet on the next battle?\n" while True: try: choice = string.lower(str(raw_input(">> "))) if choice in yes: break elif choice in no: choice = 'no' break else: print "\nPlease choose yes or no.\n" continue except ValueError: print "\nPlease choose yes or no.\n" continue print "\nThank you so much for playing!\n" if player.getPurse() > 1: print "\nYou leave the Colosseum with %d coins in your purse.\n" % player.getPurse( ) elif player.getPurse() == 1: print "\nYou leave the Colosseum with one coin, not even another to rub it against.\n" else: print "\nYou're leaving dead broke!\n"
def pokemon_battle(team1, team2): team1 = {"trainer": None, "pokemon": team1} team2 = {"trainer": "The foe", "pokemon": team2} trainer1 = Trainer(team1.get("trainer")) for pkm in team1.get("pokemon"): trainer1.addPokemon(Pokemon(pid=pkm)) trainer2 = Trainer(team2.get("trainer")) for pkm in team2.get("pokemon"): trainer2.addPokemon(Pokemon(pid=pkm)) print(trainer1.nameOrYou() + " took out " + " ".join([pokemon.name for pokemon in trainer1.team])) print(trainer2.nameOrYou() + " took out " + " ".join([pokemon.name for pokemon in trainer2.team])) print("\n") battle = Battle(trainer1, trainer2) return battle.start()
def main(): # obtener los datos de los pokemons pokemon_1_name = input("Indica el nombre del primer pokemon: ") pokemon_1_attack = get_correct_attack_value( "Indica la potencia de ataque del primer pokemon. Valor de 1 a 100. :") pokemon_2_name = input("Indica el nombre del segundo pokemon :") pokemon_2_attack = get_correct_attack_value( "Indica la potencia de ataque del segundo pokemon. Valor de 1 a 100. :" ) # generar aleatoriamente un valor 0 o 1 r_turn = random.randint(0, 1) # asignar al primer pokemon el valor de turno aleatorio y al segundo el contrario pokemon_1 = Pokemon(pokemon_1_name, pokemon_1_attack, r_turn) pokemon_2 = Pokemon(pokemon_2_name, pokemon_2_attack, int(not r_turn)) b = Battle(pokemon_1, pokemon_2) b.battle()
def battle_start(): global battle, pokemon_client, pokemon_server, player if battle == None: battle = Battle(server = True) else: abort(403) xml = request.data.decode('utf-8') pokemon_client, dummy = xml_pokemon.parse(xml) pokemon_server = Pokemon.create_pokemon() battle.print_battle_status(pokemon_client, pokemon_server) if pokemon_server.speed > pokemon_client.speed: if player == "user": option = pokemon_server.perform_attack_server() elif player == "ai": option = pokemon_server.perform_attack_server_ai(pokemon_client) pokemon_server.inflict_and_announce_damage_server(pokemon_client, option) battle.print_battle_status(pokemon_client, pokemon_server) if battle.battle_ended(pokemon_client, pokemon_server): server_shutdown() xml = xml_pokemon.generate(pokemon_client, pokemon_server) return xml
def operate(self, len_game=10000, p_debug=False): for i in range(self.n_agents): for j in range(self.n_agents): if i == j: self.score_matrix[i, i] = 0 continue elif self.score_matrix[i, j] < 0 and self.score_matrix[j, i] < 0: agent1 = self.agents[self.agent_keys[i]] agent2 = self.agents[self.agent_keys[j]] battle = Battle(agent1, agent2, len_game=len_game) scores = battle.operate() self.score_matrix[i, j] = scores[0] self.score_matrix[j, i] = scores[1] if p_debug: print(self.agent_keys[i], "vs", self.agent_keys[j], ":", scores) else: continue
def randomEncount(self): rnd = random.random() if rnd < 0.2: battle = Battle(self.userID) text = battle.enemy.name + "が現れた!" dbinfo = config.getInfoToConnectDB() self.connection = pymysql.connect( host=dbinfo['host'], user=dbinfo['user_name'], password=dbinfo['password'], db=dbinfo['db_name'], charset='utf8', cursorclass=pymysql.cursors.DictCursor) with self.connection.cursor() as cursor: cursor.execute("SELECT * FROM ENEMY WHERE id = %s", (battle.enemy.enemyId)) enemyInfo = cursor.fetchone() imageURI = "https://nozawa-linebot.tk/" + enemyInfo['imagePath'] return True, {"img": imageURI, "text": text} return False, {}
def __init__(self,map_name): pygame.init() self.core = Core() self.mode = Event_Handler() self.file = 'ingame_temp'#заміна self.file в Core.py #self.map_type - треба замінити в Core.py #self.x_coord_start self.x_coord_end - замінити в Core.py self.battle = Battle('1') self.resources = Resources() self.graphical_logic = Graphical_logic() self.w_event = Events() self.minimap_x =0 self.minimap_y =0 self.count = 0 self.days = 0 self.fraction = 1 # першими ходять червоні self.map_name = map_name self.stage = 0 self.save_load_name = '' self.fractions = [[1, 1, 0, 0, 3, 1],[2, 1, 0, 0, 0, 0]]
def test__conduct_combat(self): t1 = Army() t2 = Army() battle = Battle() formation = 1 # Test if combat is conducted correctly and if it returns # appropriate result for all Archer p1 army and empty p2 army # Assumes __assign_army is working correctly t1._Army__assign_army("", 0, 10, 0, formation) t2._Army__assign_army("", 0, 0, 0, formation) try: self.assertTrue( battle._Battle__conduct_combat(t1, t2, formation) == 1, "Fairer 0,10,0 0,0,0 failed") except AssertionError as e: self.verificationErrors.append(str(e)) # Tests combat is conducted correctly and if it # returns appropriate result for 1 Soldier p1 army and 1 Archer p2 army # Assumes __assign_army is working correctly t1._Army__assign_army("", 1, 0, 0, formation) t2._Army__assign_army("", 0, 1, 0, formation) try: self.assertTrue( battle._Battle__conduct_combat(t1, t2, formation) == 2, "Fairer 1,0,0 0,1,0 failed") except AssertionError as e: self.verificationErrors.append(str(e)) try: self.assertEqual(str(t1.force), "", msg="Army 1 wrong for Fairer 1,0,0 0,1,0") except AssertionError as e: self.verificationErrors.append(str(e)) try: self.assertEqual(str(t2.force), "Archer's life = 1 and experience = 1", msg="Army 2 wrong for Fairer 1,0,0 0") except AssertionError as e: self.verificationErrors.append(str(e))
async def create_battle(ctx): name = " ".join(ctx.message.content.split()[1:]) if len(name) == 0: await ctx.message.channel.send("Please enter a name") return try: player = get_player(ctx) if not player.in_battle(): battle = Battle(name) await player.join_battle(battle) battles[battle.get_name() + str(ctx.message.channel.guild.id)] = battle await ctx.message.channel.send( "battle \"{}\" created successfully".format(name)) else: await ctx.message.channel.send( "You are currently in a battle. Please finish current battle or " "enter !leave_battle to continue") except KeyError as e: await ctx.message.channel.send("No character exists for {}".format( ctx.message.author))
def step(self, text): if self.player is not None: if self.player.state == "BATTLE": battle = Battle(self.player.userId) reply = battle.battle() if battle.isFinish == True: world = World(self.player.userId) imageURI = world.getInitMap() reply['battlefinished'] = imageURI return reply elif self.player.state == "WORLD": world = World(self.player.userId) imageURI = world.move(text) encount, enemyInfo = world.randomEncount() if encount: self.player.state = "BATTLE" return { "img": [imageURI, enemyInfo["img"]], "text": [enemyInfo["text"]] } return {"worldImg": [imageURI]} else: return {"text": ["still not implemented"]}
def __init__(self): pyxel.init(128, 128, caption="WHAT THE ACTUALLY F**K", fps=25) try: # load files in cx_freeze pyxel.load( os.path.join( os.path.dirname(__file__)[:-16], 'my_resource.pyxel')) file = open( os.path.join(os.path.dirname(__file__)[:-16], 'items.txt')) for line in file: exec(f'self.item_database.append({line})') file.close() except FileNotFoundError: # load files in python pyxel.load( os.path.join(os.path.dirname(__file__), 'my_resource.pyxel')) file = open(os.path.join(os.path.dirname(__file__), 'items.txt')) for line in file: exec(f'self.item_database.append({line})') file.close() self.player_damage = 4 self.player_hp = 10 pyxel.mouse(visible=True) self.battle = Battle() self.menu_opened = False self.player_direction = 0 self.player_animation_frame = 1 self.player_animation_frame_counter = 0 self.x = 0 self.y = 0 self.sx = 56 self.sy = 48 self.level = Level1() self.battle_init = False # init inventory self.inventory = [] # init game app pyxel.run(self.update, self.draw)