예제 #1
0
    def setUp(self):
        sword = Weapon('Spartan Sword', 1, 20)
        bow = Weapon('Long Bow', 5, 60)

        self.leonidas = Character('King Leonidas', 10, sword, 200)
        self.legolas = Character('Elf Legolas', 5, bow, 100, 4)
        self.hulk = Character('Incredible Hulk', 100, None, 800, 2)

        self.arena = Battleground('Thunderdome', 20, 20)
        self.battle = Battle(self.arena)
예제 #2
0
 def navigate(self, x, y, Map, Monster):
     self.row = x
     self.col = y
     if Map.list[self.row][self.col] == 1:
         print "You found a Monster!"
         fight = Battle(self, Monster)
         Map.blankList[self.row][self.col] = "x"
         fight.fight()
     else:
         print "You found a safe spot!"
         Map.blankList[self.row][self.col] = "o"
예제 #3
0
 def navigate(self, x, y, Map, Monster):
     self.row = x
     self.col = y
     if Map.list[self.row][self.col] == 1:
         print "You found a Monster!"
         fight = Battle(self, Monster)
         Map.blankList[self.row][self.col] = "x"
         fight.fight()
     else:
         print "You found a safe spot!"
         Map.blankList[self.row][self.col] = "o"
예제 #4
0
 def start(self):
     self.battle = Battle(self.battleFrame)
     self.isStart.set(True)
     # スタートボタン,コンボボックスを押せなくする
     self.startButton.configure(state='disabled')
     self.comboboxS.configure(state='disabled')
     self.comboboxK.configure(state='disabled')
     # リスタートボタンとプレイヤー変更ボタンを押せるようにする
     self.restartButton.configure(state='normal')
     self.changePlayerButton.configure(state='normal')
     # 対戦スタート
     self.battle.setPlayer(self.senkouName.get(), self.koukouName.get())
     self.battle.progress()
예제 #5
0
    def checkenemy(self):
        # goes through the list of enemies, adding up all the encounter chances up until that list number
        def collect_encounter_chances(list_placement):
            chance = 0
            for x in range(0, list_placement + 1):
                chance += self.enemies[x].rarity
            return chance

        # if it is time to check, the player is moving, we do encounter an enemy, and there are enemies available
        if (pygame.time.get_ticks() - self.last_encounter_check) >= variables.encounter_check_rate and \
                classvar.player.ismoving() and \
                        random.random() < variables.encounter_chance and \
                        len(self.enemies) > 0:
            currentenemy = False
            random_factor = random.random()
            for x in range(0, len(self.enemies)):
                e = self.enemies[x]
                # if the random factor is below all of the chances previously to now added up
                if random_factor < collect_encounter_chances(x):
                    currentenemy = e
                    break
            if currentenemy == False:
                currentenemy = self.enemies[len(self.enemies) - 1]
            variables.state = "battle"
            classvar.player.change_of_state()
            if (len(self.lvrange) > 1):
                currentenemy.lv = random.randint(self.lvrange[0],
                                                 self.lvrange[1])
            else:
                currentenemy.lv = self.lvrange[0]
            currentenemy.health = stathandeling.max_health(currentenemy.lv)
            classvar.battle = Battle(currentenemy)
예제 #6
0
def time_estimate(trials):
    """
    Print a time estimate for the current simulation. If the simulation is expected to take more
    than four hours, warn the user
    :return:
    """
    total_trials = len(AI)**2 * trials
    unit = 'hours'

    if total_trials > FIVE_MINUTE_THRESHOLD:
        log.info('Calculating expected runtime ...')
        estimate_trials = 6
        start_time = timer()
        Battle(estimate_trials, Randy, Randy).run()

        expected_duration = int(
            ((timer() - start_time) * total_trials) / estimate_trials /
            SECONDS_PER_MINUTE / MINUTES_PER_HOUR)

        if expected_duration > LONG_RUN_WARNING_THRESHOLD:
            raw_input(
                'WARNING: This simulation is expected to take over {0} hours. Press any key to continue ...'
                .format(expected_duration))
    else:
        expected_duration = 5
        unit = 'minutes'

    log.info(
        STRING_INIT.format(str(total_trials), str(expected_duration), unit))
