コード例 #1
0
ファイル: screens.py プロジェクト: ntoll/crawlr
 def __init__(self, prevstate):
     Screen.__init__(self)
     Battle.__init__(self, prevstate)
     text1 = Font("menu", 24, (255, 0, 0), "Battle Screen Goes Here")
     text2 = Font("menu", 16, (255, 255, 255), "Press 'Esc' to go back to the game.")
     self.add([text1, text2])
     print "init battle"
     sounds.sounds.SWORD.play()
コード例 #2
0
ファイル: stage_select.py プロジェクト: halcat0x15a/nsg
 def action(self, controller):
     pos = controller.pos()
     for i, bounds in enumerate(WORLDS_BOUNDS):
         if controller.button_a and scene.contains(bounds, pos):
             self.client.send(i)
             s = Battle(self.client, self.player_id, i)
             s.server = self.server
             return s
     return self
コード例 #3
0
ファイル: army.py プロジェクト: matteli/histemul
    def update(self, date):
        if self.way and self.next_province != self.way[-1]: #change way since last update
            self.next_province = self.way[-1]
            self.time_walking = 0

        if self.time_walking >= self.location.size: #enter a new province
            self.time_walking -= self.location.size
            province = self.next_province
            self.location = province
            self.way.pop()
            if self.way:
                self.next_province = self.way[-1]
            else:
                self.next_province = None
                self.attitude = 'normal'

            #when enter a new province, look if there is enemy or already a battle
            person = self.for_the
            battle = province.battle

            if not battle:
                war = None
                enemies = []
                for army_in_province in province.armies:
                    if not war:
                        war = person.in_war_against(army_in_province.for_the)['war']
                        enemies.append(army_in_province)
                    else:
                        w = person.in_war_against(army_in_province.for_the)[0]['war']
                        if w == war:
                            enemies.append(army_in_province)
                if enemies: #enemy so battle
                    self.stop()
                    Battle.new(war, province, [self], enemies)

            else:
                war = battle.war
                if person in war.aggressors:
                    self.stop()
                    battle.add_aggressor(self)
                if person in war.defenders:
                    self.stop()
                    battle.add_defender(self)

        if self.next_province:
            self.time_walking += 500 * self.location.land.walkable
        else:
            self.time_walking = 0

        #morale
        if self.attitude == 'normal':
            if self.morale < 95:
                self.morale += 5
            else:
                self.morale = 100
        
        self.save()
コード例 #4
0
ファイル: connection.py プロジェクト: hirohaya/huemon
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
コード例 #5
0
    def execute(self):
        from battle import Battle;
        battle = self.black_board.get("battle");
        is_attack = self.black_board.get("side");
        target_list = [];
        if is_attack:
            target_list = list(Battle.get_all_alive(battle.defenders_list));
        else:
            target_list = list(Battle.get_all_alive(battle.attackers_list));

        target = self.choose_target(target_list);
        battle.add_event(NormalAttackEvent(self.black_board.get("self"), target, battle));
コード例 #6
0
ファイル: test.py プロジェクト: jacksontcollier/Advent_Code
    def test_one(self):
        hero = Fighter("Hero", 8)
        hero.set_attack(5)
        hero.set_armor(5)

        boss = Fighter("Boss", 12)
        boss.set_attack(7)
        boss.set_armor(2)

        battle = Battle(hero, boss)
        battle.start()
        expected = hero
        actual = battle.get_winner()
        self.assertEqual(expected, actual)
コード例 #7
0
ファイル: AICombat.py プロジェクト: uclaacm/ai-combat
class Game(object):

    """
    Constructor for Game. Initializes pygame and sets up the window
    """
    def __init__(self):
        pygame.init()

        width = 800
        height = 600
        self.screen = pygame.display.set_mode((width, height))
        pygame.display.set_caption("AI Combat")
        self.clock = pygame.time.Clock()
        # For now, start directly in Battle mode
        # Other modes in the future may include menu, settings, splash, etc.
        self.battle = Battle()
        self.game_tick = 20

    """
    Starts the game by entering into the infinite game loop
    """
    def start(self):

        elapsed = 0
        while 1:
            # Sleep in such a way that the game does not exceed 60 FPS
            # (This value is completely arbitrary)
            elapsed += self.clock.tick(60)

            while elapsed >= self.game_tick:
                # Event processing
                events = []
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        return
                    events.append(event)

                # Update battle state
                self.battle.update(events, self.game_tick)
                elapsed -= self.game_tick

            # Paint stuff (does not actually paint until you call
            # pygame.display.update)
            # The list of rects returned by the draw tells pygame.display
            # which parts to actually draw
            rects = self.battle.draw(self.screen)

            # Paint the screen
            pygame.display.update(rects)
コード例 #8
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
コード例 #9
0
ファイル: auto25.py プロジェクト: ninggeningge/jn-blacktech
    def run(self):
        if not self.fleet.isReady():
            return Auto25.Error

        self.battle = Battle(self.game, 205, self.fleet)
        spot, enemy = self.battle.go()
        Log.i('Spot: ' + str(spot))
        Log.i('Enemy fleet: ' + str(enemy))
        # if spot != 991602:
        #     return AutoE3.Pit

        self.newShips = [ None, None, None ,None,None]

        for i in range(5):
            if i != 0:
                spot, enemy = self.battle.go()
                Log.i('Spot: ' + str(spot))
                Log.i('Enemy fleet: ' + str(enemy))
                if i == 2:
                    if spot != 20504:
                        return Auto25.Pit
            self.battle.start(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.isBadlyBroken():
                    self.end()
                    return Auto25.Broke
        self.end()
        return Auto25.OK
コード例 #10
0
ファイル: autoe4.py プロジェクト: cherryunix/jn-blacktech
    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
コード例 #11
0
ファイル: AICombat.py プロジェクト: colinfong/AICombat
    def __init__(self):
        pygame.init()

        width = 800
        height = 600
        self.screen = pygame.display.set_mode((width, height))
        pygame.display.set_caption("AI Combat")
        self.clock = pygame.time.Clock()
        self.battle = Battle()
コード例 #12
0
ファイル: proto.py プロジェクト: skishore/proto
class TestGame(object):
  def __init__(self):
    self.screen = pygame.display.set_mode(screen_size)
    self.key_repeater = self.construct_key_repeater()
    self.battle = Battle()

  @staticmethod
  def construct_key_repeater():
    return KeyRepeater(
      one_time_keys=(
        pygame.K_ESCAPE,
        pygame.K_s,
        pygame.K_d,
      ),
      repeated_keys=(
        pygame.K_UP,
        pygame.K_RIGHT,
        pygame.K_DOWN,
        pygame.K_LEFT,
      ),
      pause=framerate/4,
      repeat=framerate/8,
    )

  def game_loop(self):
    while True:
      if self.handle_events():
        self.draw()
      time.sleep(delay)

  def handle_events(self):
    for event in pygame.event.get():
      if event.type == pygame.QUIT:
        sys.exit()
      self.key_repeater.handle_event(event)
    keys = self.key_repeater.query()
    if pygame.K_ESCAPE in keys:
      sys.exit()
    return self.battle.transition(keys)

  def draw(self):
    self.battle.draw(self.screen)
    pygame.display.flip()
コード例 #13
0
ファイル: gladiator.py プロジェクト: synertia/The-Arena
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"
コード例 #14
0
ファイル: AICombat.py プロジェクト: uclaacm/ai-combat
    def __init__(self):
        pygame.init()

        width = 800
        height = 600
        self.screen = pygame.display.set_mode((width, height))
        pygame.display.set_caption("AI Combat")
        self.clock = pygame.time.Clock()
        # For now, start directly in Battle mode
        # Other modes in the future may include menu, settings, splash, etc.
        self.battle = Battle()
        self.game_tick = 20
コード例 #15
0
ファイル: AICombat.py プロジェクト: colinfong/AICombat
class Game():

    """
    Constructor for Game. Initializes pygame and sets up the window
    """
    def __init__(self):
        pygame.init()

        width = 800
        height = 600
        self.screen = pygame.display.set_mode((width, height))
        pygame.display.set_caption("AI Combat")
        self.clock = pygame.time.Clock()
        self.battle = Battle()

    """
    Starts the game by entering into the infinite game loop
    """
    def start(self):
        while 1:
            # Sleep in such a way that the game does not exceed 30 FPS
            elapsed = self.clock.tick(30)

            # Event processing
            events = []
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    return
                events.append(event)

            # Update battle state
            self.battle.update(events, elapsed)
            
            # Paint stuff (does not actually paint until you call
            # pygame.display.flip)
            self.screen.fill((0,0,0))
            self.battle.draw(self.screen)
            
            # Paint the screen
            pygame.display.flip()
コード例 #16
0
ファイル: Window.py プロジェクト: iamorlov/War-for-cookies
 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]]
コード例 #17
0
ファイル: connection.py プロジェクト: hirohaya/huemon
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
コード例 #18
0
ファイル: initgame.py プロジェクト: kehlerr/airpong
def create_battle():
    window = create_window()
    battle = Battle(window)
    return battle
コード例 #19
0
ファイル: hero_game.py プロジェクト: JMcWhorter150/hero_game
from sayan import Sayan
from shadow import Shadow
from store import Store
from thief import Thief
from wizard import Wizard
from zombie import Zombie
from mimic import Mimic
hero = Hero('Oakley')
enemies = [
    Goblin('Bob'),
    Wizard('Jethro'),
    Medic('Mercy'),
    Thief('Barry'),
    Mimic('Harry'),
    Zombie('Rick'),
    Shadow('Matt'),
    Sayan('Goku')
]
# enemies = [Thief('Barry')] Goblin('Bob'), Wizard('Jethro'), Medic('Mercy'), Thief('Barry'), Zombie('Rick'), Shadow('Matt'), Sayan('Goku'),
battle_engine = Battle()
shopping_engine = Store()

for enemy in enemies:
    hero_won = battle_engine.do_battle(hero, enemy)
    if not hero_won:
        print("YOU LOSE!")
        exit(0)
    shopping_engine.do_shopping(hero, enemy)

