Esempio n. 1
0
	def newbie_adventure():
		print('Welcome to Heartlook,', references.config.name ,'! This is a massive world!')
		time.sleep(2)
		print('Who am I? Oh! My Name is...')
		time.sleep(1.5)
		print("I wouldn't tell you that! Anyways you might want a map!")
		time.sleep(1.5)
		print('Hahaha You will not get one! Ahahaha.')
		time.sleep(4)
		print('But On a Serious Note, I do not have one')
		time.sleep(1.5)
		print('Do I look like a Cartographer? No.')
		time.sleep(1.5)
		print('You picked easy mode, right? I mean that does not matter for this adventure.')
		time.sleep(1)
		print('Okay Bye...')
		print(Back.GREEN + 'Type: Map!' + Style.RESET_ALL)
		cd = input('>> ')
		print(Style.RESET_ALL + "Oh Wait You can't")
		print(cd + " Didn't work")
		print('Oh Well')
		print('Try well... I will take you there myself')
		references.config.locatation = "Heartlook Suburbs"
		references.config.precise_location = "Heartlook Fields"
		time.sleep(2)
		print('I will teach you how to battle!')
		time.sleep(1.5)
		print('The Question is who...')
		time.sleep(1)
		print('OH! I have an idea')
		print('Me...')
		battle.battle(references.battle_ref.fighting.jarzo())
		return
Esempio n. 2
0
def the_wastes(player):
    the_map = mapify('the_wastes_map.txt')
    print_map(the_map)
    x = 15
    y = 15
    while True:
        o_x = x
        o_y = y
        print("\033[H", end="")
        print_map(the_map)
        the_map[y][x] = ' '
        key_pressed = getch()
        if key_pressed == 'w':
            y -= 1
        elif key_pressed == 's':
            y += 1
        elif key_pressed == 'd':
            x += 1
        elif key_pressed == 'a':
            x -= 1
        elif key_pressed == 'l':
            break
        if the_map[y][x] not in ('S', 'L', 'P', '|', '_', 'K', 'A', 'M'):
            the_map[y][x] = 'player'
        elif the_map[y][x] == 'S':
            shop.shop(player)
        elif the_map[y][x] == 'P':
            ai_talk.speak_dude(player)
        elif the_map[y][x] == 'L':
            secret_lib_thing.library()
        elif the_map[y][x] == 'M':
            battle.battle(player)
        else:
            x = o_x
            y = o_y
Esempio n. 3
0
def wich_battle(enemy):
    for possible_enemy in inimigos:
        if int(enemy) == possible_enemy[0]:
            cur_enemy = possible_enemy
            battle.battle(current_session[1], current_session[2],current_session[3], current_session[4],current_session[5], cur_enemy[0], cur_enemy[1], cur_enemy[2], cur_enemy[3], cur_enemy[4], cur_enemy[5], cur_enemy[6])
        else:
            pass
Esempio n. 4
0
def main_menu():

    print(MAIN_MENU_TEXT)
    answer = prompt('\n>> ', '1', '2', '3', '4', '5', '6', 'r', 'R', 'q', 'Q',
                    '')
    if answer is 'q' or answer is 'Q':
        exit(0)
    elif answer is '1':
        gameshop.display()
    elif answer is '2':
        inventory.inv.display_inventory(player)
    elif answer is '3':
        inventory.inv.display_equipment(player)
    elif answer is '4':
        player.display_stats()
    elif answer is '5':
        battle(player, random.choice(low_level_monsters))
    elif answer is '6':
        usersave.save_game()
    elif answer is 'r' or answer is 'R':
        print("Hey, i'm still working on that :/")
        print(
            "Reset your save manually by deleting 'inventory.ini' and 'user_stats.ini' and run the game again"
        )
        prompt()
    main_menu()
Esempio n. 5
0
 def act(self, job):
     if job == 'battle':
         battle(player, characters.enemies[0])
     elif job == 'reload_enemies':
         characters.load_enemies()
         print('DEBUG: enemies reloaded')
     elif job == 'hurt_me':
         player.sethp(5)
Esempio n. 6
0
    def main_map(self, screen, player, assets):
        escape_call = Escape()
        sector_map = IconTree(self.images)
        sector_map.update()
        player_loc = sector_map.root
        alive = True
        win = None
        while alive and win is None:
            screen.blit(self.bg, (0, 0))
            screen.blit(self.legend, (580, 20))
            screen.blit(self.up, self.up_rect)
            screen.blit(self.down, self.down_rect)

            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()
                    break

                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        escape_call.escape_menu(screen)
                        break
                elif event.type == MOUSEBUTTONDOWN:
                    position = pygame.mouse.get_pos()
                    if self.up_rect.collidepoint(
                            position) or self.down_rect.collidepoint(position):
                        sector_map.scroll(screen, player_loc, self.bg,
                                          self.legend, self.up, self.down,
                                          self.up_rect, self.down_rect)
                    for sp in sector_map.sprites():
                        if sp.is_child(player_loc) and sp.collide(position):
                            player_loc = sp
                            if sp.type == 'minion':
                                alive = battle(screen, player, assets,
                                               escape_call)
                            elif sp.type == 'boss':
                                win = battle(screen,
                                             player,
                                             assets,
                                             escape_call,
                                             boss=True)
                            elif sp.type == 'unknown':
                                alive = events(screen, player, assets,
                                               escape_call)
                            elif sp.type == 'repair':
                                repair(screen, player, assets, escape_call)
                            elif sp.type == 'shop':
                                shop(screen, player, assets, escape_call)
                if alive:
                    sector_map.draw(screen, player_loc)
                    pygame.display.update()
            if player.current_health <= 0:
                break
        if not win or player.current_health <= 0:
            game_over(screen)
        if (win):
            game_win(screen)
Esempio n. 7
0
def tutorial():
    print("\n\n***********************")
    print("*******TUTORIAL********")
    print("***********************")

    print("\nO sistema de batalhas é bastante simples: você lutará contra um inimigo por vez até chegar no boss final!")
    print("Lembre-se de planejar bem cada ataque!")
    x = input("Vamos começar com uma batalha de treino!\n(PRESSIONE ENTER)")
    battle.battle("Chico", 40, 5, 5, 5, 0, "Ogro", 20, 3, 3, 1, 0)
Esempio n. 8
0
def colosseum():
    fight = input('Do you seek battle?  (Y/N) ')
    while fight.lower() != 'y' and fight.lower() != 'n':
        fight = input('Do you seek battle?  Input (Y)es or (N)o ')
    if fight.lower() == 'n':
        print('Live to fight another day.')
        import hub
        hub.hub()
    if fight.lower() == 'y':
        import battle
        battle.battle()
Esempio n. 9
0
def boss_battle2(player,inventory):
    print("\nThe mysterious voice says \"You have made the right choice.\" You feel power swelling through you. You grow wings that allow you to fly straight up to the final floor and confront the dragon king.")
    player = TempClass(player.name,1000000,100000,1000000,100000,1000000,player.weapon,player.armor)
    delay = input("\nPress enter to continue...\n")
    print("The Dragon King roars and attacks you.\n")
    dragon = DragonKing()
    enemies = [dragon]
    battle(player,enemies,inventory)
    print("\nYou have defeated the Dragon King! But suddenly the mysterious voice starts laughing. \"Thank you for destroying my greatest rival. With his death, I can finally return, and you will be my vessel.\"")
    delay = input("\nPress enter to continue...\n")
    print("You are covered in smoke and transformed into a demonoid being. You cannot control your body and you watch helplessly as the mysterious entity that stole your body kills the princess.")
    print("It summoned it's demon comrades and together they covered the Earth in darkness. The rule of the demons have come...and it was all your fault. Maybe you should choose better next time. THE END.")
Esempio n. 10
0
def main():
    #召喚
    m1 = monster.Monster(4, 1)
    m2 = monster.Monster(4, 5)
    m3 = monster.Monster(7, 5)
    mons = [m1, m2, m3]
    f1 = fish.Fish(9, 2)  #魚召喚
    p1 = player.Player()
    map1 = field.map()  # map召喚

    #ゲーム全体のモードのコントロール
    mode = 0
    opening.main()
    while True:
        if mode == 0:  #野
            mode, id = field.main(p1, mons, f1, map1)  #フィールドでの流れ
        elif mode == 3:  #街ナカ
            mode = town.main(p1)  #街ナカ
        elif mode == 10:  #バトル
            m1 = mons[id]
            print("モンスター出現!!  hp", m1.hp, " 攻撃力", m1.at, "  防御力", m1.df)
            flag = battle.battle(p1, m1)  #戦闘シーン
            if flag == 1:  #モンスターをやっつけた
                mons.pop(id)
                mode = 0  #野
            elif flag == 2:  #プレイヤが死んだらゲームオーバー
                print("game over")
                return
            elif flag == 3:  #プレイヤが逃げ出した
                mode = 0  #野