예제 #7
0
def affrontement(game, policy1, policy2, nbplay):
    """
    Simulation of game
    
    :param policy1: player1 strategy (dictionary: {state: {action: probability}}) 
    :param policy2: player2 strategy (dictionary: {state: {action: probability}}) 
    :param nb_play: integer number of iterations
    """
    #uses battle to have policy 1 and 1 play against each other
    policy = {0: policy1, 1: policy2}
    battle = Battle(game, nbplay, policy)
    battle.simulation()
    #print("total_rewards")
    #print(battle.total_rewards)
    wins1, wins2 = battle.get_winners()
    #print("player1 won :",wins1,"times out of",nbplay,"games")
    #print("player2 won :",wins2,"times out of",nbplay,"games")
    return (wins1, wins2)
예제 #8
0
 def __init__(self, hero):
     print("You walk up to the castle")
     if random.randrange(0, 100) > 90:
         print("The guards determine you're a threat, and want to fight!")
         guard_greature = Enemy(weapon_pile().get_random_weapon())
         Battle(hero, guard_greature)
     else:
         print("The guards stand stoically; watching your every move, as you move inside.")
     self.guard_speak(hero)
예제 #9
0
 def guard_speak(self, hero):
     print("A guard stops you in your tracks and says; \"We don't let just anyone speak with the king.\"\nWhy are you here?");
     castle_options = ["Ask for title increase", "Attack King", "Leave"]
     counter = 1
     for co in castle_options:
         print(str(counter) + ". " + co)
         counter += 1
     user_co = input("What would you like to do: ")
     if int(user_co) == 1:
         self.increase_title(hero)
     if int(user_co) == 2:
         are_you_sure = input("Are you sure you want to do this?  This is a death sentence!: ")
         if str(are_you_sure).upper() == "Y":
             print("Fighting the guards and eventual king")
             guard_one = Enemy(weapon_pile().get_random_weapon())
             Battle(hero, guard_one)
             Battle(hero, guard_one)
             Battle(hero, guard_one)
     print(hero.char.name + " leave the castle.")
예제 #10
0
 def exit_conversation(self):
     if self.special_battle == "none":
         self.progress = 0
         variables.state = "world"
     else:
         variables.state = "battle"
         classvar.player.change_of_state()
         self.special_battle.health = stathandeling.max_health(
             self.special_battle.lv)
         classvar.battle = Battle(self.special_battle)
예제 #11
0
def battleStart(you, red):
	b = Battle(you, red)
	mov = 0

	while(mov == 0):
		os.system('clear')
		b.round()

		Mechanics.printMoves(b.poke_p1)
		print('Select a move:'),
		mov = input()

		print( b.poke_p1.moves[mov-1].getName() )
		time.sleep(3)





		mov = 0
예제 #12
0
 def run(self):
     """
     Return True id the player is alive, False otherwise.
     The player enters in a room and either he engages a battle if the mob is a monster or he does a transaction if the mob is a merchant or
     he takes items in a chest if he finds one.
     """
     if (type(self.mob) == Monster):
         battle = Battle(self.player, self.mob)
         return battle.run()
     elif (type(self.mob) == Merchant):
         transaction = Transaction(self.player, self.mob)
         return transaction.run()
     else:
         print("You find a chest !")
         self.player.statistics.chestsFound += 1
         items = generateChest()
         for objects in items:
             print("{} got {}.".format(self.player.name,
                                       objects.showInfo()))
             self.player.inventory.objects.append(objects)
         return True
예제 #13
0
class TestBattle(unittest.TestCase):
    def setUp(self):
        sword = Weapon('Spartan Sword', 1, 20)
        bow = Weapon('Long Bow', 5, 60)

        self.leonidas = Character('King Leonidas', 10, sword, 200)
        self.legolas = Character('Elf Legolas', 5, bow, 100, 4)
        self.hulk = Character('Incredible Hulk', 100, None, 800, 2)

        self.arena = Battleground('Thunderdome', 20, 20)
        self.battle = Battle(self.arena)

    def test_add_fighters_in_arena(self):
        self.battle.add_fighter(self.legolas, -5, -5)
        self.battle.add_fighter(self.leonidas, 10, 10)
        self.battle.add_fighter(self.hulk, 50, 50)

        assert self.legolas.x == 1
        assert self.legolas.y == 1

        assert self.leonidas.x == 10
        assert self.leonidas.y == 10

        assert self.hulk.x == 20
        assert self.hulk.x == 20