print("YOU WIN!")
コード例 #20
0
    async def battle(self, ctx, *, args=""):
        '''Begin a battle against another player. Can specify size of game as well.'''
        if not self.cached:
            await ctx.send("Caching things on first run")
            await self.set_local_cache()

        player = str(ctx.author.id)
        if not player in self.battles:
            args = args.split()
            if len(args) == 0:
                args = [""]
            enemy = await self.at_to_id(args[0].strip())
            if len(args) > 1:
                cap = int(args[1])
            else:
                cap = 10
            if not enemy in self.trading:
                await ctx.send(
                    "Player not recognised!\nFor now, starting a testing battle"
                )
                self.battles[player] = Battle(
                    {
                        player: [],
                        "test": self.capelist[:2]
                    },
                    self.battle_stats,
                    cap=cap,
                    channel=ctx.channel)
                self.battles[player].teams["test"].ready = True
                self.battles[player].teams["test"].move = "Defend"
                return
            else:
                await ctx.send(
                    "Starting a battle. Both go add your cards as fighting capes in PMs using `%battle add capename, capename, capename`!"
                )
                self.battles[player] = Battle({
                    player: [],
                    enemy: []
                },
                                              self.battle_stats,
                                              cap=cap,
                                              channel=ctx.channel)
                self.battles[enemy] = self.battles[player]
        elif not self.battles[player].started:
            if args.split()[0] == "add":
                splittup = args[4:].split(",")
                capes = []
                for i in splittup:
                    capes += [i.strip()]
                if await self.has_cards(player, capes):
                    for card in capes:
                        cape = await self.get_cape(card)
                        self.trading[player].remove(cape)
                        if not self.battles[player].teams[player].add_cape(
                                cape):
                            await ctx.send(
                                f"Adding {card} exceeds the quota for the team"
                            )
                else:
                    await ctx.send(f"You don't have all of those cards!")

                await ctx.send(
                    self.battles[player].teams[player].info_string())
            elif args.split()[0].lower() == "quit" or args.split()[0].lower(
            ) == "cancel":
                # Quitting before the game starts!
                await ctx.send("Quitting the game")
                for i in self.battles[player].teams:
                    if i != player:
                        enemy = i
                await self.battles[player].channel.send(
                    f"<@{enemy}>, <@{player}> has cancelled the battle!")
                for bc in self.battles[player].teams[player].team:
                    self.trading[player] += [bc.cape]
                del self.battles[player]
                if enemy in self.battles:
                    for bc in self.battles[enemy].teams[enemy].team:
                        self.trading[enemy] += [bc.cape]
                    del self.battles[enemy]
            elif args.split()[0].lower() == "start" or args.split()[0].lower(
            ) == "ready":
                p_team = self.battles[player].teams[player]
                if p_team.cap is not None and p_team.quota(
                ) < p_team.cap and not p_team.forcing:
                    p_team.forcing = True
                    await ctx.send(
                        "You haven't filled your team to the cap, are you sure you want to start? Resend the command if so!"
                    )
                    return
                p_team.ready = True
                if self.battles[player].ready():
                    self.battles[player].started = True
                    await ctx.send("Other player is ready. Game starting!")
                    await self.start_battle(self.battles[player])
                else:
                    await ctx.send("Waiting for other player!")
        elif self.battles[player].started:
            strategy = args.split()[0].lower()
            p_team = self.battles[player].teams[player]
            if strategy == "attack":
                p_team.move = "Attack"
            elif strategy == "defend":
                p_team.move = "Defend"
            elif strategy == "ambush":
                p_team.move = "Ambush"
            elif strategy == "flee":
                p_team.move = "Flee"
            elif strategy == "stats":
                await ctx.send(
                    self.battles[player].teams[player].info_string())
                return
            else:
                await ctx.send("Strategy is not recognised")
                return

            if self.battles[player].do_turn():
                await ctx.send("Starting the new round!")
                await self.do_battle_round(self.battles[player])
            else:
                await ctx.send("Waiting for other player to decide strategy")
コード例 #21
0
ファイル: game.py プロジェクト: dguenther/taciturn
 def play(self):
     battle = Battle(self, self.units)
     battle.start()
コード例 #22
0
from battle import Battle
import monsters
import heroes

if __name__ == "__main__":

    #creates a battle
    battle = Battle()

    #create enemies
    battle.add_enemy(monsters.BasicMonster("evil bert", 10, 20))
    battle.add_enemy(monsters.BasicMonster("evil ernie", 5, 8))
    battle.add_enemy(monsters.BasicMonster("chicken", 5, 8))
    battle.add_enemy(monsters.Ant("ant", 1, 1))
    battle.add_enemy(monsters.SuperAnt("super ant", 1, 1))

    #create heroes
    battle.add_hero(heroes.Coward("super grover", 21, 28))
    battle.add_hero(heroes.Healer("big bird", 35, 38))

    #start battle
    while len(battle.heroes) > 0 and len(battle.enemies) > 0:
        battle.next_battle_round()

    print "\n===== THE BATTLE IS OVER ===="