Esempio n. 11
0
	def add_battle(self, uid, level = [1,1,1]):
		"""
		添加一场战斗
		id为uid的用户挑战关卡level
		level结构:[场景,关卡,星级]
		"""
		if uid in self.battles:
			print 'user ' + uid + ' already in a battle, have no time to attend another'
			return None
		player_data = world.onlineUsers.get_user(uid)
		if not player_data.test_battle_level(level):
			print 'level not allowed'
			return None
		if not player_data.cost_power(const.power_cost_per_fight):
			return None
		player = player_data.get_battle_user()
		if level[0] < 0:
			return None
		else:
			computer = world.all_fences.get_guard(level[0], level[1], level[2])
		if not player:
			return None
		if not computer:
			return None

		battle1 = battle.battle(player, computer)
		self.battles[uid] = battle1
		battle1.set_level(level)
		return battle1
Esempio n. 12
0
def beggar_city(player):
    the_map = mapify('beggar_city.txt')
    print_map(the_map)
    x = 15
    y = 15
    while True:
        o_x = x
        o_y = y
        print("\033[H", end="")
        print_map(the_map)
        the_map[y][x] = ' '
        key_pressed = getch()
        if key_pressed == 'w':
            y -= 1
        elif key_pressed == 's':
            y += 1
        elif key_pressed == 'd':
            x += 1
        elif key_pressed == 'a':
            x -= 1
        elif key_pressed == 'l':
            break
        if the_map[y][x] not in ('S', 'L', 'P', '|', '_', 'K', 'A', 'M', 'B',
                                 'G', 'Z', 'Q', 'D', 'x'):
            the_map[y][x] = 'player'
        elif the_map[y][x] == 'S':
            shop.shop(player)
        elif the_map[y][x] == 'P':
            ai_talk.speak_dude(player)
        elif the_map[y][x] == 'L':
            secret_lib_thing.library()
        elif the_map[y][x] == 'M':
            battle.battle(player)
        elif the_map[y][x] == 'D':
            multi_battle.duck_fight(player)
        elif the_map[y][x] == 'B':
            ai_talk.mega_rat(player)
        elif the_map[y][x] == 'Z':
            ai_talk.farlands(player)
        elif the_map[y][x] == 'x':
            boss_fight.gate_keeper(player)

        else:
            x = o_x
            y = o_y
Esempio n. 13
0
    def story(self):
        if self.done == False:
            self.done = True
            print """
	Você continua pelo corredor.
	Mais próximo da sala, você sente um fedor estranho.
	A sala, iluminada por duas tochas, não parecia muito grande.
	Mas havia algo estranho ali. Algo vivo. Seria outra pessoa?
	"""
            raw_input("Pressione ENTER para continuar.")

            print """
	Ao entrar, você vê quatro pontes de madeira
	que se ligam ao centro da sala.
	Embaixo de tudo, há uma gosma negra, borbulhando.
	Seu estômago embrulhado não te deixa perceber que algo se aproxima.
	"""

            raw_input("Pressione ENTER para continuar.")

            print """
	Uma sombra cobre sua visão e te joga para o meio da sala.
	Tirando a espada da bainha, você finalmente vê,
	mas ainda não consegue definir.
	Sombra, gosma? Será que é possível acertar algo assim?
	"""

            raw_input("Pressione ENTER para continuar.")

            battle(
                Party([monsters.nightmare, monsters.empada, monsters.goblin],
                      "monster"))

            print """
	Cansado, você levanta os olhos e olha para a forma desforma
	no chão. Você ainda não entende o que era aquilo.
	Não importa. Agora está morto.
	"""

            return menu.menu(self)
        else:
            return menu.menu(self)
Esempio n. 14
0
 def __init__(self, images, screen, clock, iFace, FX, iH, titleScreen, SFX, myWorldBall,
              loadTicker=None, loadHero=None, loadWorld=None, loadDirector=None):
     self.Display = display.Display(screen, images)
     self.FX = FX
     self.SFX = SFX
     if loadTicker is None:
         self.Ticker = ticker.Ticker()
     else: self.Ticker = loadTicker
     if loadDirector is None:
         self.Director = director.Director()
     else: self.Director = loadDirector
     self.myMenu = menu.menu(screen, iH, self.Display, iFace, FX, SFX)
     #self.levelDepth = levelDepth
     self.inputHandler = iH
     
     FX.displayLoadingMessage(titleScreen, 'Loading world...')
     # myWorldBall is the game world which always is loaded
     # loadWorld is the levels which have been generated ingame and saved
     self.myMap = None
     if loadWorld is None:
         self.myWorld = world.World('game', myWorldBall)
         self.myMap = self.myWorld.initialMap
         self.myWorld.currentMap = self.myMap
         (x, y) = self.myMap.heroStart
         self.myHero = hero.hero(loadHero,
                             (x*const.blocksize,
                             y*const.blocksize)                               
                             )
     else:
         self.myWorld = world.World('game', myWorldBall, loadWorld)
         self.myMap = self.myWorld.currentMap
         self.myHero = hero.hero(loadHero)
     
     FX.displayLoadingMessage(titleScreen, 'Loading game engine...')
     self.NPCs = []
     self.screen = screen
     self.gameBoard = pygame.Surface( [300,300] )
     
     #self.gameBoard = self.gameBoard.convert(32)
             
     #this is true while player is in a particular game
     self.gameOn = True
     self.DIM = const.DIM
                     
     self.myInterface = iFace
     self.addShops()
     self.addNPCs(self.myMap)
     
     self.myBattle = battle.battle(self.screen, iH, self.myMenu)
     self.clock = clock
     
     self.inputHandler = iH
     self.state = 'overworld'
     self.won = False
Esempio n. 15
0
def main():
    starters = set_starters()
    #starter_pokemon = starters[0]
    player = create_trainer()
    wild_pokemon_list = set_wild_pokemon()
    for pkm in wild_pokemon_list:
        print pkm.get_pokemon_full_stats()
    wild_pokemon = random_pokemon_from_list(wild_pokemon_list)

    #print "\ninventory dict:"
    #for key in test_inv_dict.keys():
    #    print "{}: {}\n".format(key, test_inv_dict[key])
    #inv = inventory(inv_dict=test_inv_dict)
    #inv.set_owner(player)
    #print "\n inventory instance:"
    #print inv.get_pocket_contents(pocket=constants.item_type_general)
    #print inv.get_pocket_contents(pocket=constants.item_type_medicine)
    #print inv.get_pocket_contents(pocket=constants.item_type_berry)
    #print inv.get_pocket_contents(pocket=constants.item_type_key_item)
    #print inv.get_pocket_contents(pocket=constants.item_type_poke_ball)
    #print inv.use_item_by_name(item_name='poke ball')
    #print inv.get_pocket_contents()
    #petc()
    clear()
    test_name = "--- Wild Pokemon Battle Using Interfaces ---\n"
    cmd_console = cmd_interface()
    wild_battle = battle()

    print test_name

    starter_pokemon = cmd_console.choose_pokemon_from_list(starters)

    #cmd_console.rename_pokemon(starter_pokemon)
    #clear()
    player.capture_pokemon(starter_pokemon)
    print player.get_trainer_card()
    print player.show_party()
    print player.pokedex.get_pokedex_entries()
    #print player.get_pack()
    #

    print "Will Encounter {}".format(wild_pokemon.name)
    #
    print "Entering the Field"
    #petc()
    #cmd_console.enter_wild_battle(trainer_1=player, wild_pokemon=wild_pokemon)
    wild_battle.wild_pokemon_battle(trainer_1=player,
                                    wild_pokemon=wild_pokemon)
    print "Leaving the Field"
    petc()
    print player.get_trainer_card()
    print player.show_party()
    print player.pokedex.get_pokedex_entries()
Esempio n. 16
0
def main():
    starters = set_starters()
    #starter_pokemon = starters[0]
    player = create_trainer()
    wild_pokemon_list = set_wild_pokemon()
    for pkm in wild_pokemon_list:
        print pkm.get_pokemon_full_stats()
    wild_pokemon = random_pokemon_from_list(wild_pokemon_list)

    #print "\ninventory dict:"
    #for key in test_inv_dict.keys():
    #    print "{}: {}\n".format(key, test_inv_dict[key])
    #inv = inventory(inv_dict=test_inv_dict)
    #inv.set_owner(player)
    #print "\n inventory instance:"
    #print inv.get_pocket_contents(pocket=constants.item_type_general)
    #print inv.get_pocket_contents(pocket=constants.item_type_medicine)
    #print inv.get_pocket_contents(pocket=constants.item_type_berry)
    #print inv.get_pocket_contents(pocket=constants.item_type_key_item)
    #print inv.get_pocket_contents(pocket=constants.item_type_poke_ball)
    #print inv.use_item_by_name(item_name='poke ball')
    #print inv.get_pocket_contents()
    #petc()
    clear()
    test_name = "--- Wild Pokemon Battle Using Interfaces ---\n"
    cmd_console = cmd_interface()
    wild_battle = battle()
    
    print test_name      
    
    starter_pokemon = cmd_console.choose_pokemon_from_list(starters)
    
    #cmd_console.rename_pokemon(starter_pokemon)
    #clear()
    player.capture_pokemon(starter_pokemon)
    print player.get_trainer_card()
    print player.show_party()
    print player.pokedex.get_pokedex_entries()
    #print player.get_pack()
    #
    
    print "Will Encounter {}".format(wild_pokemon.name)
    #
    print "Entering the Field"
    #petc()
    #cmd_console.enter_wild_battle(trainer_1=player, wild_pokemon=wild_pokemon)
    wild_battle.wild_pokemon_battle(trainer_1=player, wild_pokemon=wild_pokemon)
    print "Leaving the Field"
    petc()
    print player.get_trainer_card()
    print player.show_party()
    print player.pokedex.get_pokedex_entries()