예제 #14
0
    def create(self):
        self.status_icon = gtk.StatusIcon()
        self.spring_logo_pixbuf = gtk.gdk.pixbuf_new_from_file(self.ini.get(self.profile, 'DOCKAPP', None))
        self.status_icon.set_from_file(self.ini.get(self.profile, 'DOCKAPP', None))
        self.status_icon.set_visible(True)


        self.map_index = index_map(self)
        self.map_index.check_if_update_needed()

        ## Mod Index
        self.mod_index = index_mod(self)
        self.mod_index.check_if_update_needed()

        ## Datadirs
        datadirs = self.unitsync_wrapper.datadirs_list()
        self.datadirs = []
        for i in range(0,len(datadirs)):
            if os.path.isdir(datadirs[i]) == True:
                self.datadirs.append(datadirs[i])

        ## Classes
        self.battle = Battle(self)
        self.lobby = gui_lobby(self)
        self.options = config(self)
        
        self.battle.integrate_with_lobby(self)
        self.battle.integrate_with_options(self)        
        self.lobby.IntegrateWithBattle(self)

        self.lobby.Create()
        self.battle.create()        
        self.options.create()

        self.tooltip('Unity Lobby')
        self.blinking(True)
        self.status_icon.connect('activate', self.active)
        self.status_icon.connect('popup-menu', self.popup_menu)
예제 #15
0
 def entry(self, hero):
     print(
         "You find yourself in a clearing, looking at an entry to a forest."
     )
     input()
     entryFight = random.randrange(0, 100)
     if entryFight >= 90:
         print(
             "You see a creature guarding the entrance, it wants to fight!")
         guard_creature = Enemy(weapon_pile().get_random_weapon())
         #  storeWeapons = WeaponPile().getWeapons()
         #  guardCreature = guardCreature.enemyCreation(storeWeapons)
         Battle(hero, guard_creature)
     self.wandering_overview(hero)
예제 #16
0
    def __init__(self, hero):
        print("\n" + hero.char.name + " currently has " +
              str(hero.char.money) + " gold.")
        print("The shopkeeper greets you")
        input()
        shopkeep = NPC(weapon_pile().get_random_weapon())
        shopper_choice = input("Are you buying or selling?: ")

        if "B" in str(shopper_choice).upper():
            self.buying_menu(hero)
        if "S" in str(shopper_choice).upper():
            self.sellingMenu(hero)
        if "K" in str(shopper_choice).upper() or "A" in str(
                shopper_choice).upper():
            print("\nYou lunge at the " + shopkeep.Name + " with your " +
                  shopkeep.Weapon.name + "!\n")
            Battle(hero, shopkeep)
예제 #17
0
class Client():
    def __init__(self):
        self.id = None
        self.name = None
        self.level = None

        self.login_connector = GatewayConnector()
        self.game_server_connector = None
        self.battle = None
        self.transceiver = None

    def login(self, username, passwd):
        game_server_info, self.transceiver = self.login_connector.login(
            username, passwd)

        self.game_server_connector = GameServerConnector(
            *game_server_info, self.transceiver)
        player_info = self.game_server_connector.get_player_info(output=True)
        self.id = player_info["player_id"]
        self.name = player_info["player_name"]
        self.level = player_info["player_level"]

    def start_match_fight(self, output=False):
        fight_server_info = self.game_server_connector.match_player(
            output=output)
        self.battle = Battle(self.id, fight_server_info, self.transceiver)
        self.battle.send_ready(output)

    def round_begin(self, output=False):
        self.battle.round_begin(output=output)

    def wait_enemy_round(self, output=False):
        self.battle.wait_enemy_round(output=output)

    def round_end(self, output=False):
        self.battle.round_end(output=output)

    def battle_over(self):
        battle_info = self.battle.battle_info
        if battle_info.player_hero.hp <= 0 or battle_info.enemy_hero.hp <= 0:
            return True
        else:
            return False
예제 #18
0
def main():
    """
    Runs all possible battles and logs results
    """
    trials = DEFAULT_TRIAL_COUNT if len(sys.argv) > 0 else int(sys.argv[1])
    print trials
    battle_count = len(AI)**2
    time_estimate(trials)
    results_dict = {}
    trial_num = 0

    # For each possible battle b in all pair permutations of the list of AI ...
    for p1, p2 in itertools.product(AI, AI):
        progress = float(trial_num) / float(battle_count) * 100.0
        print_progress_bar(progress, p1.__name__, p2.__name__)
        results_dict[get_battle_key(p1, p2)] = Battle(trials, p1, p2).run()
        trial_num += 1

    print_progress_bar(100.0)
    report_results(results_dict)