コード例 #23
0
class App:
    item_database = []
    paused = False

    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)

    def update(self):
        pyxel.mouse(True)
        Monster.paused = App.paused  # sending vars to "monster.py"
        Monster.player_x = self.sx
        Monster.player_y = self.sy
        if Monster.battle:
            if not self.battle_init:
                self.battle.monster_id = Monster.monster_id
                self.battle.player_hp = self.player_hp
                self.battle.player_dmg = self.player_damage
                self.battle.monster_hp = Monster.monster_database[
                    self.battle.monster_id][7]
                self.battle.monster_dmg = Monster.monster_database[
                    self.battle.monster_id][7]
                self.battle_init = True
                print('init')
            App.paused = True
        elif not Monster.battle and not self.menu_opened:
            if self.battle_init:
                self.player_hp = self.battle.player_hp
            App.paused = False
            self.battle_init = False
        # CONTROLS #
        if pyxel.btnp(pyxel.KEY_Q):
            pyxel.quit()

        if not App.paused:
            if pyxel.btn(pyxel.KEY_LEFT):
                self.player_direction = 1
                if self.is_empty(self.sx, self.sy + 1) and self.is_empty(
                        self.sx, self.sy + 6):
                    self.sx = self.sx - 1
            if pyxel.btn(pyxel.KEY_RIGHT):
                self.player_direction = 0
                if self.is_empty(self.sx + 7, self.sy + 1) and self.is_empty(
                        self.sx + 7, self.sy + 6):
                    self.sx = self.sx + 1
            if pyxel.btn(pyxel.KEY_UP):
                self.player_direction = 2
                if self.is_empty(self.sx + 1, self.sy) and self.is_empty(
                        self.sx + 6, self.sy):
                    self.sy = self.sy - 1
            if pyxel.btn(pyxel.KEY_DOWN):
                self.player_direction = 3
                if self.is_empty(self.sx + 1, self.sy + 8) and self.is_empty(
                        self.sx + 6, self.sy + 8):
                    self.sy = self.sy + 1

        if pyxel.btnp(pyxel.KEY_E):
            if App.paused and not self.menu_opened:
                pass
            else:
                if not self.menu_opened:
                    App.paused = True
                    self.menu_opened = True
                else:
                    App.paused = False
                    self.menu_opened = False

        elif pyxel.btnp(pyxel.KEY_F):
            for item in self.item_database:
                if self.get_tile() == item[1]:
                    pyxel.tilemap(0).set((self.sx + 4) // 8,
                                         (self.sy + 4) // 8,
                                         0)  # clear that tile
                    self.inventory.append(self.item_database.index(item))

    def draw(self):
        pyxel.cls(0)
        print(self.player_hp)
        self.level.draw_level()
        self.mouse_button()
        if Monster.battle:
            self.battle.draw()
        if not App.paused:
            self.draw_player()
        elif self.menu_opened:
            self.draw_menu()

    def draw_menu(self):
        pyxel.bltm(0, 0, 0, 0, 16, 16, 16, 0)
        pyxel.text(14, 16, 'INVENTORY:', 9)  # text
        for i in range(9):
            try:
                pyxel.text(14, (i * 10) + 26,
                           self.item_database[self.inventory[i]][0], 15)
            except IndexError:
                break

    def mouse_button(self):
        if pyxel.btn(pyxel.MOUSE_LEFT_BUTTON):
            self.sx = pyxel.mouse_x
            self.sy = pyxel.mouse_y
            tx = pyxel.mouse_x // 8
            ty = pyxel.mouse_y // 8
            self.x = tx
            self.y = ty
            print(tx * 8, ty * 8, pyxel.tilemap(0).get(tx, ty))

    def draw_player(self):
        going = [
            pyxel.btn(pyxel.KEY_LEFT),
            pyxel.btn(pyxel.KEY_RIGHT),
            pyxel.btn(pyxel.KEY_UP),
            pyxel.btn(pyxel.KEY_DOWN)
        ]
        if any(going):
            self.player_cycle_animation()
        pyxel.blt(self.sx, self.sy, 0, self.player_direction * 8,
                  self.player_animation_frame * 8, 8, 8, 0)

    def is_empty(self, x, y):
        if pyxel.tilemap(0).get(
                x // 8,
                y // 8) == 0 or pyxel.tilemap(0).get(x // 8, y // 8) >= 32:
            return True
        else:
            return False

    def get_tile(self):
        return pyxel.tilemap(0).get((self.sx + 4) // 8, (self.sy + 4) // 8)

    def player_cycle_animation(self):
        if self.player_animation_frame_counter < 4:
            self.player_animation_frame_counter += 1
        else:
            if self.player_animation_frame == 1:
                self.player_animation_frame = 2
                self.player_animation_frame_counter = 0
            else:
                self.player_animation_frame = 1
                self.player_animation_frame_counter = 0
コード例 #24
0
 def play(self):
     battle = Battle(self.units)
     battle.start()
コード例 #25
0
 def main():
     A = Battle()
     A.battle()
コード例 #26
0
ファイル: main.py プロジェクト: stonecoldgames/anymon
from classes import Prints, Human
from battle import Battle, IQcheck, STRcheck, CHAcheck
import random

# initializing variables
p1damage = 0
p2damage = 0
ross = Human("Ross", 100,1,100,50,50)
carlos = Human("Carlos", 100,1,75,50,75)
out = Prints(False)
out.line = carlos.description()
out.delay_print()
out.line = ross.description()
out.delay_print()




Battle(ross,carlos)


out.line = carlos.description()
out.delay_print()
out.line = ross.description()
out.delay_print()
コード例 #27
0
ファイル: play.py プロジェクト: maorlv/pokemon-battle-tower
    def startBattle(self):
        self.battle_num += 1
        self.current_battle = Battle(self.battle_num, self.max_battles)

        return self.current_battle
コード例 #28
0
def performAttackOnUnit(battle, target_unit):
    # perform an attack on the given target BattleUnit
    turn_unit = battle.getTurnUnit()
    if turn_unit is None or target_unit is None\
            or turn_unit.isDestroyed() or target_unit.isDestroyed():
        # TODO: make sure it is a player unit's turn
        return 0

    src_cell = turn_unit.col, turn_unit.row
    dest_cell = target_unit.col, target_unit.row

    # minimum travel time to target used to determine when to show the damage floater
    min_travel_time = 0
    # maximum travel time to target used to determine when all animations are finished
    max_travel_time = 0

    # cell distance used to determine which range of weapons will fire
    cell_distance = Battle.getCellDistance(src_cell, dest_cell)
    target_range = Battle.getDistanceRange(cell_distance)
    print(target_range + ": " + str(src_cell) + " -> " + str(dest_cell) +
          " = " + str(cell_distance))

    # TODO: introduce dynamic damage (optional?)
    attack_damage = int(getattr(turn_unit, target_range))

    # apply damage to model before animating
    attack_remainder = target_unit.applyDamage(attack_damage)

    # determine actual target point based on the target unit sprite size
    target_sprite = target_unit.getSprite()
    real_x = (dest_cell[0] * Board.TILE_SIZE) + Board.TILE_SIZE // 2
    real_y = (dest_cell[1] *
              Board.TILE_SIZE) + (2 * target_sprite.get_height() // 3)

    for weaponMap in turn_unit.mech.weapons:
        for weapon in weaponMap.iterkeys():

            if not weapon.inRange(cell_distance):
                continue

            weapon_data = weaponMap[weapon]

            # get sound channel to use just for this weapon
            weapon_channel = pygame.mixer.find_channel()
            if weapon_channel is None:
                weapon_channel = pygame.mixer.Channel(0)

            weapon_offset = weapon_data.get('offset', [0, 0])
            weapon_x = turn_unit.sprite.position[0] + weapon_offset[0]
            weapon_y = turn_unit.sprite.position[1] + weapon_offset[1]

            weapon_color = weapon.get_color()

            if weapon.isPPC():
                # fire test ppcs
                ppc = Meteor()
                ppc.size = 10
                ppc.speed = 20
                ppc.gravity = Point2(0, 0)
                # TODO: offer decreased particle emission rate to improve performance
                ppc.emission_rate = 100
                ppc.life = 0.5
                ppc.life_var = 0.1

                ppc.position = weapon_x, weapon_y
                battle.board.add(ppc, z=1000)

                target_x = real_x + random_offset()
                target_y = real_y + random_offset()
                target_pos = target_x, target_y

                # figure out the duration based on speed and distance
                ppc_speed = weapon.get_speed()  # pixels per second
                distance = Point2(ppc.x,
                                  ppc.y).distance(Point2(target_x, target_y))
                ppc_t = distance / ppc_speed

                ppc_sound = Resources.ppc_sound
                weapon_channel.play(ppc_sound)

                action = Delay(0.5) + MoveTo((target_x, target_y), duration=ppc_t) \
                         + CallFunc(impact_ppc, ppc) \
                         + Delay(0.5) + CallFunc(ppc.kill) \
                         + Delay(ppc_sound.get_length()) \
                         + CallFunc(weapon_channel.stop)

                ppc.do(action)

                travel_time = 0.5 + ppc_t
                if min_travel_time == 0 or min_travel_time > travel_time:
                    min_travel_time = travel_time

                if travel_time > max_travel_time:
                    max_travel_time = travel_time

            elif weapon.isFlamer():
                # fire test flamer
                flamer = Fire()

                flamer.size = 25
                flamer.speed = 300
                flamer.gravity = Point2(0, 0)
                # TODO: offer decreased particle emission rate to improve performance
                flamer.emission_rate = 100

                dx = real_x - weapon_x
                dy = real_y - weapon_y
                rads = atan2(-dy, dx)
                rads %= 2 * pi
                angle = degrees(rads) + 90

                flamer.rotation = angle
                flamer.angle_var = 5
                flamer.pos_var = Point2(5, 5)

                flamer.position = weapon_x, weapon_y
                battle.board.add(flamer, z=1000)

                target_x = real_x + random_offset()
                target_y = real_y + random_offset()
                target_pos = target_x, target_y

                # figure out the duration based on speed and distance
                flamer_speed = weapon.get_speed()  # pixels per second
                distance = Point2(flamer.x, flamer.y).distance(
                    Point2(target_x, target_y))
                flamer_t = 1

                flamer.life = distance / flamer_speed
                flamer.life_var = 0

                flamer_sound = Resources.flamer_sound
                weapon_channel.play(flamer_sound)

                action = Delay(flamer_t) \
                         + CallFunc(impact_flamer, flamer) \
                         + CallFunc(weapon_channel.fadeout, 750) \
                         + Delay(flamer_t) + CallFunc(flamer.kill) \
                         + CallFunc(weapon_channel.stop)

                flamer.do(action)

                travel_time = flamer_t
                if min_travel_time == 0 or min_travel_time > travel_time:
                    min_travel_time = travel_time

                if travel_time > max_travel_time:
                    max_travel_time = travel_time

            elif weapon.isLaser():
                # fire test laser
                las_life = 1.0
                las_size = (1, 1, 1)
                if weapon.isShort():
                    las_size = (2, 1, 0.5)
                    las_life = 0.5
                elif weapon.isMedium():
                    las_size = (3, 2, 1)
                    las_life = 0.75
                elif weapon.isLong():
                    las_size = (6, 4, 2)
                    las_life = 1.0

                target_x = real_x + random_offset()
                target_y = real_y + random_offset()
                target_pos = target_x, target_y

                las_outer = gl.SingleLine(
                    (weapon_x, weapon_y), (target_x, target_y),
                    width=las_size[0],
                    color=(weapon_color[0], weapon_color[1], weapon_color[2],
                           50))
                las_middle = gl.SingleLine(
                    (weapon_x, weapon_y), (target_x, target_y),
                    width=las_size[1],
                    color=(weapon_color[0], weapon_color[1], weapon_color[2],
                           125))
                las_inner = gl.SingleLine(
                    (weapon_x, weapon_y), (target_x, target_y),
                    width=las_size[2],
                    color=(weapon_color[0], weapon_color[1], weapon_color[2],
                           200))

                las_outer.visible = False
                las_middle.visible = False
                las_inner.visible = False

                node = cocos.layer.Layer()
                node.add(las_outer, z=1)
                node.add(las_middle, z=2)
                node.add(las_inner, z=3)
                battle.board.add(node, z=1000)

                # give lasers a small particle pre-fire effect
                laser_charge = Galaxy()
                laser_charge.angle = 270
                laser_charge.angle_var = 180
                laser_charge.position = weapon_x, weapon_y
                laser_charge.size = 10
                laser_charge.size_var = 5
                laser_charge.emission_rate = 15
                laser_charge.life = 0.5
                laser_charge.speed = 0
                laser_charge.speed_var = 0
                laser_charge.start_color = Color(weapon_color[0] / 255,
                                                 weapon_color[1] / 255,
                                                 weapon_color[2] / 255, 1.0)
                laser_charge.end_color = Color(weapon_color[0] / 255,
                                               weapon_color[1] / 255,
                                               weapon_color[2] / 255, 1.0)
                node.add(laser_charge, z=0)

                laser_drift = random.uniform(-15.0, 15.0), random.uniform(
                    -15.0, 15.0)

                las_action = Delay(0.5) + ToggleVisibility() \
                             + CallFunc(create_laser_impact, battle.board, target_pos, laser_drift, las_life) \
                             + gl.LineDriftBy(laser_drift, las_life) \
                             + CallFunc(laser_charge.stop_system) + CallFunc(node.kill)
                las_outer.do(las_action)
                las_middle.do(las_action)
                las_inner.do(las_action)

                las_sound = Resources.las_sound
                weapon_channel.play(las_sound)
                las_duration_ms = int(las_action.duration * 1000)
                weapon_channel.fadeout(las_duration_ms)

                travel_time = 0.5
                if min_travel_time == 0 or min_travel_time > travel_time:
                    min_travel_time = travel_time

                if travel_time > max_travel_time:
                    max_travel_time = travel_time

            elif weapon.isBallistic():
                # fire test ballistic projectile
                num_ballistic = weapon.get_projectiles()

                if weapon.isGauss():
                    ballistic_img = Resources.gauss_img
                elif weapon.isLBX():
                    # LBX fires only one projectile, but will appear to have multiple random impacts
                    num_ballistic = 1
                    ballistic_img = Resources.buckshot_img
                else:
                    ballistic_img = Resources.ballistic_img

                # machine gun sound only plays once instead of per projectile
                cannon_sound = None
                if weapon.isMG():
                    cannon_sound = Resources.machinegun_sound
                elif weapon.isGauss():
                    cannon_sound = Resources.gauss_sound

                for i in range(num_ballistic):
                    ballistic = Sprite(ballistic_img)
                    ballistic.visible = False
                    ballistic.position = weapon_x, weapon_y
                    ballistic.scale = weapon.get_scale()
                    ballistic.anchor = 0, 0

                    dx = real_x - weapon_x
                    dy = real_y - weapon_y
                    rads = atan2(-dy, dx)
                    rads %= 2 * pi
                    angle = degrees(rads)

                    ballistic.rotation = angle

                    target_x = real_x + random_offset()
                    target_y = real_y + random_offset()
                    target_pos = target_x, target_y

                    # figure out the duration based on speed and distance
                    ballistic_speed = weapon.get_speed()  # pixels per second
                    distance = Point2(weapon_x, weapon_y).distance(
                        Point2(target_x, target_y))
                    ballistic_t = distance / ballistic_speed

                    # setup the firing sound
                    if cannon_sound is None:
                        cannon_sound = Resources.cannon_sound

                    impact_func = create_ballistic_impact
                    if weapon.isLBX():
                        impact_func = create_lbx_impact

                    action = Delay(i * 0.1) + ToggleVisibility() \
                             + CallFunc(weapon_channel.play, cannon_sound) \
                             + MoveTo((target_x, target_y), ballistic_t) \
                             + CallFunc(impact_func, weapon, battle.board, target_pos) \
                             + CallFunc(ballistic.kill)

                    if weapon.isGauss():
                        # give gauss sound a bit more time to stop
                        action += Delay(cannon_sound.get_length())

                    if i == num_ballistic - 1:
                        # stop the sound channel after the last projectile only
                        action += CallFunc(weapon_channel.stop)

                    ballistic.do(action)

                    battle.board.add(ballistic, z=1000 + i)

                    travel_time = (i * 0.1) + ballistic_t
                    if min_travel_time == 0 or min_travel_time > travel_time:
                        min_travel_time = travel_time

                    if travel_time > max_travel_time:
                        max_travel_time = travel_time

            elif weapon.isMissile():
                # get another sound channel to use just for the explosions
                explosion_channel = pygame.mixer.find_channel()
                if explosion_channel is None:
                    explosion_channel = pygame.mixer.Channel(1)

                # fire test missile projectile
                missile_img = Resources.missile_img

                num_missile = weapon_data.get('count', 1)

                num_per_row = 1
                if weapon.isLRM():
                    num_per_row = 5
                elif weapon.isSRM():
                    num_per_row = 2

                for i in range(num_missile):

                    tube_x = i % num_per_row
                    tube_y = i // num_per_row

                    missile = Sprite(missile_img)
                    missile.visible = False
                    missile.position = weapon_x + tube_x, weapon_y + tube_y
                    missile.scale = weapon.get_scale()
                    missile.anchor = 0, 0

                    dx = real_x - weapon_x
                    dy = real_y - weapon_y
                    rads = atan2(-dy, dx)
                    rads %= 2 * pi
                    angle = degrees(rads)

                    missile.rotation = angle

                    target_x = real_x + random_offset()
                    target_y = real_y + random_offset()
                    target_pos = target_x, target_y

                    # figure out the duration based on speed and distance
                    missile_speed = weapon.get_speed()  # pixels per second
                    distance = Point2(weapon_x, weapon_y).distance(
                        Point2(target_x, target_y))
                    missile_t = distance / missile_speed

                    rand_missile_sound = random.randint(0, 7)
                    missile_sound = Resources.missile_sounds[
                        rand_missile_sound]

                    explosion_sound = Resources.explosion_sound

                    action = Delay(i * 0.05) + ToggleVisibility() \
                             + CallFunc(weapon_channel.play, missile_sound) \
                             + MoveTo((target_x, target_y), missile_t) \
                             + CallFunc(create_missile_impact, battle.board, target_pos) \
                             + CallFunc(missile.kill) \
                             + CallFunc(explosion_channel.play, explosion_sound) \
                             + Delay(0.5)

                    if i == num_missile - 1:
                        # stop the sound channels after the last missile only
                        action += CallFunc(weapon_channel.stop) + CallFunc(
                            explosion_channel.stop)

                    missile.do(action)

                    battle.board.add(missile, z=1000 + i)

                    travel_time = (i * 0.05) + missile_t
                    if min_travel_time == 0 or min_travel_time > travel_time:
                        min_travel_time = travel_time

                    if travel_time > max_travel_time:
                        max_travel_time = travel_time

    # scroll focus over to the target area halfway through the travel time
    target_area = Board.board_to_layer(target_unit.col, target_unit.row)

    # show damage floater after the travel time of the first projectile to hit
    floater = floaters.TextFloater("%i" % attack_damage)
    floater.visible = False
    floater.position = real_x, real_y + target_sprite.get_height() // 3
    battle.board.add(floater, z=2000)

    action = Delay(min_travel_time / 2) + CallFunc(battle.scroller.set_focus, *target_area) \
        + Delay(min_travel_time / 2) + ToggleVisibility() \
        + Delay(0.25) + MoveBy((0, Board.TILE_SIZE), 1.0) \
        + FadeOut(1.0) + CallFunc(floater.kill)
    floater.do(action)

    if action.duration > max_travel_time:
        max_travel_time = action.duration

    stats_action = Delay(min_travel_time) + CallFunc(target_sprite.updateStatsIndicators) \
                   + CallFunc(Interface.UI.updateTargetUnitStats, target_unit)
    target_sprite.do(stats_action)

    if attack_remainder > 0:
        print("Overkill by %i!" % attack_remainder)

    if target_unit.structure > 0:
        print("Remaining %i/%i" % (target_unit.armor, target_unit.structure))

    else:
        print("Target destroyed!")
        # show destroyed floater after the travel time of the first projectile to hit
        destroyed = floaters.TextFloater("DESTROYED")
        destroyed.visible = False
        destroyed.position = real_x, real_y + target_sprite.get_height() // 3
        battle.board.add(destroyed, z=5000)

        # get another sound channel to use just for the explosions
        explosion_channel = pygame.mixer.find_channel()
        if explosion_channel is None:
            explosion_channel = pygame.mixer.Channel(1)

        explosion_sound = Resources.explosion_multiple_sound

        action = Delay(max_travel_time) + ToggleVisibility() \
            + CallFunc(explosion_channel.play, explosion_sound) \
            + (MoveBy((0, Board.TILE_SIZE), 1.0) | CallFunc(create_destruction_explosions, battle.board, target_unit)) \
            + Delay(0.5) + CallFunc(target_sprite.destroy) + FadeOut(2.0) + CallFunc(destroyed.kill)
        destroyed.do(action)

        # give a bit of extra time to explode
        max_travel_time = action.duration

    return max_travel_time
コード例 #29
0
elif len(sys.argv) == 2:
    poke = Pokemon(sys.stdin)

# começa a bataha

r = requests.post('http://localhost:5000/battle/',
                  data=poke.to_XML('<battle_state></battle_state>'))

while r.status_code != 200:
    print('status code: ', r.status_code)
    arq = input('Digite um nome de arquivo valido: ')
    poke = Pokemon(arq)
    r = requests.post('http://localhost:5000/battle/',
                      data=poke.to_XML('<battle_state></battle_state>'))

battle = Battle()

poke = Pokemon(r.text, xml=True)

battle_state = etree.fromstring(r.text)
poke1 = battle_state[0]
battle_state.remove(poke1)
pkmn = etree.tostring(battle_state, encoding='unicode')

poke2 = Pokemon(pkmn, xml=True)

while battle.all_alive(poke, poke2):

    atk_id = battle.make_choice(poke, poke2, ai) + 1
    r = requests.post('http://localhost:5000/battle/attack/' + str(atk_id))
コード例 #30
0
ファイル: proto.py プロジェクト: skishore/proto
 def __init__(self):
   self.screen = pygame.display.set_mode(screen_size)
   self.key_repeater = self.construct_key_repeater()
   self.battle = Battle()
コード例 #31
0
ファイル: model.py プロジェクト: matteli/histemul
    def __init__(self, reset=False, preset=False):
        self.model = {
            'army': Army,
            'battle': Battle,
            'culture': Culture,
            'land': Land,
            'person': Person,
            'player': Player,
            'province': Province,
            'title': Title,
            'war': War,
        }
        connect('histemul')
        self.orders = {}

        if reset:
            client = MongoClient()
            db = client.histemul
            Player.drop_collection()
            Person.drop_collection()
            Army.drop_collection()
            Battle.drop_collection()
            War.drop_collection()

            Province.drop_collection()
            #collection = db.province_vo
            db.command('aggregate', 'province_vo', pipeline=[{'$match':{}}, {'$out': "province"}], allowDiskUse=True, cursor={})
            if preset:
                Matthieu = self.new_player('Matthieu', division='fess', tinctures=['green', 'orange'])
                Pierre = self.new_player('Pierre', division='pale', tinctures=['blue', 'red'])
                Robert = self.new_person('Robert', True, datetime.date(975, 1, 1), Matthieu, 1)
                Jean = self.new_person('Jean', True, datetime.date(981, 1, 1), Pierre, 14)
                Philippe = self.new_person('Philippe', True, datetime.date(965, 1, 1), Pierre, 39)
                Matthieu.leader = Robert
                Matthieu.save()
                Pierre.leader = Jean
                Pierre.save()

                Berquinais = Title.objects.get(pk='Berquinais')
                Berquinais.holder = Robert
                Berquinais.name_number = {'Robert': 1}
                Berquinais.save()

                Orvence = Title.objects.get(pk='Orvence')
                Orvence.holder = Jean
                Orvence.name_number = {'Jean': 1}
                Orvence.save()

                Bourquige = Title.objects.get(pk='Bourquige')
                Bourquige.holder = Philippe
                Bourquige.name_number = {'Philippe': 1}
                Bourquige.save()

                Berquinais_province = Province.objects.get(name='Berquinais')
                Berquinais_province.controller = Robert
                Berquinais_province.save()

                Orvence_province = Province.objects.get(name='Orvence')
                Orvence_province.controller = Jean
                Orvence_province.save()

                Bourquige_province = Province.objects.get(name='Bourquige')
                Bourquige_province.controller = Philippe
                Bourquige_province.save()

                Army_Orvence = self.rally_troops(Pierre, Orvence_province, 'execute')
コード例 #32
0
ファイル: test_task5.py プロジェクト: Canyanwu/BattleGame
    def test__conduct_combat(self):
        t1 = Army()
        t2 = Army()
        t3 = Army()
        t4 = 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)
        t3._Army__assign_army("", 0, 4, 0, formation)
        t4._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) == 0,
                "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),
                             "",
                             msg="Army 2 wrong for Fairer 1,0,0 0")
        except AssertionError as e:
            self.verificationErrors.append(str(e))

        # Checking if t1 is an instance of Army
        try:
            self.assertEqual(isinstance(t3, Army),
                             True,
                             msg="Object is not an instance of Army")
        except AssertionError as e:
            self.verificationErrors.append(str(e))

        # Testing __conduct_combat method
        try:
            self.assertTrue(
                battle._Battle__conduct_combat(t3, t4, formation) == 1,
                "Fairer 0,4,0 0,0,0 failed")
        except AssertionError as e:
            self.verificationErrors.append(str(e))