Esempio n. 17
0
def main():
    player_1 = create_trainer_1()
    player_2 = create_trainer_2()
    pkm1_1 = pokemon(gd=bulbasaur_d)._randomize_vital_statistics(
        set_level=5, gender=constants.male).set_nickname("Bulba")
    pkm1_2 = pokemon(gd=charmander_d)._randomize_vital_statistics(
        set_level=5, gender=constants.female).set_nickname("Char Char")
    pkm1_3 = pokemon(gd=squirtle_d)._randomize_vital_statistics(
        set_level=5, gender=constants.male).set_nickname("Squirts")

    pkm2_1 = pokemon(gd=bulbasaur_d)._randomize_vital_statistics(
        set_level=5, gender=constants.female).set_nickname("Saura")
    pkm2_2 = pokemon(gd=charmander_d)._randomize_vital_statistics(
        set_level=5, gender=constants.male).set_nickname("Ander")
    pkm2_3 = pokemon(gd=squirtle_d)._randomize_vital_statistics(
        set_level=5, gender=constants.female).set_nickname("Turts")

    player_1.capture_pokemon(pkm1_1)
    player_1.capture_pokemon(pkm1_2)
    player_1.capture_pokemon(pkm1_3)

    player_2.capture_pokemon(pkm2_1)
    player_2.capture_pokemon(pkm2_2)
    player_2.capture_pokemon(pkm2_3)
    clear()
    test_name = "--- Trainer Battle Using Interfaces ---\n"
    cmd_console = cmd_interface()
    trainer_battle = battle()
    #
    print test_name
    print player_1.get_trainer_card()
    print player_1.show_party()
    print player_2.get_trainer_card()
    print player_2.show_party()
    #
    print "Entering the field."
    petc()
    print trainer_battle.wild_pokemon_battle(
        trainer_1=player_1,
        wild_pokemon=random_pokemon_from_list(set_wild_pokemon()))
    print "Leaving the field."
    player_1.fully_heal_all_party_members
    print "Entering the arena."
    petc()
    print trainer_battle.trainer_pokemon_battle(trainer_1=player_1,
                                                trainer_2=player_2)
    print "Leaving the arena."
    petc()
    print player_1.get_trainer_card()
    print player_1.show_party()
    print player_2.get_trainer_card()
    print player_2.show_party()
Esempio n. 18
0
def battle_packet_handler(data, player_data):
    if data[0] == 1:
        q = storage.sql("select battle_data from last_battle where id=?",
                        (player_data["id"], ))
        return bytearray(q[0]["battle_data"])

    print(data)
    rnd_items_1 = []
    rnd_items_2 = []
    for i in range(0, 8):
        rnd_items_1.append(random.choice(list(items.ITEM_CLASSES.keys())))
    for i in range(0, 8):
        rnd_items_2.append(random.choice(list(items.ITEM_CLASSES.keys())))
    rnd_state = {
        "species": random.choice(list(resources.MON_DATA.keys())),
        "mon_name": "Shadow",
        "moves": ["SCRATCH"],
        "name": "X",
        "items": rnd_items_1
    }

    attacking_player = json.loads(player_data["mon"])
    defending_player = trainerloader.load_trainer(data[2] * 256 + data[1])

    b = battle.battle(attacking_player, defending_player)

    r = bytearray(
        bytes(defending_player["items"]) +  # attacker items
        bytes(attacking_player["items"]) +  # defender items
        bytes([defending_player["class_id"]]) +  # trainer class id
        bytes(util.bcd(defending_player["bp_reward"])) +  # bp reward
        bytes(util.bcd(defending_player["credits_reward"])) +  # credit reward
        bytes([
            resources.MON_DATA[attacking_player["species"]]["mon_numeric_id"]
        ]) +  # attacker species id
        bytes([
            resources.MON_DATA[defending_player["species"]]["mon_numeric_id"]
        ]) +  # defender species id
        bytes(util.parse_text(defending_player["name"], 21)) +  # defender name
        b.log_bytes()  # offset to stringbuf, battle data, stringbuf
    )
    print(r)

    storage.sql(
        """
        update last_battle set battle_data=? where id=?
    """, (r, player_data["id"]))

    return r
def random_battle(player,inventory):
    enemy_count = random.randrange(2,5)
    enemies = []
    for x in range (0,enemy_count):
        s = random.randrange(0,3)
        if s == 0:
            goblin = Goblin()
            enemies.append(goblin)
        elif s == 1:
            bat = Bat()
            enemies.append(bat)
        elif s == 2:
            skeleton = Skeleton()
            enemies.append(skeleton)
    return battle(player,enemies,inventory)
Esempio n. 20
0
    def attack(self, world):
        if world.turn != 0:
            self.allocate_armies(world)
        attack_priority = self.define_priorities(world)
        for a in attack_priority:
            attacker = self.my_countries[a[0]]
            if attacker.army > 1:
                defender = world.countries[a[1]]
                # Attack until winning or exhausting army
                a, d = battle.battle(attacker, defender)
                if d == 0:
                    temp_defender = defender.owner
                    defender.owner.remove_country(world, defender)
                    # Check number of armies to pass
                    if a > 4:
                        self.add_country(world, defender, a - 3)
                        attacker.army -= a - 3
                    else:
                        self.add_country(world, defender, a - 1)
                        attacker.army -= a - 1

                    # Check if loser is done
                    if len(temp_defender.my_countries) == 0:
                        temp_defender.playing = False
                        if world.log:
                            world.log.info(
                                f'{temp_defender.name} is out of the game')
                        # Checking if 'destroy' objective is done immediately at every successful attack
                        if attacker.owner.goal.enemy == temp_defender.name:
                            world.winner = attacker.owner
                            world.on = False
                            if world.log:
                                arms = sum([
                                    c.army for c in
                                    attacker.owner.my_countries.values()
                                ])
                                world.log.info(
                                    f"{attacker.owner.name.capitalize()} is the WINNER, with {arms} armies, "
                                    f"goal: '{attacker.owner.goal.type}' "
                                    f"and enemy {attacker.owner.goal.enemy} "
                                    f"with strategy {attacker.owner.strategy}")
                            return
                    if self.strategy == 'minimalist':
                        return
                else:
                    attacker.army = a
                    defender.army = d
def main():
    player_1 = create_trainer_1()
    player_2 = create_trainer_2()
    pkm1_1 = pokemon(gd=bulbasaur_d)._randomize_vital_statistics(set_level=5, gender=constants.male).set_nickname("Bulba")
    pkm1_2 = pokemon(gd=charmander_d)._randomize_vital_statistics(set_level=5, gender=constants.female).set_nickname("Char Char")
    pkm1_3 = pokemon(gd=squirtle_d)._randomize_vital_statistics(set_level=5, gender=constants.male).set_nickname("Squirts")

    pkm2_1 = pokemon(gd=bulbasaur_d)._randomize_vital_statistics(set_level=5, gender=constants.female).set_nickname("Saura")
    pkm2_2 = pokemon(gd=charmander_d)._randomize_vital_statistics(set_level=5, gender=constants.male).set_nickname("Ander")
    pkm2_3 = pokemon(gd=squirtle_d)._randomize_vital_statistics(set_level=5, gender=constants.female).set_nickname("Turts")

    player_1.capture_pokemon(pkm1_1)
    player_1.capture_pokemon(pkm1_2)
    player_1.capture_pokemon(pkm1_3)

    player_2.capture_pokemon(pkm2_1)
    player_2.capture_pokemon(pkm2_2)
    player_2.capture_pokemon(pkm2_3)
    clear()
    test_name = "--- Trainer Battle Using Interfaces ---\n"
    cmd_console = cmd_interface()
    trainer_battle = battle()
    #
    print test_name      
    print player_1.get_trainer_card()
    print player_1.show_party()
    print player_2.get_trainer_card()
    print player_2.show_party()
    #
    print "Entering the field."
    petc()
    print trainer_battle.wild_pokemon_battle(trainer_1=player_1, wild_pokemon=random_pokemon_from_list(set_wild_pokemon()))
    print "Leaving the field."
    player_1.fully_heal_all_party_members
    print "Entering the arena."
    petc()
    print trainer_battle.trainer_pokemon_battle(trainer_1=player_1, trainer_2=player_2)
    print "Leaving the arena."
    petc()
    print player_1.get_trainer_card()
    print player_1.show_party()
    print player_2.get_trainer_card()
    print player_2.show_party()
Esempio n. 22
0
def main():
    status = ''
    while status != "dead":
        try:
            print('What do you want to do?')
            select = selection(["Battle", "Shop", "Inventory"], 0)
            if select[1] == 'Battle':
                print('You go to battle!')
                status = battle(hero)
            elif select[1] == 'Shop':
                print('You go to the shop!')
                wgi = shop(hero.gold, hero.inventory, hero)
                hero.gold = wgi[0]
                hero.inventory = wgi[1]
            elif select[1] == 'Inventory':
                wgi = inventory(hero.equipped_weapon, hero.gold, hero.inventory, hero)
                hero.equipped_weapon = wgi[0]
                hero.gold = wgi[1]
                hero.inventory = wgi[2]
            else:
                print("Invalid input %r" % select[1])
        except:
            print("Invalid input")