예제 #19
0
    def _encounter_enemy(self):

        # If there is an enemy, start the battle with it
        if self._enemy is not None:

            battle = Battle(self._player, self._enemy)
            battle.start_battle()

            if battle.fleed():

                # Go back to the previous node
                print("You frantically run back to the last room you were in.")
                self._has_fleed = True

            elif battle.won():
                self._enemy = None

            elif battle.lost():
                self._has_lost = True
예제 #20
0
    def wandering_overview(self, hero):
        directions = ["north", "south", "east", "west", "Go Back to Town"]

        while self.is_plotter_zeroed() == False:
            print("What direction would you like to go: ")
            counter = 1
            for dir in directions:
                print(str(counter) + ". " + dir)
                counter += 1
            dir_choice = input("Your choice: ")
            #      self.entryCount += 1
            if dir_choice == "north" or dir_choice.upper() == "N":
                self.plotter[0] += 1
            if dir_choice == "south" or dir_choice.upper() == "S":
                self.plotter[0] -= 1
            if dir_choice == "east" or dir_choice.upper() == "E":
                self.plotter[1] += 1
            if dir_choice == "west" or dir_choice.upper() == "W":
                self.plotter[1] -= 1
            if "town" in dir_choice:
                self.plotter[0] = 0
                self.plotter[1] = 0

            deepness_range = random.randrange(
                self.plotter[0] * self.plotter[1], 100)
            #     print("Deepness Range: " + str(deepnessRange))
            if deepness_range > 50:
                available_weapons = weapon_pile().get_random_weapon()
                #      enemy = Enemy(availableWeapons)
                print("As " + hero.char.name + " comes to a clearing")
                Battle(hero, Enemy(available_weapons))

        if self.is_plotter_zeroed() == True:
            user_leave = input("Are you sure you want to leave the forest?: ")
            if str(user_leave) is "N" or str(user_leave) is "N":
                self.plotter[0] += 1
                print(hero.Name + " walks back into the forest.")
            else:
                print(hero.Name + " walks out of the forest, towards the town")
예제 #21
0
from Goblin import Goblin
from Store import Store
from Wizard import Wizard
from Spider import Spider
from Snake import Snake
from Medic import Medic
from Shadow import Shadow
from Zombie import Zombie

if __name__ == "__main__":
    hero = Hero()
    enemies = [
        Goblin(),
        Wizard(),
        Medic(),
        Shadow(),
        Zombie(),
        Spider(),
        Snake()
    ]
    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)

    print("YOU WIN!")
 def start(self):
     self.window.findChild(QLineEdit, 'bot1Path').cursorPositionChanged.connect(self.setBot1Path)
     self.window.findChild(QLineEdit, 'bot2Path').cursorPositionChanged.connect(self.setBot2Path)
     self.window.findChild(QPushButton).clicked.connect(
         lambda: self.window.stateManager.changeState(Battle('Assets/game.ui', self.bot1_path, self.bot2_path)))
예제 #23
0
 UI.print_prompt(lang=lang)
 cmd = input()
 os.system("cls")
 if cmd == '4' or cmd.lower() == 'exit':
     UI.print_exit(lang=lang)
     input()
     exit()
 elif cmd == '2' or cmd.lower() == 'battle':
     if len(army1) < 1 or len(army2) < 1:
         UI.print_not_enough_stacks(lang=lang)
         continue
     b_army1 = BattleArmy(
         *list(map(lambda x: BattleUnitsStack(x), army1)))
     b_army2 = BattleArmy(
         *list(map(lambda x: BattleUnitsStack(x), army2)))
     battle = Battle(b_army1, b_army2)
     while True:
         battle.print_status()
         if battle.status:
             break
         UI.print_battle(lang=lang)
         UI.print_prompt(lang=lang)
         cmd = input()
         os.system("cls")
         if cmd == '1' or cmd.lower() == 'attack':
             print(f"Select unit to attack (e.g. 'Skeleton')")
             battle.print_turn()
             unit = input("Type: ")
             battle.do_action('attack', unit)
         elif cmd == '4' or cmd.lower() == 'cast':
             print(f"Select unit and army to cast (e.g. 'Skeleton 2')")