コード例 #33
0
ファイル: main.py プロジェクト: DiasDaniels/criseinfinita
    artigo = ['uma', 'sua']
helpers.separador()

print(
    f'''Durante uma tempestade de gafanhotos, {j1.name} procurava um lugar para se abrigar, ouviu um chamado abaixo de uma ponte que cruzava um córrego
um velho homem fedorento que tinha com ele algumas trouxas, umas de roupas e outras de sabe-se Odin lá o que. Após um diálogo breve, o mendigo, ausente de suas
faculdades mentais, te entrega {artigo[0]} {arma}, você segue seu caminho após a tempestade de gafanhotos e, ao final da ponte, você encontra um Goblin sedento
por sangue.
Prepare-se para usar {artigo[1]} {arma}!''')

helpers.separador10s()

helpers.separador()
while j1.alive:

    Battle(j1, mon)
    if (j1.alive):
        monkilled += 1

        goblinhp += 10
        mon.hp = goblinhp

        baseAtk += 5
        maxAtk += 5
        mon.atk = randint(baseAtk, maxAtk)

        baseArm += 5
        maxArm += 5
        mon.arm = randint(baseArm, maxArm)
        mon.alive = goblinarm
        mon.alive = True
コード例 #34
0
                if event.key == pygame.K_a:
                    movement = (-1, 0)
                elif event.key == pygame.K_d:
                    movement = (1, 0)
                elif event.key == pygame.K_w:
                    movement = (0, -1)
                elif event.key == pygame.K_s:
                    movement = (0, 1)
                else:
                    movement = (0, 0)

        if (boss.check_movement(movement, player.position)):
            if (map.check_movement(movement, player.position)):
                player.move_player(movement)
        else:
            battle = Battle(niespanier, paichu)
            gameState.changeMode()

        gui.proceed_input(event)

    else:
        screen.fill((0, 255, 0))

        if gameState.battleType == 'boss':

            gui.draw_gui_battle(battle)
            if boss.speak(screen, gui):
                battle.drawBattle(screen)
                if battle.checkBattleState() == 'victory':
                    gameState.changeMode()
            for event in pygame.event.get():
コード例 #35
0
 def setUp(self) -> None:
     self.first_army = Army(Side.Monsters)
     self.first_army.add(DragonSquad(self.first_army.side, 4))
     self.battle = Battle(self.first_army)
コード例 #36
0
ファイル: client.py プロジェクト: romaolucas/PokemonHolyWater
    poke = Pokemon(sys.stdin)

# começa a bataha


r = requests.post('http://localhost:5000/battle/', data = poke.to_XML(
                                    '<battle_state></battle_state>'))

while r.status_code != 200:
    print('status code: ', r.status_code)
    arq = input('Digite um nome de arquivo valido: ')
    poke = Pokemon(arq)
    r = requests.post('http://localhost:5000/battle/', data = poke.to_XML(
                                    '<battle_state></battle_state>'))

battle = Battle()

poke = Pokemon(r.text, xml = True)

battle_state = etree.fromstring(r.text)
poke1 = battle_state[0]
battle_state.remove(poke1)
pkmn = etree.tostring(battle_state, encoding = 'unicode')
 
poke2 = Pokemon(pkmn, xml = True)
 
while battle.all_alive(poke, poke2):

    atk_id = battle.make_choice(poke, poke2, ai) + 1
    r = requests.post('http://localhost:5000/battle/attack/' + str(atk_id))
コード例 #37
0
ファイル: main.py プロジェクト: smallzhong/pythonRPG
        if t == '1':
            mon = get_monster()
            # print(mon)
            print('当前有如下武将:', end='')
            for key in g_userdata['hero'].keys():
                print(key)
            a = input('请输入您想要派出的武将,1.云天河')
            if a != '1':
                continue
            else:
                a = '云天河'
            # print(g_userdata['hero'][a])
            fighter = Fighter(**g_userdata['hero'][a])  # 传入字典
            # print(mon[1])
            monster = Monster(**mon[1])
            battle = Battle(monster, fighter)  # 创建战斗对象
            print(
                f'战斗开始,{a}({g_userdata["hero"][a]["level"]}级)对阵{mon[0]}({mon[1]["level"]}级)!'
                f'{a}剩余{battle.fighter.hp}精,剩余{battle.fighter.qi}气,'
                f'{mon[0]}剩余{battle.monster.hp}精,剩余{battle.monster.qi}气')
            # while not battle.done():
            #     battle.move()
            while battle.move():  # 如果返回False表明战斗结束
                time.sleep(1)
                print(
                    f'\t战斗进行中,{a}剩余{battle.fighter.hp if battle.fighter.hp > 0 else 0}精,剩余{battle.fighter.qi}气,'
                    f'{mon[0]}剩余{battle.monster.hp if battle.monster.hp > 0 else 0}精,剩余{battle.monster.qi}气'
                )

            # 战斗结束后获取战斗结果,进行加气、判断升级等操作
            res = battle.res()