Esempio n. 23
0
    def battle(self, enemy):
        # A battle between the player and the enemy party needs resolving
        if enemy != self.user:
            self.dx = 0
            self.dy = 0
            if battle.battle(self.user, enemy, self.my_win, self.world.name, self.fullscreen):
                if self.world.name == "nott_interior":
                    self.world.remove_party(enemy)
                    self.prompt = game_won((self.my_win.get_width(), self.my_win.get_height()))
                    self.in_prompt = True
                else:
                    self.world.remove_party(enemy)
                    self.prompt = battle_won((self.my_win.get_width(), self.my_win.get_height()))
                    self.in_prompt = True
            else:
                self.world.remove_party(self.user)
                self.prompt = death((self.my_win.get_width(), self.my_win.get_height()))
                self.in_prompt = True

            self.enemy_sound.play(0, 500)

        self.init_screen()
        self.init_camera()
Esempio n. 24
0
def boss_battle(player,inventory):
    print("Ignoring the voice, you enter the first floor of the castle and encounter the fat Goblin King. He yells  YOU SHALL NOT PASS and engages you in batle.\n")
    enemies = []
    #Goblin King Fight
    for x in range(0,4):
        goblin = Goblin()
        enemies.append(goblin)
    goblin_king = Goblin("Goblin King",500, 500, 30, 10)
    enemies.append(goblin_king)
    battle(player,enemies,inventory)
    if player.hp <= 0:
        return
    print("After slaying the Goblin King, you find in his treasure room an old stone sword. This is the sword of legend, Excalibur. However its true power will be revealed after you obtain the ancient armor.\n")
    delay = input("Press enter to continue...\n")
    print("You proceed to the second floor. The moment you step through the door to the Skeleton King's room, him and his minions launch themselves at you.\n")
    #Skeleton King Fight
    for x in range(0,4):
        skeleton = Skeleton()
        enemies.append(skeleton)
    skeleton_king = Goblin("Skeleton King",500, 500, 30, 10)
    enemies.append(skeleton_king)
    battle(player,enemies,inventory)
    if player.hp <= 0:
        return
    print("The Skeleton King has been slain and you take the Artifact Armor, off his dead body. The armor and Excalibur both glow in a blinding light. Their power has been restored! Put them on and proceed to the last floor.\n")
    delay = input("Press enter to continue...\n")
    excalibur = Excalibur()
    af_armor = ArtifactArmor()
    player.equip_weapon(excalibur,inventory)
    player.equip_armor(af_armor,inventory)
    #Dragon King Fight
    print("\nYou have reached the final floor! The dragon compliments you on reaching this far. He unleashes a loud roar and charges.\n")
    dragon = DragonKing()
    enemies.append(dragon)
    battle(player,enemies,inventory)
    if player.hp <= 0:
        return
    print("Congratulations! You beat the dragon king! You saved the princess and she falls in love with you and marries and yada yada yada. You live happily ever after. The end!\n")
Esempio n. 25
0
def checkBoard(check, player, eventCards, deck, turn, player1, player2) :
  event = eventCards
  enemy = player2
  if check[1] == ['I'] :
    print ('get 1 item card') 
    player.draw(deck)
  elif check[1] == ['E'] :
    item = 0
    event, item = eventCard.eventCard(player, event, player2, deck, turn)
    if item == 1 :
      player.draw(deck)
    elif item == 2 :
      player.draw(deck)
      player.draw(deck)
  elif check[1] == ['W'] :
    print ('Warp portal')
    print ('1. go to warp portal [P12]')
    print ('2. go to warp portal [J2]')
    print ('3. go to warp portal [A6]')
    print ('4. go to warp portal [G9]')
    print ('5. go to warp portal [H3]')
    print ('6. Do not warp')
    number = player.chooseWarp(player2)
    if number == 1 :
      print ('You are going to the warp portal [P12]')
      player.position = 17
    elif number == 2 :
      print ('You are going to the warp portal [J2]')
      player.position = 39
    elif number == 3 :
      print ('You are going to the warp portal [A6]')
      player.position = 56
    elif number == 4 :
      print ('You are going to the warp portal [G9]')
      player.position = 65
    elif number == 5 :
      print ('You are going to the warp portal [H3]')
      player.position = 91
    elif number == 6 :
      print ('Do not warp')
  elif check[1] == ['B'] :
    print ('Do you want to battle ?')
    print ('1.Battle')
    print ('2.No battle')
    choose = player.chooseBattle(enemy)
    if choose == 1 :
      print ('## Battle ##')
      battle.battle(player, player2, turn)
    else :
      print ('No Battle')
  elif check[1] == ['P'] :
    priestCastle(player)
  elif check[1] == ['M'] :
    magicSchool(player, enemy, deck)
  elif check[1] == ['D'] :
    demonCastle(player, enemy, deck)
  elif check[1] == ['F'] :
    factoryCastle(player, deck)
  elif check[1] == ['S'] :
    swordCastle(player, deck)
  elif check[1] == ['4'] :
    player.hp = player.hp - 4
    print ('Player HP - 4 =', player.hp)
  elif check[1] == ['3'] :
    player.hp = player.hp - 3
    print ('Player HP - 3 =', player.hp)
  elif check[1] == ['2'] :
    player.hp = player.hp  - 2
    print ('Player HP - 2 =', player.hp)
  elif check[1] == ['1'] :
    player.hp = player.hp - 1
    print ('Player HP - 1 =', player.hp)
  return event
Esempio n. 26
0
def run(key):
    global player_x
    global player_y

    # Handle the new keypress
    process_input(key)

    # Draw the title screen
    if constants.game_state['mode'] == 'menu':
        engine.draw_buf(title.data, (0, 0))
        constants.game_state['mode'] = 'intro'

    # Play the intro cutscene
    elif constants.game_state['mode'] == 'intro':
        # Draw a text box
        engine.draw_text_box(
            0,
            0,
            79,
            4,
            text=
            "       -- W E L C O M E   T O   P O R K   A N D   A D V E N T U R E! --       \n"
            "             wasd to move, space to select, e for inventory.                  \n"
            "                         Press space to continue",
            fill=True,
            delay=0.02)
        constants.game_state['mode'] = 'main'

    # Map movement
    elif constants.game_state['mode'] == 'main':
        # Draw Maps
        collision = enemy.check_collision((player_y, player_x))
        if type(collision) is int:
            engine.draw_buf(battlescreen.data)
            constants.game_state['mode'] = 'battle_transition'
            battle.start_battle(collision)
        else:
            engine.draw_enemies(enemy.enemies)
            engine.draw_buf(maze.maze, (0, 1))
            engine.plot(constants.PLAYER_CHAR,
                        (1 + player_y, 3 + 2 * player_x))
            enemy.move_enemies()

    # Disable input in first frame of battle
    elif constants.game_state['mode'] == 'battle_transition':
        battle.battle()
        constants.game_state['mode'] = 'battle'

    # Battle scene
    elif constants.game_state['mode'] == 'battle':
        battle.battle()

    # Screen when you win the battle
    elif constants.game_state['mode'] == 'win_screen':
        constants.game_state['mode'] = 'main'

        # Won the floor!
        if len(enemy.enemies) == 0:
            # Reset everything
            constants.game_state['mode'] = 'next_floor'
            constants.game_state['level'] += 1
            maze.regen_maze((4, 4))
            enemy.enemies = enemy.generate_enemies()
            player_x = 0
            player_y = 0

    # Levelup screen
    elif constants.game_state['mode'] == 'next_floor':
        engine.draw_buf(levelup.data)
        constants.game_state['mode'] = 'main'

    # You succ lol
    elif constants.game_state['mode'] == 'lose_screen':
        engine.draw_text_box(
            0,
            0,
            79,
            4,
            text="                             B O O   Y O U   D I E D")

    # Don't run away boo
    elif constants.game_state['mode'] == 'run_screen':
        engine.draw_text_box(
            0,
            0,
            79,
            4,
            text="                              ran away successfully!")
        constants.game_state['mode'] = 'main'

    # Bag state
    elif constants.game_state['mode'] == 'bag':
        inventory.draw_inventory()

    # Draw the screen to the terminal
    engine.draw()
Esempio n. 27
0
import UI
import train
import battle
import replay

if __name__ == "__main__":
    tau = {}
    while True:
        choice = UI.showMenu()
        if choice == 0:  #訓練模式
            tau = train.train(tau)
        elif choice == 1:  #對戰模式
            battle.battle(tau)
        elif choice == 2:  #重播模式(輸入完整檔名,重播比賽過程)
            replay.replay()
        elif choice == 3:  #退出程式
            break
Esempio n. 28
0
        pass