예제 #24
0
class Gomoku:
    def roop(self):
        self.root = tk.Tk()
        self.setButton()
        self.root.mainloop()

    def setButton(self):
        self.root.title(u'五目並べ')
        self.root.geometry("+300+300")  #ヨコ*タテ+X+Y
        self.root.resizable(width=False, height=False)
        self.root.option_add('*font', ('FixedSys', 14))

        # コンボボックスのデフォルトの値
        self.senkouName = tk.StringVar()
        self.senkouName.set(u'人間')
        self.koukouName = tk.StringVar()
        self.koukouName.set(u'人間')

        # スタートボタンが押されたかどうか
        self.isStart = tk.BooleanVar()
        self.isStart.set(False)

        # プレイヤーの設定をするフレーム
        self.settingFrame = tk.Frame(self.root)
        self.senkouFrame = tk.Frame(self.settingFrame)
        self.senkouFrame.pack()
        self.koukouFrame = tk.Frame(self.settingFrame)
        self.koukouFrame.pack()

        # 盤面が表示されるフレーム(プレイヤーに人間がいる場合のみ)
        self.battleFrame = tk.Frame(self.root)

        # 先攻の設定
        self.senkouLabel = tk.Label(self.senkouFrame, text=u'先攻:◯')
        self.senkouLabel.pack(side=tk.LEFT)
        self.comboboxS = ttk.Combobox(self.senkouFrame,
                                      textvariable=self.senkouName)
        self.comboboxS.bind('<<ComboboxSelected>>', self.comboboxSelected)
        self.comboboxS['values'] = (u'人間', u'ランダム君', u'強いランダム君', 'DQN')
        self.comboboxS.pack()

        # 後攻の設定
        self.koukouLabel = tk.Label(self.koukouFrame, text=u'後攻:✕')
        self.koukouLabel.pack(side=tk.LEFT)
        self.comboboxK = ttk.Combobox(self.koukouFrame,
                                      textvariable=self.koukouName)
        self.comboboxK.bind('<<ComboboxSelected>>', self.comboboxSelected)
        self.comboboxK['values'] = (u'人間', u'ランダム君', u'強いランダム君', 'DQN')
        self.comboboxK.pack()

        # スタートボタン
        self.startButton = tk.Button(self.settingFrame,
                                     text=u'スタート',
                                     command=self.start)
        self.startButton.pack()

        # リスタートボタンとプレイヤー変更ボタンが置かれるフレーム
        self.restartFrame = tk.Frame(self.settingFrame)
        self.restartFrame.pack()

        # プレイヤー変更ボタン
        self.changePlayerButton = tk.Button(self.restartFrame,
                                            text=u'プレイヤー変更',
                                            command=self.changePlayer,
                                            state='disabled')
        self.changePlayerButton.pack(side=tk.LEFT)

        # リスタートボタン
        self.restartButton = tk.Button(self.restartFrame,
                                       text=u'リスタート',
                                       command=self.restart,
                                       state='disabled')
        self.restartButton.pack()

        # 学習ボタン
        self.learningButton = tk.Button(self.settingFrame,
                                        text=u'学習',
                                        command=self.learning)
        self.learningButton.pack()

        # フレームの設置
        self.settingFrame.pack(padx=100)
        self.battleFrame.pack()
        self.gomokuFrame = tk.Frame(self.root)
        self.gomokuFrame.pack()

    # コンボボックスが選択された時のイベント
    def comboboxSelected(self, event):
        print self.senkouName.get() + " vs " + self.koukouName.get()

    # スタートボタンが押されたときのイベント
    def start(self):
        self.battle = Battle(self.battleFrame)
        self.isStart.set(True)
        # スタートボタン,コンボボックスを押せなくする
        self.startButton.configure(state='disabled')
        self.comboboxS.configure(state='disabled')
        self.comboboxK.configure(state='disabled')
        # リスタートボタンとプレイヤー変更ボタンを押せるようにする
        self.restartButton.configure(state='normal')
        self.changePlayerButton.configure(state='normal')
        # 対戦スタート
        self.battle.setPlayer(self.senkouName.get(), self.koukouName.get())
        self.battle.progress()

    # リスタートボタンが押されたときのイベント
    def restart(self):
        self.battle.reset()
        self.battle.progress()

    # プレイヤー変更ボタンが押されたときのイベント
    def changePlayer(self):
        self.startButton.configure(state='normal')
        self.comboboxS.configure(state='normal')
        self.comboboxK.configure(state='normal')
        self.restartButton.configure(state='disabled')
        self.changePlayerButton.configure(state='disabled')
        self.battle.reset()

    # 学習を行うボタン
    def learning(self):
        self.learningButton.configure(state='disabled')
        self.dqn = DQN.DQNPlayer("learning", True)
        self.learningWindow = tk.Toplevel()
        self.loadFileFrame = tk.Frame(self.learningWindow)
        self.loadFileFrame.pack()
        self.outputFileFrame = tk.Frame(self.learningWindow)
        self.outputFileFrame.pack()
        self.episodeFrame = tk.Frame(self.learningWindow)
        self.episodeFrame.pack()
        self.loadFileLabel = tk.Label(self.loadFileFrame, text=u'読み込みファイル名:')
        self.loadFileLabel.pack(side=tk.LEFT)
        self.loadFileLabel2 = tk.Label(self.loadFileFrame,
                                       text=self.dqn.getLoadFile())
        self.loadFileLabel2.pack(side=tk.LEFT)
        self.selectButton = tk.Button(self.loadFileFrame,
                                      text=u'選択',
                                      command=self.fileSelection)
        self.selectButton.pack()
        self.outputFileLabel = tk.Label(self.outputFileFrame, text=u'出力ファイル名:')
        self.outputFileLabel.pack(side=tk.LEFT)
        self.editBox = tk.Entry(self.outputFileFrame)
        self.editBox.insert(tk.END, self.dqn.getOutputFile())
        self.editBox.pack()
        self.episodeLabel = tk.Label(self.episodeFrame, text=u'エピソード数')
        self.episodeLabel.pack(side=tk.LEFT)
        self.episodeNumber = tk.StringVar()
        self.episodeNumber.set('10000')
        self.combobox = ttk.Combobox(self.episodeFrame,
                                     textvariable=self.episodeNumber)
        self.combobox['values'] = ('10000', '20000')
        self.combobox.pack()
        self.learningStartButton = tk.Button(self.learningWindow,
                                             text=u'学習スタート',
                                             command=self.learningStart)
        self.learningStartButton.pack()

    def fileSelection(self):
        self.iDir = os.path.abspath(os.path.dirname(__file__))
        self.iDir += "/result"
        self.filename = tkfd.askdirectory(initialdir=self.iDir)
        self.loadFileLabel2['text'] = self.filename

    def learningStart(self):
        self.dqn.setLoadFile(self.loadFileLabel2['text'])
        self.dqn.setOutputFile(self.editBox.get())
        print "エピソード数" + self.episodeNumber.get()
        self.root.destroy()
        self.dqn.learning(int(self.episodeNumber.get()))