コード例 #38
0
 def __init__(self):
     self.core = Core()
     self.graphical_logic = Graphical_logic()
     self.battle = Battle('1')
コード例 #39
0
ファイル: autoe4.py プロジェクト: cherryunix/jn-blacktech
class AutoE4:
    OK = 0
    Pit = -1
    Broke = -2
    Error = -3

    def __init__(self, game, shipNames, dismantleList = [ ]):
        self.game = game
        self.ships = [ game.findShip(name) for name in shipNames ]
        self.dismantleList = dismantleList
        self.fleet = None
        self.formerShips = None

    def isReady(self):
        return (self.fleet is not None) and (self.fleet.isReady())

    def getReady(self, fleet):
        if self.fleet is not None and self.fleet != fleet:
            Log.i('Already has fleet')
            return False
        for i in range(len(self.ships)):
            if not self.ships[i].isIdle():
                Log.i('%s is not idle' % self.ships[i].getName())
                return False
            if self.ships[i].isBroken():
                Log.i('%s is broken' % self.ships[i].getName())
                return False

        self.fleet = fleet
        self.formerShips = fleet.ships.copy()
        for i in range(6):
            if self.ships[i] != self.fleet.ships[i]:
                fleet.changeShips(self.ships)
                fleet.fill()
                return True
        fleet.fill()
        return True

    def end(self):
        ret = self.fleet
        self.fleet.changeShips(self.formerShips)
        self.fleet = None
        self.formerShips = None
        return ret

    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 end(self):
        self.battle.quit()
        self.fleet.fill()

        for ship in self.newShips:
            if ship is not None:
                if ship.getName() in self.dismantleList:
                    Log.i('Dismantle ' + ship.getName())
                    keepEquipt = (ship.getName() in [ '翡翠', '列克星敦' ])
                    ship.dismantle(keepEquipt)
                else:
                    Log.i('Keep ship ' + ship.getName())
                    if '威廉' in ship.getName():
                        Log.e('Done')
コード例 #40
0
def actOnCell(battle, col, row):
    if not isActionReady():
        return

    # perform an action based on the given cell and/or its occupants
    turn_unit = battle.getTurnUnit()
    turn_player = turn_unit.getPlayer()

    if turn_unit is None:
        # TODO: make sure it is a player unit's turn or do something else
        return

    cell = battle.getCellAt(col, row)
    if cell is None:
        return

    # if the cell is not already selected, select it instead
    sel_pos = battle.getSelectedCellPosition()
    if sel_pos is None or col != sel_pos[0] or row != sel_pos[1]:
        moveSelectionTo(battle, col, row)
        return

    cell_unit = battle.getUnitAtCell(col, row)

    if col == turn_unit.col and row == turn_unit.row:
        setActionReady(False)

        # TODO: ask confirmation to end the turn without firing
        print("Skipping remainder of the turn!")

        battle.nextTurn()

        setActionReady(True)

    elif battle.isCellAvailable(col, row) and cell.range_to_display > 0:
        setActionReady(False)

        turn_unit.move -= cell.range_to_display

        for cell in battle.board.cellMap.itervalues():
            cell.remove_indicators()

        animate_reverse = (turn_unit.col - col > 0) or (turn_unit.row - row >
                                                        0)

        def _ready_next_move():
            turn_unit.sprite.sulk()
            for chk_cell in battle.board.cellMap.itervalues():
                chk_cell.remove_indicators()

            battle.showRangeIndicators()
            battle.showUnitIndicators()

            battle.setSelectedCellPosition(turn_unit.col, turn_unit.row)

            turn_cell_pos = Board.board_to_layer(turn_unit.col, turn_unit.row)
            if turn_cell_pos is not None:
                turn_cell_pos = turn_cell_pos[
                    0] + Board.TILE_SIZE // 2, turn_cell_pos[
                        1] + Board.TILE_SIZE // 2

            battle.scroller.set_focus(*turn_cell_pos)

            setActionReady(True)

        turn_unit.sprite.strut(reverse=animate_reverse)
        turn_unit.sprite.moveToCell(col, row, animate_reverse,
                                    _ready_next_move)

    elif Battle.isFriendlyUnit(turn_player, cell_unit):
        # TODO: interact with friendly unit somehow, like swap cells with it if it has move remaining?
        print("Friendly: " + str(cell_unit))

    elif cell_unit is not None \
            and not cell_unit.isDestroyed() \
            and cell_unit is not turn_unit:
        setActionReady(False)

        print("Enemy: " + str(cell_unit))

        battle.showUnitIndicators(visible=False)
        for chk_cell in battle.board.cellMap.itervalues():
            chk_cell.remove_indicators()

        attack_time = performAttackOnUnit(battle, cell_unit)

        def _ready_next_turn():
            setActionReady(False)
            battle.nextTurn()
            setActionReady(True)

        # start the next turn when the attack is completed
        battle.board.do(Delay(attack_time) + CallFunc(_ready_next_turn))
コード例 #41
0
    def characters_select(self):
        """
		Displays the screen in which character select happens.
		"""
        errors = False
        error = None

        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.game.quit_game()
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_l:
                        self.game.show_skills()
                    if event.key == pygame.K_ESCAPE:
                        self.game.player.skills = dict(
                            self.original_player_skills)
                        return True
                    if event.key == pygame.K_RETURN:
                        if len(self.warriors) == 0:
                            errors = True
                            error = self.no_chosed_warriors
                        elif len(self.enemies) == 0:
                            errors = True
                            error = self.no_chosed_enemies
                        else:
                            # Flip warrir images
                            self.change_image_direction()
                            # Start battle
                            battle = Battle(self.game, self.warriors,
                                            self.enemies)
                            battle.start_battle()
                            # Clear warriors and enemies
                            self.clear()

            # Get character image and rects
            self.character_images, self.character_rects = self.get_rects_and_images(
            )

            # Display bg and title
            self.window.blit(self.battle_bg, [0, 0])
            self.window.blit(self.title,
                             [self.game.center_text_x(self.title), 50])

            # Draw unlocked characters
            for char, charimg, imgrect in zip(self.characters,
                                              self.character_images,
                                              self.character_rects):
                self.window.blit(charimg, [imgrect.x, imgrect.y])

                # Check if clicked character
                try:
                    clicked_char, pressed_btn = self.game.clicked_surface_rect(
                        imgrect, True, True)
                    print pressed_btn
                except TypeError:
                    clicked_char = False

                # Add clicked to warriors or to enemies group
                if clicked_char and pressed_btn[0] and len(self.warriors) < 3:
                    self.characters.remove(char)
                    self.warriors.append(char)
                    self.warrior_images.append(charimg)
                elif clicked_char and pressed_btn[2] and len(self.enemies) < 3:
                    self.characters.remove(char)
                    self.enemies.append(char)
                    self.enemy_images.append(charimg)

            # Draw enemies
            self.window.blit(
                self.enemies_text,
                [self.game.WINDOW_WIDTH / 1.3, self.game.WINDOW_HEIGHT / 5])
            enemy_rects = self.set_chosed_chars_rects(
                len(self.enemies), self.game.WINDOW_WIDTH / 1.7,
                self.game.WINDOW_HEIGHT / 4, 100)

            for enemy, enemyimg, enemyrect in zip(self.enemies,
                                                  self.enemy_images,
                                                  enemy_rects):
                self.window.blit(enemyimg, [enemyrect.x, enemyrect.y])

                clicked_enemy = self.game.clicked_surface_rect(enemyrect)
                if clicked_enemy:
                    # Remove from enemies and add to all characters
                    self.enemies.remove(enemy)
                    self.enemy_images.remove(enemyimg)
                    self.characters.append(enemy)

            # Draw warriors
            self.window.blit(
                self.warriors_text,
                [self.game.WINDOW_WIDTH / 6, self.game.WINDOW_HEIGHT / 5])
            warrior_rects = self.set_chosed_chars_rects(
                len(self.warriors), 20, self.game.WINDOW_HEIGHT / 4, 100)

            for warrior, warriorimg, warriorect in zip(self.warriors,
                                                       self.warrior_images,
                                                       warrior_rects):
                self.window.blit(warriorimg, [warriorect.x, warriorect.y])

                clicked_warrior = self.game.clicked_surface_rect(warriorect)
                if clicked_warrior:
                    # Remove from warriors and add to all characters
                    self.warriors.remove(warrior)
                    self.warrior_images.remove(warriorimg)
                    self.characters.append(warrior)

            # Draw errors if any
            if errors:
                self.window.blit(error, [20, self.game.WINDOW_HEIGHT / 1.1])

            # Update everything and set clock
            pygame.display.update()
            self.game.clock.tick(self.game.FPS)
コード例 #42
0
ファイル: civil_war.py プロジェクト: Raven65/CivilWar
    if mode == 'n':
        choice = cf.choose_input(
            "Who do you want to stand for?", ["t", "s"],
            "(T: Tony Starks / S: Steven Rogers)")  # 若手动操作,询问操作哪一方
        if choice == 't':
            tony_mode = 'user'
        else:
            steven_mode = 'user'

    # 初始化
    settings = Settings()
    win = [0, 0, 0]
    for i in range(100):
        tony = Fighter("Tony Stark", settings)
        steven = Fighter("Steven Rogers", settings)
        battle = Battle(tony, steven, settings)
        while battle.round:

            # 获取战斗策略
            tony_act = tony.fight_strategy(steven, tony_mode)
            steven_act = steven.fight_strategy(tony, steven_mode)

            # 进行战斗
            fn.fight_function[tony_act](tony, steven, steven_act)
            fn.fight_function[steven_act](steven, tony, tony_act)

            # 键盘输出
            cf.keyboard_output(settings, tony, steven, tony_act, steven_act)

            # 判断胜负
            battle.round -= 1
コード例 #43
0
ファイル: game.py プロジェクト: UPIMAN73/RTGM-machine
 def battleTest(self):
     battle = Battle(self.ph, self.eh)
     battle.battleLoop()