if __name__ == '__main__':
    """Main loop.
    User has the option to change equipment, fight a monster, or exit
    the program.
    """

    print(f'\nAre you ready for adventure, {characters.hero.name}? '
          'How will you proceed?')

    prompt = '\n1. EQUIP - Change your character\'s equipment'
    prompt += '\n2. FIGHT - Do battle with an enemy'
    prompt += '\n3. EXIT - Exit the program\n\t'

    # Main Menu
    # Will loop indefinitely until user chooses to EXIT
    menu = True
    while menu == True:
        message = input(prompt)

        if message.upper() == 'EQUIP' or message == '1':
            change_equip()
        elif message.upper() == 'FIGHT' or message == '2':
            battle.battle()
        elif message.upper() == 'EXIT' or message == '3':
            print('Thank you for playing. Good bye!\n')
            menu = False
        else:
            print('Please choose one of the available options.')
Esempio n. 29
0
from Ogre import Ogre
from Okabe import Okabe
from Simon import Simon
from Link import Link
from battle import battle

ogre = Ogre()
okabe = Okabe()
simon = Simon()
link = Link()

battle([okabe,simon,link],[ogre])
Esempio n. 30
0
def iron_clan(player):
    the_map = mapify('iron_clan.txt')
    print_map(the_map)
    x = 15
    y = 15
    while True:
        o_x = x
        o_y = y
        print("\033[H", end="")
        print_map(the_map)
        the_map[y][x] = ' '
        key_pressed = getch()
        if key_pressed == 'w':
            y -= 1
        elif key_pressed == 's':
            y += 1
        elif key_pressed == 'd':
            x += 1
        elif key_pressed == 'a':
            x -= 1
        elif key_pressed == 'l':
            break
        if the_map[y][x] not in ('U', 'S', 'L', 'P', '|', '_', 'K', 'A', 'M',
                                 'B', 'G', 'Z', 'Q', 'D', 'x', 'R'):
            the_map[y][x] = 'player'
        elif the_map[y][x] == 'S':
            shop.shop(player)
        elif the_map[y][x] == 'P':
            ai_talk.speak_dude(player)
        elif the_map[y][x] == 'L':
            secret_lib_thing.library()
        elif the_map[y][x] == 'M':
            battle.battle(player)
        elif the_map[y][x] == 'D':
            multi_battle.duck_fight(player)
        elif the_map[y][x] == 'B':
            ai_talk.mega_rat(player)
        elif the_map[y][x] == 'U':
            ai_talk.ultra_thorg(player)
        elif the_map[y][x] == 'G':
            battle.monster_guard(player)
        elif the_map[y][x] == 'R':
            baba = random.randint(1, 2)
            if baba == 1:
                util.s_print(
                    "Ohno! It wasn't an octopus it was a Raider in disguise!")
                battle.yeckity_toe(player)
            else:
                util.s_print("Ohno! A wild octopus attacks!")
                damage = random.randint(1, 8)
                octo_damage = damage * 8
                util.s_print("The wild octopus attacks and deals " +
                             str(octo_damage) + " damage!")
                player['life'] -= octo_damage
                if player['life'] <= 0:
                    util.s_print("You were killed by a savage octopus")
                else:
                    util.s_print("You vicously strike the octopus with your " +
                                 player['main_weapon'] + " and kill it")
                    player['kills'].append("Wild Octopus")
                    player['weapons'].append("Octopus")
                    util.s_print("You got a new weapon: Octopus")
                    util.s_print(
                        "Note: Octopus and some other specialty weapons cannot be used against bosses"
                    )

        else:
            x = o_x
            y = o_y
Esempio n. 31
0
File: mana.py Progetto: keis/game
uis = [UI(p) for p in players]

def turns():
	while True:
		for p,u in zip(players,uis):
			yield p,u
turns = turns()

for t in turns:
	player,ui = t
	ui.active = True
	print "it is now %s's turn" % player
	#hook_db.dump()
	hook_db.run_hook(None, 'start-of-turn', player)

	while ui.input() != False: pass

	for p in players:
		battles = [x for x in p.core.network() if x.is_battle_zone()]
		if len(battles) > 0:
			for x in battles:
				print 'battle @ %s' % x
				battle.battle(x)
		else:
			print "no battles in %s territory" % p

	player.build_pool()
	player.focus()
	hook_db.run_hook(None, 'end-of-turn', player)
	ui.active = False
Esempio n. 32
0
def game_loop():
    screen = settings.screen
    b_surf = screen.subsurface((5, 200), (400, 275))
    p_surf = screen.subsurface((5, 5), (350, 190))
    m_surf = screen.subsurface((360, 5), (240, 120))
    pet_surf = screen.subsurface((360, 130), (240, 65))
    fashu_surf = screen.subsurface((410, 200), (190, 100))
    count_surf = screen.subsurface((410, 305), (190, 170))
    toolbar_surf = screen.subsurface((605, 5), (190, 470))
    cangku_surf = screen.subsurface((5, 5), (595, 470))
    pet_cangku_surf = screen.subsurface((5, 5), (595, 470))
    hecheng_surf = screen.subsurface((5, 5), (595, 470))
    ronghe_surf = screen.subsurface((5, 5), (595, 470))
    fuwen_surf = screen.subsurface((5, 5), (595, 470))
    lianbao_surf = screen.subsurface((5, 5), (595, 470))
    xiulian_surf = screen.subsurface((5, 5), (790, 470))
    set_surf = screen.subsurface((5, 5), (790, 470))
    show_equip_surf = screen.subsurface((5, 5), (790, 470))
    player_detail_surf = screen.subsurface((5, 5), (790, 470))
    login_surf = screen.subsurface((5, 5), (790, 470))
    ditu = settings.ditu
    if settings.use_load:
        if settings.link_load:
            screen.blit(waiting_pic, (0, 0))
            pygame.display.update()
            url_data = link.load_online()
            if url_data:
                a_p, time_n, battle_n, use_money = url_data
                p = a_p
            else:
                settings.game_stage = 'start'
                settings.use_load = False
                settings.link_load = False
                return
        else:
            p = save.load()
        settings.battle_set = p.battle_set.copy()
        p.game_version = settings.VERSION
        p.enemys = []
        p.attack_all = []
        p.attacking = None
        p.defending = None
        p.jisuan_shuxin()
        if str(p.place.__class__) == 'codes.place.Fuben':
            place.change_place(place.changan, p)
            settings.in_fuben = False
        if p.place.name == u'\u901a\u5929\u5854':
            place.change_place(place.changan, p)
            settings.in_ttt = False
        if settings.link_load:
            if p.place.name != u'\u957f\u5b89':
                for i in range(battle_n):
                    battle.battle(p)

            functions.msg(u'\u53d6\u56de\u6210\u529f\uff0c\u6302\u673a\u65f6\u957f' + link.count_guaji_time(time_n), settings.FPS * 10)
            functions.msg(u'\u6263\u9664\u70b9\u6570\uff1a%s \u70b9' % unicode(use_money), settings.FPS * 10)
            settings.bc_base_time -= time_n
    else:
        if settings.rw_select[3] == u'\u4eba\u65cf':
            p = player.Zhongzu_Ren(settings.rw_select)
        elif settings.rw_select[3] == u'\u9b54\u65cf':
            p = player.Zhongzu_Mo(settings.rw_select)
        else:
            p = player.Zhongzu_Xian(settings.rw_select)
        with file('yourname.txt', 'r') as f:
            name = unicode(f.readline(), 'gbk')[:10].strip()
            if name != u'':
                p.name = name
        p.place = place.Place(place.place_data_list[0])
        w = equip.Weapon(equip.weapon_list_0[random.randint(0, 11)])
        while w.type not in p.adept_weapons:
            w = equip.Weapon(equip.weapon_list_0[random.randint(0, 11)])

        w.get_pr()
        w.get(p)
        w.equip()
        for i in range(15):
            ch = random.choice(random.choice(p.place.spoils))
            exec 'e = equip.%s(ch)' % settings.equip_list[ch[1]]
            e.get_pr()
            e.get(p)
            e.equip()

        cl_list = ['shuiyuezhi',
         'liuyanhuo',
         'xuanminshi',
         'honglianshengquan',
         'zichengtie',
         'xuanyebin',
         'cangleijinshi',
         'bixinsha']
        random.shuffle(cl_list)
        cl_use = cl_list[:4]
        for i in cl_use:
            cl = fabao.Fabao_Cailiao(i)
            cl.get(p)

        pet = monster.Pet(monster.monsters_dict['yefendanqi'], p)
        p.pet_bag.append(pet)
        pet = monster.Pet(monster.monsters_dict['boji'], p)
        p.pet_bag.append(pet)
        p.add_kucun_exp(10000)
        if settings.TEST:
            p.add_exp(5000000000L)
            p.money = enc.en(5000000000L)
            p.shengli = enc.en(100000)
            p.get_skill('weiguanzhidao')
            p.get_skill('xunshouzhidao')
            for i in range(4):
                g = goods.BB_Skill_Forget_Book()
                g.get(p)

            g = goods.MoonStone()
            g.get(p)
            for i in range(2):
                fw = goods.Fuwen_suipian()
                fw.get(p)

            for i in range(60):
                pet = monster.Pet(monster.monsters_dict[random.choice(p.place.monsters)], p)
                p.pet_bag.append(pet)

    draw_init.draw_init(p)
    if settings.battle_set['4beijiasu']:
        pygame.time.set_timer(settings.EVT_BATTLE, settings.TIME_BATTLE_SHORT)
    else:
        pygame.time.set_timer(settings.EVT_BATTLE, settings.TIME_BATTLE)
    pygame.time.set_timer(EVT_SAVE, TIME_SAVE)
    pygame.time.set_timer(EVT_SAVE_2, TIME_SAVE_2)
    b_surf.blit(settings.b_surf_init, (0, 0))
    settings.bt_surf = b_surf.copy()
    while settings.game_stage == 'game':
        for event in gui.setEvents(pygame.event.get()):
            if event.type == QUIT:
                pygame.quit()
                exit()
            if event.type == MOUSEBUTTONUP:
                settings.mouse.click = True
                settings.mouse.button = event.button
            if event.type == EVT_BATTLE:
                check = [settings.map_open,
                 settings.cangku_open,
                 settings.hecheng_open,
                 settings.xiulian_open,
                 settings.ronghe_open,
                 settings.set_open,
                 settings.fuwen_open,
                 settings.lianbao_open]
                if True not in check:
                    if p.place.name != u'\u957f\u5b89':
                        battle.battle(p)
                    else:
                        battle.stay_in_changan(p)
                    if pygame.display.get_active():
                        draw.b_draw_surf(b_surf)
            if event.type == EVT_SAVE:
                save.save(p)
            if event.type == EVT_SAVE_2:
                save.save_2(p)

        screen.fill(GRAY)
        if pygame.display.get_active():
            if settings.map_open:
                draw.map_open(ditu, p)
            elif settings.cangku_open:
                draw.cangku_open(p, cangku_surf)
                draw.cangku_bag_draw_surf(p, toolbar_surf)
            elif settings.pet_cangku_open:
                draw.pet_cangku_open(p, pet_cangku_surf)
                draw.pet_cangku_bag_draw_surf(p, toolbar_surf)
            elif settings.hecheng_open:
                draw.hecheng_open(p, hecheng_surf)
                draw.hecheng_bag_draw_surf(p, toolbar_surf)
            elif settings.ronghe_open:
                draw.ronghe_open(p, ronghe_surf)
                draw.ronghe_pet_bag_draw_surf(p, toolbar_surf)
            elif settings.xiulian_open:
                draw.xiulian_open(p, xiulian_surf)
            elif settings.fuwen_open:
                draw.fuwen_open(p, fuwen_surf)
                draw.fuwen_bag_draw_surf(p, toolbar_surf)
            elif settings.lianbao_open:
                draw.lianbao_open(p, lianbao_surf)
                draw.lianbao_bag_draw_surf(p, toolbar_surf)
            elif settings.set_open:
                draw.set_open(p, set_surf)
            elif settings.show_equip_open:
                draw.show_equip_open(p, show_equip_surf)
            elif settings.player_detail_open:
                draw.player_detail_open(p, login_surf)
            elif settings.login_open:
                draw.login_open(p, login_surf)
            else:
                draw.bt_draw_surf(b_surf)
                draw.p_draw_surf(p, p_surf)
                draw.m_draw_surf(p, m_surf, settings.font_14)
                draw.pet_draw_surf(p, pet_surf, settings.font_14)
                draw.fashu_draw_surf(p, fashu_surf)
                draw.count_draw_surf(p, count_surf)
                draw.toolbar_draw_surf(p, toolbar_surf)
                draw.detect_mouse(p)
            draw.message_draw_surf()
            settings.mouse.fresh()
        settings.clock.tick(settings.FPS)
        pygame.display.update()

    return