예제 #25
0
class status_icon:

    def __init__(self, profile):

        gtk.gdk.threads_init()

        ### Initialise Variables
        self.windows = ({'Battle':False, 'Lobby':False, 'Options':False})
        self.updating = False
        self.profile = profile

        ## Platform
        self.platform = sys.platform
        if self.platform != 'win32':
            ## Linux
            HOME = os.environ['HOME']
            self.profile_dir = os.path.join(HOME, '.unity-lobby', 'profiles', profile)
            self.ini_file = os.path.join(HOME, '.unity-lobby', 'profiles', 'setup.ini')
        else:
            ## Windows
            APPDATA = os.environ['APPDATA']
            self.setup_dir = os.path.join(APPDATA, 'unity-lobby', 'profiles', profile)
            self.ini_file = os.path.join(APPDATA, 'unity-lobby', 'profiles', 'setup.ini')

        ## Unity Conf
        self.ini = ConfigParser.ConfigParser()
        self.ini.optionxform = lambda x: x
        self.ini.read(self.ini_file)

        ## Lobby Conf
        self.lobby_ini_file = self.ini.get(self.profile, 'LOBBY_CONF')
        self.lobby_ini = ConfigParser.ConfigParser()
        self.lobby_ini.optionxform = lambda x: x
        self.lobby_ini.read(self.lobby_ini_file)

        ## Unitsync Wrapper
        self.unitsync_wrapper = unitsync_wrapper(self.ini.get(self.profile, 'SPRING_DATADIR', None))

        ## Unitsync Cache files
        self.map_index_file = self.ini.get(self.profile, 'MAP_INDEX')
        self.mod_index_file = self.ini.get(self.profile, 'MOD_INDEX')

        ## UnityLobby Location
        self.unity_location = self.ini.get(self.profile, 'UNITY_INSTALL_DIR')

        ## Register Custom Stock Images
        bot_image_location = os.path.join(self.unity_location, 'resources', 'status', 'bot.svg')
        insync_location = os.path.join(self.unity_location, 'resources', 'sync', 'sync1.png')
        unknownsync_location = os.path.join(self.unity_location, 'resources', 'sync', 'sync2.png')
        outofsync_location = os.path.join(self.unity_location, 'resources', 'sync', 'sync3.png')

        self.register_iconsets([('unitylobby-bot', bot_image_location), ('unitylobby-in-sync', insync_location),  ('unitylobby-unknown-sync', unknownsync_location), ('unitylobby-outof-sync', outofsync_location)])


    def create(self):
        self.status_icon = gtk.StatusIcon()
        self.spring_logo_pixbuf = gtk.gdk.pixbuf_new_from_file(self.ini.get(self.profile, 'DOCKAPP', None))
        self.status_icon.set_from_file(self.ini.get(self.profile, 'DOCKAPP', None))
        self.status_icon.set_visible(True)


        self.map_index = index_map(self)
        self.map_index.check_if_update_needed()

        ## Mod Index
        self.mod_index = index_mod(self)
        self.mod_index.check_if_update_needed()

        ## Datadirs
        datadirs = self.unitsync_wrapper.datadirs_list()
        self.datadirs = []
        for i in range(0,len(datadirs)):
            if os.path.isdir(datadirs[i]) == True:
                self.datadirs.append(datadirs[i])

        ## Classes
        self.battle = Battle(self)
        self.lobby = gui_lobby(self)
        self.options = config(self)
        
        self.battle.integrate_with_lobby(self)
        self.battle.integrate_with_options(self)        
        self.lobby.IntegrateWithBattle(self)

        self.lobby.Create()
        self.battle.create()        
        self.options.create()

        self.tooltip('Unity Lobby')
        self.blinking(True)
        self.status_icon.connect('activate', self.active)
        self.status_icon.connect('popup-menu', self.popup_menu)


    def tooltip(self, text):
        self.status_icon.set_tooltip(text)


    def active(self, status_icon):
        self.blinking(False)


    def blinking(self, boolean):
        self.status_icon.set_blinking(boolean)


    def popup_menu(self, status_icon, button, activate_time):
        if self.updating == False:
            self.blinking(False)

            menu = gtk.Menu()
            battle_item = gtk.MenuItem("Battle")
            lobby_item = gtk.MenuItem("Lobby")
            options_item = gtk.MenuItem("Options")
            close_item = gtk.MenuItem("Close")

            battle_item.connect("button_press_event", self.battle_show)
            lobby_item.connect("button_press_event", self.lobby_show)
            options_item.connect("button_press_event", self.options_show)
            close_item.connect("button_press_event", self.close)

            menu.append(battle_item)
            menu.append(lobby_item)
            menu.append(options_item)
            menu.append(close_item)

            menu.show_all()
            menu.popup(None, None, None, button, activate_time)


    def battle_show(self, menu_item, event):
        if self.windows['Battle'] == False:
            self.windows['Battle'] == True
            self.battle.show()
        else:
            self.windows['Battle'] == False
            self.battle.hide()


    def lobby_show(self, menu_item, event):
        if self.windows['Lobby'] == False:
            self.windows['Lobby'] == True
            self.lobby.Show()
        else:
            self.windows['Lobby'] == False
            self.lobby.Hide()


    def options_show(self, menu_item, event):
        if self.windows['Options'] == False:
            self.windows['Options'] == True
            self.options.show()
        else:
            self.windows['Options'] == False
            self.options.hide()


    def close(self, menu_item, event):
        gtk.main_quit()


    def main(self):
        gtk.gdk.threads_enter()
        self.create()
        gtk.main()
        gtk.gdk.threads_leave()


    def register_iconsets(self, icon_info):
        iconfactory = gtk.IconFactory()
        stock_ids = gtk.stock_list_ids()
        for stock_id, file in icon_info:
            ## only load image files when our stock_id is not present
            if stock_id not in stock_ids:
                pixbuf = gtk.gdk.pixbuf_new_from_file(file)
                iconset = gtk.IconSet(pixbuf)
                iconfactory.add(stock_id, iconset)
                iconfactory.add_default()