コード例 #44
0
    def _battle(self, battle):
        print('========== Found a battle: <', battle['user0'].encode('utf-8'),
              ',', battle['idOfUser0'], '> vs <',
              battle['user1'].encode('utf-8'), ', ', battle['idOfUser1'], '>')

        # Mark Running
        doc_rec = {'$set': {'status': 'Running', 'judger': const.SERVER_NAME}}
        self._updateDB('records', {'_id': battle['_id']}, doc_rec)

        # Run battle
        server = const.AI_SERVER_DIRECTORY
        ai0 = self._findOne('ais', {
            'user': battle['user0'],
            'idOfUser': battle['idOfUser0']
        })
        ai1 = self._findOne('ais', {
            'user': battle['user1'],
            'idOfUser': battle['idOfUser1']
        })
        updater = lambda step: self._updateDB(
            'records', {'_id': battle['_id']}, {'$set': {
                'step': step
            }})
        text_uploader = lambda path: self._uploadText(path)

        # Ensure executable file
        self._ensureFile(str(ai0['_id']), 'ai', ai0['absPath'])
        self._ensureFile(str(ai1['_id']), 'ai', ai1['absPath'])

        # Run battle
        result = Battle(server, ai0, ai1, updater, text_uploader).Run()

        # Prepare documents
        doc_ai0 = {'$set': {'name': result['user'][0]}}
        doc_ai1 = {'$set': {'name': result['user'][1]}}
        doc_rec = {
            '$set': {
                'name0': result['user'][0],
                'name1': result['user'][1],
                'step': result['total'],
                'status': 'Finished',
                'result': result['result'],
                'log': result['json'],
                'runDate': datetime.utcnow(),
                'stdin0': result['stdin0'],
                'stdout0': result['stdout0'],
                'stderr0': result['stderr0'],
                'stdin1': result['stdin1'],
                'stdout1': result['stdout1'],
                'stderr1': result['stderr1'],
            }
        }
        doc_user0 = {'$inc': dict()}
        doc_user1 = {'$inc': dict()}
        doc_contest_ai0 = {'$inc': dict()}
        doc_contest_ai1 = {'$inc': dict()}
        if result['result'] == 2:
            # if draw
            doc_ai0['$inc'] = {'draw': 1}
            doc_ai0['$set']['ratio'] = (
                ai0['win']) / float(ai0['win'] + ai0['draw'] + ai0['lose'] + 1)
            doc_user0['$inc']['draw'] = 1
            if ai0['user'] != ai1['user']:
                doc_user1['$inc']['draw'] = 1
                doc_ai1['$set']['ratio'] = (ai1['win']) / float(
                    ai1['win'] + ai1['draw'] + ai1['lose'] + 1)
                doc_ai1['$inc'] = {'draw': 1}
            else:
                doc_user1 = None
            doc_contest_ai0['$inc']['ais.$.draw'] = 1
            doc_contest_ai1['$inc']['ais.$.draw'] = 1
        elif result['result'] == 1:
            # if ai1 won:
            doc_ai0['$inc'] = {'lose': 1}
            doc_ai1['$inc'] = {'win': 1}
            if ai0['user'] != ai1['user']:
                cnt0 = float(ai0['win'] + ai0['draw'] + ai0['lose'] + 1)
                cnt1 = float(ai1['win'] + ai1['draw'] + ai1['lose'] + 1)
            else:
                cnt0 = float(ai0['win'] + ai0['draw'] + ai0['lose'] + 2)
                cnt1 = float(ai1['win'] + ai1['draw'] + ai1['lose'] + 2)
            doc_ai0['$set']['ratio'] = (ai0['win']) / cnt0
            doc_ai1['$set']['ratio'] = (ai1['win'] + 1) / cnt1
            doc_user0['$inc']['lose'] = 1
            doc_user1['$inc']['win'] = 1
            doc_rec['$set']['winnerId'] = ai1['_id']
            doc_rec['$set']['loserId'] = ai0['_id']
            doc_rec['$set']['winner'] = {
                'name': result['user'][1],
                'user': ai1['user'],
                'idOfUser': ai1['idOfUser']
            }
            doc_rec['$set']['loser'] = {
                'name': result['user'][0],
                'user': ai0['user'],
                'idOfUser': ai0['idOfUser']
            }
            doc_contest_ai0['$inc']['ais.$.lose'] = 1
            doc_contest_ai1['$inc']['ais.$.win'] = 1
        elif result['result'] == 0:
            # if ai0 won:
            doc_ai0['$inc'] = {'win': 1}
            doc_ai1['$inc'] = {'lose': 1}
            if ai0['user'] != ai1['user']:
                cnt0 = float(ai0['win'] + ai0['draw'] + ai0['lose'] + 1)
                cnt1 = float(ai1['win'] + ai1['draw'] + ai1['lose'] + 1)
            else:
                cnt0 = float(ai0['win'] + ai0['draw'] + ai0['lose'] + 2)
                cnt1 = float(ai1['win'] + ai1['draw'] + ai1['lose'] + 2)
            doc_ai0['$set']['ratio'] = (ai0['win'] + 1) / cnt0
            doc_ai1['$set']['ratio'] = (ai1['win']) / cnt1
            doc_user0['$inc']['win'] = 1
            doc_user1['$inc']['lose'] = 1
            doc_rec['$set']['winnerId'] = ai0['_id']
            doc_rec['$set']['loserId'] = ai1['_id']
            doc_rec['$set']['winner'] = {
                'name': result['user'][0],
                'user': ai0['user'],
                'idOfUser': ai0['idOfUser']
            }
            doc_rec['$set']['loser'] = {
                'name': result['user'][1],
                'user': ai1['user'],
                'idOfUser': ai1['idOfUser']
            }
            doc_contest_ai0['$inc']['ais.$.win'] = 1
            doc_contest_ai1['$inc']['ais.$.lose'] = 1
        else:
            print("!!!!!!!! UNKNOWN RESULT !!!!!!!!")

        # Update documents
        docs = {'ais': [], 'users': [], 'records': []}
        docs['ais'].append({'where': {'_id': ai0['_id']}, 'value': doc_ai0})
        docs['ais'].append({'where': {'_id': ai1['_id']}, 'value': doc_ai1})
        docs['users'].append({
            'where': {
                'name': ai0['user']
            },
            'value': doc_user0
        })
        if doc_user1:
            docs['users'].append({
                'where': {
                    'name': ai1['user']
                },
                'value': doc_user1
            })
        docs['records'].append({
            'where': {
                '_id': battle['_id']
            },
            'value': doc_rec
        })
        if 'contestId' in battle and battle['contestId'] != ObjectId(
                '000000000000000000000000'):
            docs['contests'] = []
            docs['contests'].append({
                'where': {
                    '_id': battle['contestId'],
                    "ais.ai_id": ai0['_id']
                },
                'value': doc_contest_ai0
            })
            docs['contests'].append({
                'where': {
                    '_id': battle['contestId'],
                    "ais.ai_id": ai1['_id']
                },
                'value': doc_contest_ai1
            })
            docs['contests'].append({
                'where': {
                    '_id': battle['contestId']
                },
                'value': {
                    '$inc': {
                        'running': -1,
                        'finished': 1
                    }
                }
            })
        self._updateDBs(docs)

        print("      Done!")
コード例 #45
0
pokemon2.stats = {
    HP: 39,
    ATTACK: 52,
    DEFENSE: 43,
    SPATTACK: 80,
    SPDEFENSE: 65,
    SPEED: 65
}

#Attacks
pokemon1.attacks = [Attack("scratch", "normal", PHYSICAL, 10, 10, 100)]
pokemon2.attacks = [Attack("scratch", "normal", PHYSICAL, 10, 10, 100)]

#Start Battle!
battle = Battle(pokemon1, pokemon2)


def ask_command(pokemon):
    command = None
    while not command:
        # DO ATTACK -> attack 0
        tmp_command = input("what should " + pokemon.name + " do?").split(" ")
        if len(tmp_command) == 2:
            try:
                if tmp_command[0] == DO_ATTACK and 0 <= int(tmp_command[1]):
                    command = Command({DO_ATTACK: int(tmp_command[1])})
            except Exception:
                pass
    return command
コード例 #46
0
ファイル: main.py プロジェクト: tpennypacker/showdown_bot
async def parse_response(ws, msg):

    msg_arr = msg.split('|')

    # ignore short messages
    if ( len(msg_arr) == 1 ):
        print("length 1 message: " + msg)

    # display error messages
    elif (msg_arr[1] == "error" or msg_arr[1] == "popup"):
        print(msg)

    #  display PMs received, handle command messages from whitelisted users
    elif (msg_arr[1] == "pm"):
        print(msg)
        sender = msg_arr[2].strip().lower().replace(" ", "").replace("≧◡≦","")
        whitelist = [username.lower().strip() for username in bot_settings.bot_owners.split(",")]
        if (msg_arr[4][0] == "$" and sender in whitelist):
            await pm_commands.parse_command(ws, msg_arr[4], sender)

    # triggers when a battle ends, checks if bot won and sends appropriate message
    elif (msg_arr[0][0:7] == ">battle" and "win" in msg_arr):
        battletag = funcs.get_battletag(msg_arr)
        win_id = msg_arr.index("win") + 1
        bot_won = (msg_arr[win_id].strip("\n").lower() == bot_settings.username.lower())
        await funcs.on_battle_end(ws, battles, battletag, bot_won)
        # remove finished battle
        battle = funcs.get_battle(battles, battletag)
        battle.did_bot_win = bot_won
        #logging.record_battle(battle)
        remove_id = battles.index(battle)
        battles.pop(remove_id)

    # checks if challenges to be accepted
    elif (msg_arr[1] == "updatechallenges" and bot_settings.accept_challenges == True):
        #print(msg)
        await funcs.handle_challenges(ws, msg_arr)

    # triggers on any request message, adds team_data from it to battle
    elif (msg_arr[1] == "request"):
        battletag = funcs.get_battletag(msg_arr)
        battle = funcs.get_battle(battles, battletag)
        battle.next_team_data = msg_arr[2]

    # triggers when receive information about a battle
    elif (msg_arr[0][0:7] == ">battle" and msg_arr[1] == "\n"):
        battletag = funcs.get_battletag(msg_arr)
        battle = funcs.get_battle(battles, battletag)
        # read in information from message
        battlelog_parser.battlelog_parsing(battle, msg)
        # read data from previous request message, and prompt any needed switch/move
        await battle.load_team_data(ws)

    # login action
    elif (msg_arr[1] == "challstr"):
        await funcs.log_in(ws, msg_arr)

    # triggers when user first logs in
    elif (msg_arr[1] == 'updateuser' and msg_arr[2].lower().strip() == bot_settings.username.lower()):
        #print(msg)
        await funcs.startup_ops(ws, msg_arr)

    # triggers when battle initialises
    elif ('>battle' in msg_arr[0] and msg_arr[1] == 'init'):
        battletag = funcs.get_battletag(msg_arr)
        battles.append(Battle(battletag)) # instantiate battle object

    # triggers when get information at start of battle about either player
    elif ('>battle' in msg_arr[0] and msg_arr[1] == 'player'):
        battletag = funcs.get_battletag(msg_arr)
        battle = funcs.get_battle(battles, battletag)
        # note player's side
        if (msg_arr[3].lower() == bot_settings.username.lower()):
            battle.my_side = msg_arr[2]
        else: # note foe's name, side, and send greeting message
            battle.opponent_name = msg_arr[3]
            #battle.opponent_elo, battle.opponent_gxe = logging.get_rank(battle.opponent_name)
            #battle.my_elo, battle.my_gxe = logging.get_rank(bot_settings.username)
            battle.foe_side = msg_arr[2]
            await funcs.on_battle_start(ws, battles, battletag)
        # if message contains team preview, read in teams and prompt leads
        if ("teampreview\n" in msg_arr):
            battle.initialise_teams(msg_arr)
            await battle.load_team_data(ws)
コード例 #47
0
class Event_Handler():

    def __init__(self):
        self.core = Core()
        self.graphical_logic = Graphical_logic()
        self.battle = Battle('1')