Esempio n. 33
0
def eventCard(player, cards, enemy, deck, turn):
    item = 0
    eventCards = random.choice(cards)
    cards.remove(eventCards)
    if cards == []:
        for i in range(36):
            cards.append(i + 1)

    print("## Event card ##")
    if eventCards == 1:
        print("Found the mother and baby bear")
        redDice = [1, 2, 3, 4, "Battle", "Battle"]
        red = random.choice(redDice)
        print("The red dice is ", red)
        if red == "Battle":
            print('Bitten')
            player.hp = player.hp - 2
            print('Player HP - 2 = ', player.hp)
        else:
            print('Friendly')
            print('get 1 item card')
            item = 1
    elif eventCards == 2:
        print('Found lord vampire')
        if player.character == "Priest":
            print('Win')
            print('get 1 item card')
            item = 1
        elif player == "Demon":
            print('Increase power')
            player.hp = player.hp + 3
            print('Player Hp + 3 =', player.hp)
        elif player.character == "Swordman" or player.character == "Magician":
            print('Sucked blood')
            player.hp = player.hp - 2
            print('Player Hp - 2 = ', player.hp)
        else:
            print('Nothing happened')
    elif eventCards == 3:
        print('This is something')
        redDice = [1, 2, 3, 4, "Battle", "Battle"]
        red = random.choice(redDice)
        print("The red dice is ", red)
        if red == "Battle":
            print('It is a bomb')
            player.hp = player.hp - 3
            print('Player Hp - 3 = ', player.hp)
        else:
            print('It was crab and clamped into it')
            player.hp = player.hp - 1
            print('Player Hp - 1 = ', player.hp)
    elif eventCards == 4:
        print('Found a strange tribe')
        redDice = [1, 2, 3, 4, "Battle", "Battle"]
        red = random.choice(redDice)
        print("The red dice is ", red)
        if red == "Battle":
            print('Shy tribe fled')
            print('Nothing happened')
        else:
            print('Provide accommodation')
            print('Stop 1 turn')
            player.status = player.status + 1
    elif eventCards == 5:
        print('Found a ferocious lizard')
        redDice = [1, 2, 3, 4, "Battle", "Battle"]
        red = random.choice(redDice)
        print("The red dice is ", red)
        if red == "Battle":
            print('win')
            print('get 1 item card')
            item = 1
        else:
            print('Attacked')
            player.hp = player.hp - 2
            print('Player HP - 2 = ', player.hp)
    elif eventCards == 6:
        print('Fishing can be a dragon')
        redDice = [1, 2, 3, 4, "Battle", "Battle"]
        red = random.choice(redDice)
        print("The red dice is ", red)
        if red == "Battle":
            print('Dragon Attack')
            player.hp = player.hp - 3
            print('Player HP - 3 = ', player.hp)
        else:
            print('Dragon brought the goods to')
            print('get 1 item card')
            item = 1
    elif eventCards == 7:
        print('Walking into the abyss.')
        player.hp = player.hp - 3
        print('Player HP - 3 = ', player.hp)
        print('Stop 1 turn')
        player.status = player.status + 1
    elif eventCards == 8:
        print('Take a bath onsen')
        redDice = [1, 2, 3, 4, "Battle", "Battle"]
        red = random.choice(redDice)
        print("The red dice is ", red)
        if red == 'Battle':
            player.hp = player.hp + 1
            print('Player HP + 1 = ', player.hp)
        else:
            print('Player HP increase according to the number of pitches')
            player.hp = player.hp + red
            print('Player Hp +', red, '= ', player.hp)
    elif eventCards == 9:
        print('Angel appeared')
        if player.character == "Priest":
            print('Received')
            print('get 1 item card')
            item = 1
        elif player.character == "Demon":
            print('Lost to the sacred')
            player.hp = player.hp - 2
            print('Player HP - 2 = ', player.hp)
        else:
            print('blessed')
            player.hp = player.hp + 2
            print('Player HP + 2 = ', player.hp)
    elif eventCards == 10:
        print('Meet bird nurse')
        player.hp = player.hp + 4
        print('Player HP + 4 = ', player.hp)
    elif eventCards == 11:
        print('Meet nuns')
        if player.character == 'Demon':
            print('Repent')
            print('Stop 1 turn')
        else:
            redDice = [1, 2, 3, 4, "Battle", "Battle"]
            red = random.choice(redDice)
            print("The red dice is ", red)
            if red == 'Battle':
                print('Nuns point the way')
                print('Go to the church')
                player.position = 14
                checkBoard.priestCastle(player)
            else:
                print('The nun breaks the dessert')
                player.hp = player.hp + 3
                print('Player HP + 3 = ', player.hp)
    elif eventCards == 12:
        print('Found flowers rushing to sniff')
        redDice = [1, 2, 3, 4, "Battle", "Battle"]
        red = random.choice(redDice)
        print("The red dice is ", red)
        if red == 'Battle':
            print('Bitten by the head')
            player.hp = player.hp - 2
            print('Player HP - 2 = ', player.hp)
        else:
            print('fragrance')
            player.hp = player.hp + 2
            print('Player HP + 2 = ', player.hp)
    elif eventCards == 13:
        print('Hungry & faint')
        player.hp = player.hp - 1
        print('Player HP - 1 and stop 1 turn', player.hp)
        print('Stop 1 turn')
        player.status = player.status + 1
    elif eventCards == 14:
        print('Find the goddess')
        print('Choose one')
        print('1. get 1 item card')
        print('2. HP + 3')
        choose = player.detailEvent(eventCards)
        if choose == 1:
            print('get 1 item card')
            item = 1
        else:
            player.hp = player.hp + 3
            print('Player HP + 3', player.hp)
    elif eventCards == 15:
        print('Mole dig out something')
        redDice = [1, 2, 3, 4, "Battle", "Battle"]
        red = random.choice(redDice)
        print("The red dice is ", red)
        if red == 'Battle':
            print('Get a bomb')
            player.hp = player.hp - 2
            print('Player HP - 2 = ', player.hp)
        else:
            print('Get a item')
            item = 1
    elif eventCards == 16:
        print('Find a mage')
        redDice = [1, 2, 3, 4, "Battle", "Battle"]
        red = random.choice(redDice)
        print("The red dice is ", red)
        if red == 'Battle':
            if player.character == 'Magician':
                player.hp = player.hp + 3
                print('Player HP + 3 = ', player.hp)
            else:
                print('guide')
                print('go to magic School')
                player.position = 50
                checkBoard.magicSchool(player, enemy, deck)
        else:
            print('give item')
            print('get 1 item card')
            item = 1
    elif eventCards == 17:
        print('Found a sacred pond')
        if player.hp > 15:
            player.hp = player.hp + 2
            print('Player HP + 2 = ', player.hp)
        else:
            player.hp = player.hp + 4
            print('Player HP + 4 = ', player.hp)
    elif eventCards == 18:
        print('Met Medusa')
        redDice = [1, 2, 3, 4, "Battle", "Battle"]
        red = random.choice(redDice)
        print("The red dice is ", red)
        if red == 'Battle':
            print('Win')
            print('get 1 item card')
            item = 1
        else:
            print('petrify')
            print('Stop 1 turn')
            player.status = player.status + 1
    elif eventCards == 19:
        print('Hit by a trap')
        print('choose one')
        print('1. Stop 1 turn')
        print('2. Hp - 2')
        choose = player.detailEvent(eventCards)
        if choose == 1:
            print('Stop 1 turn')
            player.status = player.status + 1
        else:
            player.hp = player.hp - 2
            print('Player HP - 2 = ', player.hp)
    elif eventCards == 20:
        print('Giant mushroom')
        redDice = [1, 2, 3, 4, "Battle", "Battle"]
        red = random.choice(redDice)
        print("The red dice is ", red)
        if red == 'Battle':
            print('Poisonous mushroom')
            player.hp = player.hp - 2
            print('Player HP - 2 = ', player.hp)
        else:
            print('Edible mushrooms')
            player.hp = player.hp + 2
            print('Player HP + 2 = ', player.hp)
    elif eventCards == 21:
        print('Find mushrooms')
        if player.character == 'Demon':
            print('Eat mushrooms')
            player.hp = player.hp + 2
            print('Player HP + 2 = ', player.hp)
        elif player.character == 'Robot':
            print('Collect mushrooms')
            print('get 1 item card')
            item = 1
        else:
            print('Eat mushrooms')
            player.hp = player.hp + 3
            print('Player HP + 3 = ', player.hp)
    elif eventCards == 22:
        print('Found an ugly mummy')
        if player.character == 'Demon':
            print('get 1 item card')
            item = 1
        else:
            print('Attacked')
            player.hp = player.hp - 2
            print('Player HP - 2 = ', player.hp)
    elif eventCards == 23:
        print('Take a nap & rest')
        player.hp = player.hp + 4
        player.status = player.status + 1
        print('Stop 1 turn and HP + 4 =', player.hp)
    elif eventCards == 24:
        print('Find a scientist')
        if player.character == 'Robot':
            print('Be repaired')
            player.hp = player.hp + 2
            print('Player HP + 2 and get 1 item card', player.hp)
        else:
            print('get 1 item card')
            item = 1
    elif eventCards == 25:
        print('Find a robot')
        redDice = [1, 2, 3, 4, "Battle", "Battle"]
        red = random.choice(redDice)
        print("The red dice is ", red)
        if red == 'Battle':
            if player.character == 'Robot':
                print('Player hp + 3 && get 1 item card')
                player.hp = player.hp + 3
                item = 1
            else:
                print('get 1 item card')
                player.hp = player.hp + 3
                item = 1
                print('Player HP + 3', player.hp)
        else:
            print('guide')
            print('go to Factory')
            player.position = 31
            checkBoard.factoryCastle(player, deck)
    elif eventCards == 26:
        print('Into the mysterious forest')
        redDice = [1, 2, 3, 4, "Battle", "Battle"]
        red = random.choice(redDice)
        print("The red dice is ", red)
        if red == 'Battle':
            print('Wandering the forest')
            print('Stop 1 turn')
            player.status = player.status + 1
        else:
            print('Found a special fruit')
            player.hp = player.hp + 2
            print('Player HP + 2 = ', player.hp)
    elif eventCards == 27:
        print('Found a warrior carrying a flag')
        redDice = [1, 2, 3, 4, "Battle", "Battle"]
        red = random.choice(redDice)
        print("The red dice is ", red)
        if red == 'Battle':
            print('Battle')
            battle.battle(player, enemy, turn)
        else:
            if player.character == 'Swordman':
                player.hp = player.hp + red
                print('Player HP increase according to the number of pitches')
                print('Player Hp =', player.hp)
            else:
                print('guide')
                player.position = 2
                checkBoard.swordCastle(player, deck)
    elif eventCards == 28:
        print('Meet the water goddess')
        print('Give power')
        player.hp = player.hp + 3
        print('Player HP + 3 = ', player.hp)
    elif eventCards == 29:
        print('The swarm of bees fly')
        print('Collect honey for sale')
        print('get 1 item card, but hit by a bee sting')
        player.hp = player.hp - 2
        item = 1
        print('Player HP - 2 = ', player.hp)
    elif eventCards == 30:
        print('Meet the Black Magician')
        print('Attacked')
        player.hp = player.hp - 3
        print('Player HP - 3 = ', player.hp)
    elif eventCards == 31:
        print('Lightning storm')
        if player.character == 'Robot':
            print('Get power')
            player.hp = player.hp + 3
            print('Player HP + 3 = ', player.hp)
        else:
            print('get hurt')
            player.hp = player.hp - 2
            print('Player HP - 2 = ', player.hp)
    elif eventCards == 32:
        print('Dragon watching eggs')
        redDice = [1, 2, 3, 4, "Battle", "Battle"]
        red = random.choice(redDice)
        print("The red dice is ", red)
        if red == 'Battle':
            print('Dunhuang dragon attack eggs')
            player.hp = player.hp - 2
            print('Player HP - 2 = ', player.hp)
        else:
            print('The dragon gave the eggs, get 1 item card')
            item = 1
    elif eventCards == 33:
        print('Beautiful girl in the forest')
        blueDice = [1, 2, 3, 4, "Item", "Event"]
        blue = random.choice(blueDice)
        print("The blue dice is ", blue)
        if blue == 'Item':
            print('She is the queen giving gifts')
            print('get 1 item card')
            item = 1
        elif blue == 'Event':
            print('She is a magic witch attacked')
            player.hp = player.hp - 4
            print('Player HP - 4 = ', player.hp)
        else:
            print('She is the angel to bless')
            player.hp = player.hp + 2
            print('Player HP + 2 = ', player.hp)
    elif eventCards == 34:
        print('Weapon shop')
        blueDice = [1, 2, 3, 4, "Item", "Event"]
        blue = random.choice(blueDice)
        print("The blue dice is ", blue)
        if blue == 'Item':
            print('buy 1 get 1 free')
            item = 2
        elif blue == 'Event':
            print('Do damage')
            print('remove 1 item card')
            player.disCard()
        else:
            print('Shopping')
            print('get 1 item card')
            item = 1
    elif eventCards == 35:
        print('Found the sea lion king')
        blueDice = [1, 2, 3, 4, "Item", "Event"]
        blue = random.choice(blueDice)
        print("The blue dice is ", blue)
        if blue == 'Item':
            print('Give 2 item')
            print('get 2 item card')
            item = 2
        elif blue == 'Event':
            print('Organize a celebration')
            player.hp = player.hp + 5
            print('Player HP + 5 = ', player.hp)
        else:
            print('get 1 item card')
            item = 1
    elif eventCards == 36:
        blueDice = [1, 2, 3, 4, "Item", "Event"]
        blue = random.choice(blueDice)
        print("The blue dice is ", blue)
        if blue == 'Item':
            print('Collect treasures')
            print('get 2 item card')
            item = 2
        elif blue == 'Event':
            print('Is a trap')
            player.hp = player.hp - 3
            print('Player HP - 3 = ', player.hp)
        else:
            print('Just an illusion')
            print('Nothing happened')
    print('-------------------------------------')
    return cards, item