예제 #26
0
파일: Main.py 프로젝트: TGizzi/Simple-RPG
from Battle import Battle
from Player import Player
from Enemy import Enemy, get_enemy

player1 = Player("Haz")
player2 = Player("Ekko")
player3 = Player("Dash")



battle = Battle()
battle.fight([player1, player2, player3], get_enemy(5))
# -*- coding: utf-8 -*-
__author__ = 'Jackie'

from Role import Role
from Team import Team
from Battle import Battle

if __name__ == '__main__':
    r1 = Role(100000, 20000, 'AA')
    r2 = Role(50000, 10000, 'BB')
    r3 = Role(30000, 8000, 'CC')
    l1 = [r1, r2, r3]
    t1 = Team(l1, 'Team One')

    r4 = Role(100000, 20000, 'AA')
    r5 = Role(50000, 10000, 'BB')
    r6 = Role(30000, 8000, 'CC')
    l2 = [None, None, None, r4, r5, r6]
    t2 = Team(l2, 'Team Two')

    b = Battle(t1, t2)
    b.start()


예제 #28
0
#!/usr/bin/python
# coding=utf-8
__author__ = "Aleksandr Shyshatsky"

from Battle import Battle
from Flash import Flash
from Callbacks import Callbacks
from Events import Events

callbacks = Callbacks()
flash = Flash()
battle = Battle()
events = Events()