#Уровень шаманизма - 90! NE ПbTauTeCb ПОНЯТb БЕЗНОГNМ 
    def stage_0(self,event,fraction,days,action_to_map_coords,action_to_minimap_coords,last_x,last_y,filename,x_start,y_start):
        if (event[0]=='map_coords'):
            try:
                x_start,y_start = action_to_minimap_coords(last_x,last_y)# ВОТ ТЫ ГДЕ, СЦУКА!
            except AttributeError:
                print 'lol'
                x_start,y_start = action_to_minimap_coords(event[2],event[3])# ВОТ ТЫ ГДЕ, СЦУКА!
            #print 'Coords = '+str(event[2])+' '+str(event[3])
            stage, army_coords,id_army = action_to_map_coords(event[2],event[3],x_start,y_start)
            return stage,last_x,last_y,fraction,days, army_coords,id_army,x_start,y_start
        elif (event[0]=='minimap_coords'):
            x_start,y_start = action_to_minimap_coords(event[2],event[3])# ВОТ ТЫ ГДЕ, СЦУКА!
            stage = event[1]
            last_x = event[2]
            last_y = event[3]
            return stage,last_x,last_y,fraction,days, 0,0,x_start,y_start
        elif (event[0]=='save_mode'):
            stage = event[1]
            return stage,last_x,last_y,fraction,days, 0,0,x_start,y_start
        elif (event[0]=='load_mode'):
            stage = event[1]
            return stage,last_x,last_y,fraction,days, 0,0,x_start,y_start
        elif (event[0]=='end_of_army_steps'):
            print 'end_of_army_steps'
            return stage,last_x,last_y,fraction,days, 0,0,x_start,y_start
        elif (event[0]=='base_mode'):
            stage = event[1]
            return stage,last_x,last_y,fraction,days, 0,0,x_start,y_start
        elif (event[0]=='end_of_players_steps'):
            if fraction == 1:
                self.graphical_logic.add_resources_for_current_fraction(fraction, filename)
                self.graphical_logic.change_all_armies_steps_for_fraction(fraction, filename)
                if (days+2)%10 == 0:
                    print ' pivo'
                    self.graphical_logic.troops_generator(fraction, filename)                
                fraction = 2
                return 0,last_x,last_y,fraction,days, 0,0,x_start,y_start
            elif fraction == 2:
                self.graphical_logic.add_resources_for_current_fraction(fraction, filename)
                self.graphical_logic.change_all_armies_steps_for_fraction(fraction, filename)
                if (days+2)%10 == 0:
                    print 'vodka'
                    self.graphical_logic.troops_generator(fraction, filename)    
                fraction = 1
                days +=1
                return 0,last_x,last_y,fraction,days, 0,0,x_start,y_start

        
    def stage_1(self,event,name_for_saving,filename,action_for_save,reload_window,last_x,last_y):
        action_for_save(name_for_saving)
        print 'Lol = '+str(len(event))
        stage = event[1]
        if event[3] == 'continue':
            if len(name_for_saving) <10:
                name_for_saving += event[2]
                action_for_save(name_for_saving)
        if event[3] == 'backspace':
            if len(name_for_saving)>0:
                name_for_saving = name_for_saving[:-1]
                action_for_save(name_for_saving)
        if event[3] == 'save':
            if name_for_saving >2:
                self.core.save_file(name_for_saving,filename)
                name_for_saving = ''
                try:
                    reload_window(last_x,last_y)
                except AttributeError:
                    reload_window(0,0)
        if event[3] == 'cancel':
            name_for_saving = ''
            try:
                reload_window(last_x,last_y)
            except AttributeError:
                reload_window(0,0)
        return stage, name_for_saving
    
    def stage_2(self,event,name_for_loading,filename,action_for_load,reload_window,last_x,last_y):
        action_for_load(name_for_loading)
        print 'Lol = '+str(len(event))
        stage = event[1]
        if event[3] == 'continue':
            if len(name_for_loading) <10:
                name_for_loading += event[2]
                action_for_load(name_for_loading)
        if event[3] == 'backspace':
            if len(name_for_loading)>0:
                name_for_loading = name_for_loading[:-1]
                action_for_load(name_for_loading)
        if event[3] == 'save':
            if name_for_loading >2:
                self.core.load_file(name_for_loading,filename)
                name_for_loading = ''
                try:
                    reload_window(last_x,last_y)
                except AttributeError:
                    reload_window(0,0)
        if event[3] == 'cancel':
            name_for_loading = ''
            try:
                reload_window(last_x,last_y)
            except AttributeError:
                reload_window(0,0)
        return stage, name_for_loading
    
    def stage_3(self,event,stage,moving_army,filename,id_army,last_x,last_y):
        armies_list = 0
        if (event[0] == 'move_army'):
            current_steps = self.graphical_logic.get_current_steps(id_army, filename)
            if current_steps > 0:
                try:
                    move, stage,last_x,last_y,armies_list = moving_army(event[1],event[2],last_x,last_y)
                except TypeError:
                    move = False
                if move == True:
                    self.graphical_logic.change_current_steps(id_army, filename, current_steps, -1)

        elif (event[0] == 'end_of_army_steps'):
            stage = event[1]
            armies_list = 0
        return stage,last_x,last_y,armies_list
    
    
    def stage_6(self,event,battle_dialog,stage,reload_window,last_x,last_y,armies_lists):
        print event
        list = self.battle.auto_battle(armies_lists[0], armies_lists[1])
        print list
        if event[0] == 'battle_mode':
            stage = event[1]
            print stage
            print event
            return stage
        
        else:
            stage = 6
            return stage
コード例 #48
0
import sys
from pokemon import Pokemon
from battle import Battle
from ai import *
 
poke2 = Pokemon("squirtle")
poke1 = Pokemon("charmander")
ai = AI()
battle = Battle()


active = battle.get_first(poke1, poke2)
while battle.all_alive(poke1, poke2):
    
    if (active == poke2):
        AI_choice = battle.make_choice(poke2, poke1, ai)
        battle.attack(poke2, poke1, AI_choice)
    else :
        AI_choice = battle.make_choice(poke1, poke2, ai)
        battle.attack(poke1, poke2, AI_choice)
        
    if (active == poke1): active = poke2
    else : active = poke1

コード例 #49
0
ファイル: field.py プロジェクト: AFDudley/equanimity
 def start_battle(self, attacking_squad):
     self.battle = Battle(self, attacking_squad)
     self.battle.persist()
     self.battle.start()
コード例 #50
0
ファイル: field.py プロジェクト: AFDudley/equanimity
class Field(Persistent):

    """Player owned field logic."""

    @classmethod
    def get(self, world, loc):
        w = get_world(world)
        if w is not None:
            return w.fields.get(tuple(loc))

    def __init__(self, world, coord, element, owner=None, grid=None):
        self.world = world
        self.world_coord = Hex._make(coord)
        if grid is None:
            grid = Grid()
        self.grid = grid
        self.element = element
        self.clock = FieldClock()
        self.stronghold = Stronghold(self)
        self.queue = FieldQueue()
        self.plantings = {}
        self.battle = None
        self._owner = None
        if owner is None:
            owner = WorldPlayer.get()
        self.owner = owner

    def api_view(self, requester=None):
        if requester is not None:
            visible = requester.get_visible_fields(self.world.uid)
            if self.world_coord not in visible:
                return {}
        # TODO -- add factory etc stuff
        return dict(owner=self.owner.uid,
                    element=self.element,
                    coordinate=self.world_coord,
                    state=self.state,
                    clock=self.clock.api_view(),
                    queue=self.queue.as_array(),
                    battle=getattr(self.battle, 'uid', None))

    @property
    def in_battle(self):
        return (self.battle is not None and not self.battle.state.game_over)

    @property
    def state(self):
        if self.in_battle:
            return FIELD_BATTLE
        else:
            return self.clock.state(self)

    @property
    def owner(self):
        return self._owner

    @owner.setter
    def owner(self, owner):
        self._owner = owner
        for s in self.stronghold.squads:
            s.owner = owner
        for u in self.stronghold.free:
            u.owner = owner

    def get_adjacent(self, direction):
        """ Returns the field adjacent to this one in a given direction.
        Returns None if at the border. """
        t = self.world.grid.get_adjacent(self.world_coord, direction=direction)
        if t:
            return self.world.fields.get(tuple(tuple(t)[0]))

    def process_battle_and_movement(self):
        """ Starts a battle if an attacker is available, otherwise moves
        a friendly squad into the stronghold if available """
        # First, check if there was a previous battle and if it is over
        if self.battle is not None and self.battle.state.game_over:
            # If the winner is not the owner, that means the stronghold was
            # still garrisoned, and we must start a new battle
            if self.battle.winner != self.owner:
                self.start_battle(self.battle.battlefield.atksquad)
        else:
            next_squad = self.queue.pop()
            if next_squad is not None:
                if next_squad.owner == self.owner:
                    self.stronghold.move_squad_in(next_squad)
                else:
                    self.start_battle(next_squad)

    def start_battle(self, attacking_squad):
        self.battle = Battle(self, attacking_squad)
        self.battle.persist()
        self.battle.start()

    def check_ungarrisoned(self):
        """ Reverts ownership to the WorldPlayer if unoccupied """
        wp = WorldPlayer.get()
        if self.owner != wp and not self.stronghold.garrisoned:
            self.owner = wp

    def get_taken_over(self, atkr):
        """ Transfers a winning attacking squad to the field. Returns False
        if the stronghold is still controlled. """
        if self.stronghold.garrisoned:
            return False
        self.owner = atkr.owner
        self.stronghold.move_squad_in(self.battlefield.atksquad)
        return True

    def place_scient(self, unit, location):
        if getattr(unit, 'type', '') != 'scient':
            raise ValueError('Unit {0} must be a scient'.format(unit))
        location = Hex._make(location)
        # Placement can only be on one side of the field
        if location[0] <= 0:
            raise ValueError('First coordinate of location must be positive')
        # Unit must be in a squad
        if not isinstance(unit.container, Squad):
            raise ValueError('Unit must be in a squad to be placed on a field')
        # Location must fit on grid
        if not self.grid.in_bounds(location):
            msg = 'Location {0} does not fit on the field'
            raise ValueError(msg.format(location))
        # Unit must not collide with other units placed in its squad
        for u in unit.container:
            if u != unit and u.chosen_location == location:
                msg = 'Location is already occupied by squad member {0}'
                raise ValueError(msg.format(u))
        unit.chosen_location = location

    def rand_place_scient(self, unit):
        """Randomly place a unit on the grid."""
        available = set(self.grid.placement_coords())
        if not available:
            raise ValueError("Grid is full")
        taken = set([u.chosen_location for u in unit.container
                     if not u.chosen_location.is_null()])
        available = available - taken
        return self.place_scient(unit, random.choice(available))

    def rand_place_squad(self, squad):
        """place the units in a squad randomly on the battlefield"""
        # Clear any previously chosen locations
        for u in squad:
            u.chosen_location = Hex.null
        available = set(self.grid.placement_coords())
        positions = random.sample(available, len(squad))
        for unit, pos in zip(squad, positions):
            self.place_scient(unit, pos)

    def get_tile_comps(self):
        """returns a list of stones 1/8th the value of the tile comps."""
        stone_list = []
        for tile in self.grid.iter_tiles():
            stone = Stone()
            for suit, value in tile.comp.iteritems():
                stone[suit] += value / 8  # this 8 will need to be tweaked.
            if stone.value() != 0:
                stone_list += [stone]
        return stone_list

    def set_silo_limit(self):
        """Sets the silo limit to 1 year's worth of stones."""
        # this uses get_tile_comps so the / 8 is only maintained in one place.
        limit = {'Earth': 0, 'Fire': 0, 'Ice': 0, 'Wind': 0}
        for stone in self.get_tile_comps():
            for element in limit.keys():
                limit[element] += stone[element]
        return self.stronghold.silo.set_limit(limit)

    def add_planting(self, loc, comp):
        self.planting[loc] = comp, sum(comp.values())

    def plant(self):
        """Plants from self.plantlings"""
        if self.stronghold.farm.produce(self.plantings):
            for loc, comp in self.plantings.iteritems():
                stone = self.stronghold.silo.get(comp)
                self.grid.imbue_tile(loc, stone)
                self.grid.get(loc)._p_changed = 1
                self.grid._p_changed = 1
                self.element = get_element(self.grid.comp)
                self._p_changed = 1
                self.set_silo_limit()

    def harvest(self):
        """returns set of stones generated at harvest"""
        # this needs to be more clever and relate to the units in
        # the stronghold somehow.
        # happens once a year.
        return self.stronghold.silo.imbue_list(self.get_tile_comps())

    def battle_end_callback(self, atksquad, defsquad, winner, awards,
                            prisoners):
        """ Triggered by Battle when it ends. Dead units/squads should
        have been disbanded before calling this. """
        # Add awards to the silo
        self.stronghold.silo.imbue_list(awards)
        if winner == atksquad:
            # Attempt to capture the field. It will fail if the stronghold
            # is still garrisoned.
            if atksquad:
                self.get_taken_over(atksquad)
        else:
            # Prisoners must be transferred from attacker to defender's
            # stronghold's free units.
            # If prisoners cannot fit they return to where they came from.
            # Highest valued units are captured first, in case they don't fit.
            prisoners = sorted(prisoners, key=attrgetter('value'),
                               reverse=True)
            for u in prisoners:
                try:
                    self.stronghold.add_free_unit(u)
                except ValueError:
                    # We've filled the stronghold
                    break
        # Allow the world to take over if the defender is vacant
        self.check_ungarrisoned()

    """ Special """

    def __eq__(self, other):
        if not isinstance(other, Field):
            return False
        return (other.world == self.world and
                other.world_coord == self.world_coord)

    def __ne__(self, other):
        return not self.__eq__(other)