Esempio n. 34
0
def test_board(file_name):
    """Base example from challenge."""
    with open(f'test/boards/{file_name}.txt') as f:
        expected = f.read().strip()
    assert battle(f'test/scenarios/{file_name}.txt',
                  report=True).strip() == expected
Esempio n. 35
0
    while True:
        game = parse_page(page.content)
        logging.debug("gstate={}".format(game))
        utils.tick_delay()

        # TODO: oop
        if game['state'] == "attack":
            if roo_maze_lvl < 6:
                # roo keys not all obtained
                if M_ROO[roo_maze_lvl] in game['data']['names'][1]:
                    logging.debug("roo_maze++")
                    roo_maze_lvl += 1

            logging.debug("battling {}".format(game['data']['names'][1]))
            page = battle.battle(s, game['data'])
        elif game['state'] == "begin_fight":
            logging.info("battle start")
            page = act.begin_fight(s)
        elif game['state'] == "loot":
            logging.debug("looting")
            page = act.loot(s)
        elif game['state'] == "end_fight":
            logging.info("battle end")
            page = act.end_fight(s)
        elif game['state'] == "skill":
            logging.info("level up")
            page = act.level_up(s, None)
        elif game['state'] == "map":
            # default state, includes dialog (rip)
Esempio n. 36
0
        print("")
        print("Created by Anish Kachinthaya.")
        print("As the property of team 5327B, this tool uses Excel and web scraping libraries to scout teams.")
        print("")

    elif choice.startswith("current") == True:
        print("")
        print("Current Tournament")
        print(title)
        print("")

    elif choice.startswith("battle") == True:
        choice = choice.split(" ")
        if len(choice) == 5:
            #try:
            battle(choice[1],choice[2],choice[3],choice[4])
        else:
            print("Error: only 4 arguments accepted, which are team numbers.")
            print("Remember, 1st and 2nd are Red Allience, 3nd and 4th are Blue Alliance.")


    elif choice.startswith("rankings") == True:
        choice = choice.split(" ")
        if len(choice) == 1:
            rankings()

        elif len(choice) == 2:
            url = choice[1]
            rankings(url)

        else:
Esempio n. 37
0
def ranking_learn(game):
    # ranking_leanのデータ読み込み
    with open(ranking_data_path, 'rt') as fin:
        cin = csv.reader(fin)
        datas = [row for row in cin if len(row) > 0]
        num_weights = int(datas[0][0])

    # ランキングデータの読み込み
    ranking_path = []
    ranking_n = []
    ranking_r = []
    with open(rankings_path, 'rt') as fin:
        cin = csv.reader(fin)
        datas = [row for row in cin if len(row) > 0]
        ranking_path = [row[2] for row in datas]
        ranking_n = [int(row[3]) for row in datas]
        ranking_r = [float(row[4]) for row in datas]

    # ランキングの人数が足りないときはランダムな重みのREINFORCEagentを追加
    while len(ranking_path) < num_rankingagents:
        ranking_path.append(get_path_radom(game))  # path_listの末尾を移動
        ranking_n.append(0)
        ranking_r.append(0)
    # ランキングの人数が多すぎるときはエラー
    if len(ranking_path) > num_rankingagents:
        print("error. ranking_num is over num_rankingagents")
        # path_list.append(ranking_path.pop(0))  # rankingの末尾を移動
        # del ranking_n[0]
        # del ranking_r[0]

    # rank agentsの重みの読み込み
    game = Geister2()
    train_is = rnd.sample(range(num_rankingagents), num_rankingagents // 2)
    test_is = [i for i in range(num_rankingagents) if i not in train_is]
    rank_agents = load_agents(ranking_path, game, None)
    train_agents = [rank_agents[i] for i in train_is]
    test_agents = [rank_agents[i] for i in test_is]

    # 新しいagentの作成
    agent = pick_agent(game)
    agent_path = weights_path + "/rankRF" + str(num_weights)
    # agnetの学習
    env = VsEnvs(train_agents, game, None)  # 対戦相手はランダムに一度だけ
    agent.learn(env, max_episodes=max_episodes)

    # 最新のランキングに対して改めて対戦を行い,(test_agentsのみ更新)
    # 基準を満たしていれば,agentのランキングへの追加
    results = []
    for i in test_is:
        test_agent = rank_agents[i]
        # resultはagentの勝率
        result = battle(agent, test_agent, bttl_num=bttl_num, seed=None)
        results.append(result)
        # 対戦相手の勝率を更新
        r_opp = -result
        ranking_r[i] = (ranking_r[i] * ranking_n[i] + r_opp) / (ranking_n[i] +
                                                                1)
        ranking_n[i] += 1
    results = np.array(results)
    # 基準を満たしている場合(rが一定値以上かつ過半数に対し勝利),ランキングに追加
    if (results.mean() > threshold
            and len(np.where(results > 0)[0]) > num_rankingagents / 2):
        # ランキングの削除対象(test_agentsのうち勝率が最低のもの)
        dl_index = ranking_r.index(min([ranking_r[i] for i in test_is]))
        ranking_path[dl_index] = agent_path
        ranking_n[dl_index] = ranking_r[dl_index] = 0

    # agentのデータの書き込み
    np.save(agent_path + "_w", agent.w)
    np.save(agent_path + "_theta", agent.theta)
    num_weights += 1

    # ranking_learnのデータ書き込み
    with open(ranking_data_path, 'wt') as fout:
        csvout = csv.writer(fout)
        datas = [[str(num_weights)]]
        csvout.writerows(datas)

    # ランキングデータの書き込み
    datas = [[str(i + 1), "REINFORCEAgent", ranking_path[i], n, r]
             for i, n, r in zip(range(len(ranking_path)), ranking_n, ranking_r)
             ]
    with open(rankings_path, 'wt') as fout:
        csvout = csv.writer(fout)
        csvout.writerows(datas)
Esempio n. 38
0
def main():
    doctest.testmod()

    # user prompt whether to make a new character or load game,  if input is not "new" or "load"
    # an error message is printed
    start_screen = True
    while start_screen:
        select = input("new or load?")
        if select == "new" or select == "load":
            start_screen = False
        else:
            print("incorrect selection")

    border_y = 5
    border_x = 5
    game_map = map.Map(border_y, border_x)

    # create a new character
    if select == "new":
        character_name = input("enter your character name:")
        hero = Character.Character(10, character_name)
        game_map.update_character_position_on_map(0, 0)
        game_map.display_map()
    elif select == "load":

        # open a json file to load a character, if no json file is present, prompted to create new character
        try:
            with open("character_data.json") as json_file:
                json_data = json.load(json_file)
                hero = Character.Character(json_data['hp'], json_data['name'])
                hero.set_x_position(json_data['position_x'])
                hero.set_y_position(json_data['position_y'])
                game_map.update_character_position_on_map(
                    hero.get_x_position(), hero.get_y_position())
        except FileNotFoundError:
            character_name = input(
                "no character data was found, enter a name for a new character: "
            )
            hero = Character.Character(10, character_name)
            game_map.update_character_position_on_map(0, 0)

    play = True
    while play:
        command = input("enter a command, type help for list of commands")
        commands = [
            'n', 'N', 'e', 'E', 's', 'S', 'w', 'W', 'map', 'q', 'Q', 'help',
            'status'
        ]

        # check for correct commands
        if command not in commands:
            print("invalid command entered")
        elif command == 'help':
            print("available commands:\nmove: N, E, S, W\ndisplay map: map\n"
                  "quit game: q\ncharacter status: status")

        # if you quit, character is saved to a json file
        elif command == 'q' or command == 'Q':
            character_dict = {
                'name': hero.get_name(),
                'hp': hero.get_hp(),
                'position_x': hero.get_x_position(),
                'position_y': hero.get_y_position()
            }
            with open('character_data.json', 'w') as outfile:
                json.dump(character_dict, outfile)
            play = False

        # bring up status of your character
        elif command == 'status':
            print("name:", hero.get_name())
            print("hp:", hero.get_hp())

        # bring up game map
        elif command == 'map' or command == 'MAP' or command == 'Map':
            game_map.display_map()

        # entered a movement command
        else:
            hero.move(command, border_x - 1, border_y - 1)

            # update the map with current position of your character
            game_map.update_character_position_on_map(hero.get_x_position(),
                                                      hero.get_y_position())

            # chance spawn of an enemy monster when character moves or attempts to move
            # enter a battle phase with monster
            enemy_spawn = random.randint(1, 3)
            if enemy_spawn == 2:
                print("suprise attack from a monster!")
                monster = Monster.Monster(5, "goblin")
                battle.battle(hero, monster)

                if hero.get_alive() is False:
                    print("game over, you died")
                    play = False

                game_map.update_character_path_taken()
                game_map.update_character_position_on_map(
                    hero.get_x_position(), hero.get_y_position())
            else:
                hero.set_hp(hero.get_hp() + 1)
                game_map.update_character_path_taken()
                game_map.update_character_position_on_map(
                    hero.get_x_position(), hero.get_y_position())
Esempio n. 39
0
#!/usr/bin/env python3

import random

# Local
from prompt import prompt
from npcs import low_level_monsters
from battle import battle
from usersave import player
import usersave
import inventory
import gameshop

__author__ = 'John Victor'
__version__ = 'Alpha 0.3'
""" Dev Notes:
battle(player, random.choice(monster_list))  # Battle with random npc from monster_list

inv = inventory.Inventory()  # Alias of inventory.Inventory()

inv.add_item(inventory.item_var)  # Add item to inventory
inv.remove_item(inventory.item_var)  # Remove item from inventory

inv.equip_item(inventory.item_var)  # Equip item
inv.unequip_item(inventory.item_var)  # Unequip item

prompt(text, key1, key2, key3, key4 (...))  # Asks for user input with (text) and only allows user to type keys in *keys
"""

START_TEXT = f"""
 _______________________________________________________________