__all__ = ['flash', 'battle', 'callbacks', 'events']
from random import randint
from player import player
from Battle import Battle

main_player = player()

while True:

    print('\nPlayers Stats:')
    print('Health: {0}/{1}'.format(main_player.health, main_player.maxHealth))
    print('MP: : {0}/{1}'.format(main_player.magicPoints, main_player.maxMagicPoints))
    print('Attack: {0}'.format(main_player.attackSkill))
    print('Speed: {0}'.format(main_player.speedSkill))
    print('Defence: {0}\n'.format(main_player.defenceSkill))

    if randint(0, 100) > 80:
        Battle(main_player).grainExp()

    input('Type anything to end the turn.\n')
예제 #30
0
import time
import random
from Character import Character
import Monster
from Monster import Goblin, Vampire, Brigand, Wizard, Mermaid, Mountain_lion
from Monster import Ski_bunny, Whirling_dervish, Snake, Shark, Abominable_snowman
from Monster import Giant_scorpion, Sandworm, Mountain_troll, Beach_bunny, Zombie, Shadow, Medic

from Companion import Knight, Bard, Thief, Companion
from Item import Item
from Battle import Battle
from Hero import Hero

hero = Hero("myhero", 40, 25, "Mountains", "Hero")
a_goblin = Goblin("goblin", 10, 5, "Mountains", "Goblin")
a_vampire = Vampire("vamp", 12, 8, "Mountains", "Vampire")
a_brigand = Brigand("brigand", 8, 2, "Mountains", "Brigand")

battle_engine = Battle()
#shopping_engine = Shopping()
monsters = [a_vampire, a_goblin, a_vampire, a_brigand]

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

print "YOU WIN!"
예제 #31
0
from Battle import Battle
from Player import Player
from Enemy import Enemy, get_enemy

player1 = Player("Haz")
player2 = Player("Ekko")
player3 = Player("Dash")

battle = Battle()
battle.fight([player1, player2, player3], get_enemy(5))
예제 #32
0
파일: Main.py 프로젝트: uhspres/fellas
# configure the display
winSize = (800, 600)  # window size
screen = pygame.display.set_mode(winSize)
pygame.display.set_caption("Fellas... the game")

# variables for the game loop
running = True
clock = pygame.time.Clock()

# main state handler
stateHandler = StateHandler()

# initial states
firstState = TitleScreen(stateHandler)
battleState = Battle(stateHandler)
deathState = DeathScreen(stateHandler)
winState = WinScreen(stateHandler)
finalWin = FinalWin(stateHandler)
soundPlayer = SoundPlayer()

if sys.argv[1] == "hmmmmm":
    soundPlayer.play("dope.ogg")
else:
    soundPlayer.play("mountain_king.ogg")

stateHandler.configStates(firstState, battleState, deathState, winState,
                          finalWin)  # configure the statehandler

while running:
예제 #33
0
 def start_match_fight(self, output=False):
     fight_server_info = self.game_server_connector.match_player(
         output=output)
     self.battle = Battle(self.id, fight_server_info, self.transceiver)
     self.battle.send_ready(output)
예제 #34
0
 def start_battle(self, wait):
     battle = Battle(self.driver, self.pokedex, self.selected_team)
     battle.battle()