コード例 #51
0
__author__ = 'Policenaut'

from battle import Battle
import constants
import pygame

screen = pygame.display.set_mode((constants.windowWi, constants.windowHi))

# class Main():
fpsClock = pygame.time.Clock()
battleInst = Battle()



pygame.display.set_caption("Game Sampling!")

# gameRunning = True
#
# while gameRunning:
# 	battleInst.getInputSetValues()
# 	battleInst.updateDisplay()
# 	# Updates display and then sets FPS to 30 FPS.
# 	#print str(fpsClock.get_fps())
# 	pygame.display.update()
# 	fpsClock.tick(30)

pygame.quit()
コード例 #52
0
class Server():

    _poke_cliente = None
    _poke_server  = None
    _battle = None
    _ai = None

    @property
    def poke_cliente(self):
        return self._poke_cliente

    @property
    def poke_server(self):
        return self._poke_server

    @property
    def ai(self):
        return self._ai

    @property
    def battle(self):
        return self._battle

    @poke_cliente.setter
    def poke_cliente(self, value):
        self._poke_cliente = value

    @poke_server.setter
    def poke_server(self, value):
        self._poke_server = value

    @battle.setter
    def battle(self, value):
        self._battle = value

    @ai.setter
    def ai(self, value):
        self._ai = value

    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 compute_attack(self, id):
        
        self.battle.attack(self.poke_cliente, self.poke_server, choice = id - 1)

        print('Oponente escolheu o ataque: ', self.poke_cliente.atks[id - 1].name)

        if self.battle.all_alive(self.poke_cliente, 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_cliente, self.poke_server)
        battle_state = self.poke_cliente.to_XML('<battle_state></battle_state>')
        battle_state = self.poke_server.to_XML(battle_state)

        return battle_state, 200

    from flask import request

    def shutdown_server(self):
        func = request.environ.get('werkzeug.server.shutdown')
        if func is None:
                raise RuntimeError('Not running with the Werkzeug Server')
        func()

    def shutdown(self):
        self.shutdown_server()
        return 'You have been terminated'
コード例 #53
0
class Control:
    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()

        ### BOSS POSITION ###                                ### IN THE FUTURE MOVE TO THE CHARACTERS ###
    def boss_position(self):
        x_pos = random.randint(0, 9)
        y_pos = random.randint(0, 8)

        while self.map.board[y_pos][x_pos] != 1:
            print("wall")
            print("y", y_pos)
            print("x", x_pos)
            x_pos += random.randint(-1, 1)
            y_pos += random.randint(-1, 1)
            #  x_pos = random.randint(0,9)
            #  y_pos = random.randint(0,10)

        self.view.display_boss(x_pos, y_pos)
        self.boss.x_pos = x_pos
        self.boss.y_pos = y_pos

    def boss_move(self):

        x_pos = self.boss.x_pos
        y_pos = self.boss.y_pos

        # while self.map.board[self.boss.y_pos][self.boss.x_pos] == 1 and (x_pos != self.boss.x_pos):
        self.korte = random.randint(1, 4)
        if self.korte == 1:
            self.boss.x_pos += 1
        elif self.korte == 2:
            self.boss.y_pos += 1
        elif self.korte == 3:
            self.boss.x_pos -= 1
        elif self.korte == 4:
            self.boss.y_pos -= 1

        if self.boss.x_pos < 0 or self.boss.y_pos < 0 or self.boss.x_pos > 9 or self.boss.y_pos > 10:
            self.boss.x_pos = x_pos
            self.boss.y_pos = y_pos
            self.boss_move()
            return

        if self.map.board[self.boss.y_pos][self.boss.x_pos] != 1:
            self.boss.x_pos = x_pos
            self.boss.y_pos = y_pos
            self.boss_move()
            return

        self.view.display_floor(72 + x_pos * self.view.size,
                                72 + y_pos * self.view.size)
        self.view.display_boss(self.boss.x_pos, self.boss.y_pos)
        print("BX", self.boss.x_pos)
        print("BY", self.boss.y_pos)
        ### SKELETON NUMBERS AND POSITION ###

    def skeletons_position(self):
        skeleton_numbers = random.randint(2, 5)

        for i in range(skeleton_numbers):
            x_pos = random.randint(0, 9)
            y_pos = random.randint(0, 8)

            while self.map.board[y_pos][x_pos] != 1:
                print("wall")
                print("y", y_pos)
                print("x", x_pos)
                x_pos += random.randint(-1, 1)
                y_pos += random.randint(-1, 1)
            self.view.display_skeleton(x_pos, y_pos)

        ### HERO MOVING ###

    def input_event(self):
        self.view.root.bind('<s>', self.move_down)
        self.view.root.bind('<w>', self.move_up)
        self.view.root.bind('<a>', self.move_left)
        self.view.root.bind('<d>', self.move_right)

    def move_down(self, event):

        if event.char == "s":

            if self.map.board[self.hero.y_pos + 1][
                    self.hero.x_pos] != 1 or self.hero.y_pos == 10:

                print("wall")

            else:
                self.view.display_floor(72 + self.hero.x_pos * self.view.size,
                                        72 + self.hero.y_pos * self.view.size)
                self.hero.y_pos += 1
                self.draw_game_map("down")
                self.battle.fight()
                self.boss_move()
                self.battle.fight()
            #  self.finish_him()

    def move_up(self, event):

        if event.char == "w":

            if self.map.board[self.hero.y_pos -
                              1][self.hero.x_pos] != 1 or self.hero.y_pos == 0:

                print("wall")

            else:
                self.view.display_floor(72 + self.hero.x_pos * self.view.size,
                                        72 + self.hero.y_pos * self.view.size)
                self.hero.y_pos -= 1
                self.draw_game_map("up")
                self.battle.fight()
                self.boss_move()
                self.battle.fight()
            #  self.finish_him()

    def move_left(self, event):

        if event.char == "a":

            if self.map.board[self.hero.y_pos][self.hero.x_pos -
                                               1] != 1 or self.hero.x_pos == 0:

                print("wall")

            else:
                self.view.display_floor(72 + self.hero.x_pos * self.view.size,
                                        72 + self.hero.y_pos * self.view.size)
                self.hero.x_pos -= 1
                self.draw_game_map("left")
                self.battle.fight()
                self.boss_move()
                self.battle.fight()
            #  self.finish_him()

    def move_right(self, event):

        if event.char == "d":

            if self.map.board[self.hero.y_pos][
                    self.hero.x_pos + 1] != 1 or self.hero.x_pos == 11:

                print("wall")

            else:
                self.view.display_floor(72 + self.hero.x_pos * self.view.size,
                                        72 + self.hero.y_pos * self.view.size)
                self.hero.x_pos += 1
                self.draw_game_map("right")
                self.battle.fight()
                self.boss_move()
                self.battle.fight()
            #  self.finish_him()

    def draw_game_map(self, direction):
        if direction == "right":
            self.view.display_hero_right(72 + self.hero.x_pos * self.view.size,
                                         72 + self.hero.y_pos * self.view.size)
        if direction == "down":
            self.view.display_hero_down(72 + self.hero.x_pos * self.view.size,
                                        72 + self.hero.y_pos * self.view.size)
        if direction == "left":
            self.view.display_hero_left(72 + self.hero.x_pos * self.view.size,
                                        72 + self.hero.y_pos * self.view.size)
        if direction == "up":
            self.view.display_hero_up(72 + self.hero.x_pos * self.view.size,
                                      72 + self.hero.y_pos * self.view.size)

            ### END OF HERO MOVING ###

        ### FINISH HIM ###

    def finish_him(self):
        if self.boss.hp <= 0:
            self.view.display_finishhim()
コード例 #54
0
 def launch_battle(self):
     Battle(self).mainloop()
コード例 #55
0
ファイル: main.py プロジェクト: HabibiDev/battle_simulation
from random import randint
from battle import Battle
from models.army import Army

if __name__ == '__main__':

    armies = []
    try:
        calc_army = int(
            input('Enter how many armies are playing (min = 2): \n'))

        if calc_army < 2:
            print('You entered less then 2 armies')
        else:
            for i in range(calc_army):
                calc_squad = int(
                    input('Enter how many squads for Army_{0} (min = 1):\n'.
                          format(i)))
                army = Army(randint(2, calc_squad), i)
                army.create_army()
                army.damage_rank()
                armies.append(army)

            Game = Battle(armies)
            Game.battle_armies()
            print(Game)
    except ValueError:
        print('Wrong input, you must input only number')
コード例 #56
0
import sys
from pokemon import Pokemon
from battle import Battle
from ai import *

poke2 = Pokemon("squirtle")
poke1 = Pokemon("charmander")
ai = AI()
battle = Battle()

active = battle.get_first(poke1, poke2)
while battle.all_alive(poke1, poke2):

    if (active == poke2):
        AI_choice = battle.make_choice(poke2, poke1, ai)
        battle.attack(poke2, poke1, AI_choice)
    else:
        AI_choice = battle.make_choice(poke1, poke2, ai)
        battle.attack(poke1, poke2, AI_choice)

    if (active == poke1): active = poke2
    else: active = poke1