示例#1
0
 def add_player(self):
     print("add_player")
     #roll initiative
     player = Encounter()
     initiative = self.ui.spinBox_initiative.value()
     player.set_option('initiative', initiative)
     hp = self.ui.spinBox_hp.value()
     player.set_option('hp', hp)
     player.set_option('maxHP',hp)
     #if this seems strange, i have to ensure this function always updates
     #the name combo box. Because comboBox_name.insertPolicy is set to do nothing.
     self.ui.comboBox_name.insertItem(self.ui.comboBox_name.currentIndex(),
                                      self.ui.comboBox_name.currentText())
     name = self.ui.comboBox_name.currentText()
     player.set_option('name', name)
     player.set_option('groupOf', 1)
     item = QListWidgetItem("%s | %s | hp:%s" % (
                                 initiative,
                                 name,
                                 hp))
     # initiative window requires these attributes be added to items
     item.encounter = player
     item.encounter.set_option('id', -1)
     self.main.ui.listWidget_Encounter.addItem(item)
     self.ui.comboBox_name.setEditText('')
     self.ui.spinBox_initiative.setValue(1)
     self.ui.spinBox_hp.setValue(1)
     self.ui.comboBox_name.setFocus()
     self.close()
 def setup(self, path):
     self.resourceHandler = ResourceHandler()
     self.reset()
     self.path = path
     self.encounter = Encounter(path)
     self.encounter.progressSignal.connect(self.emitProgress)
     self.encounter.quickFinished.connect(self.quickParseFinished)
     job = Job(self.encounter.parseQuick)
     Worker.ThreadPool.start(job)
示例#3
0
    def test_encounter(self):
        encounter = Encounter()

        char1 = Character.create(
            name="Player A",
            start_class="Fighter",
            str_modify=6,
            dex_modify=2,
            con_modify=4,
            int_modify=2,
            wis_modify=0,
            chr_modify=0,
            unit_main_hand_weapon=SHORT_SWORD_MEDIUM,
            unit_off_hand_weapon=LIGHT_WOOD_SHIELD_MEDIUM,
            unit_armor=SPLINT_MAIL_MEDIUM,
            )
        char1.team = "party"
        char1.ask_ability_bonus = MagicMock(return_value="unit_str")
        
        char1.gain_level("Fighter")
        char1.gain_level("Fighter")
        char1.gain_level("Fighter")
        print("Char stats: HP:%d/%d %s" % (char1.unit_hp, char1.unit_hp_max, char1.get_base_attack_bonus()))
        char1.get_command = MagicMock(return_value=["attack", "1"])

        # char2 = Character.create(
        #     name="Player B",
        #     start_class="Fighter",
        #     str_modify=6,
        #     dex_modify=2,
        #     con_modify=4,
        #     int_modify=2,
        #     wis_modify=0,
        #     chr_modify=0,
        #     init_weapon=SHORT_SWORD_MEDIUM,
        #     )
        # char2.team = "party"
        # char2.gain_level("Fighter")
        # char2.gain_level("Fighter")
        # char2.gain_level("Fighter")
        # print("Char stats: HP:%d/%d %s" % (char2.unit_hp, char2.unit_hp_max, char2.get_base_attack_bonus()))
        # char2.get_command = MagicMock(return_value=["attack", "2"])

        gob1 = Goblin.create(name='goblin', unit_level=5)
        gob2 = GoblinCaster.create(name='goblin caster', unit_level=5)
        gob3 = GoblinHealer.create(name='goblin header', unit_level=7)
        encounter.add_unit(char1)
        # encounter.add_unit(char2)
        encounter.add_unit(gob1)
        encounter.add_unit(gob2)
        encounter.add_unit(gob3)

        win_team = None
        try:
            encounter.run_until_exception()
        except BattleFinishedException as e:
            win_team = e.team_win
            print("team %s wins!" % win_team)
            print("unit dead:", encounter.unit_dead_list)
 def check_space(self):
     # you ask first about the amount of space for people
     check_space = Encounter("check space")
     self.clear()
     check_space.encounter_text.append(
         "\n'How many of us can fit in the vehicle?' you ask, 'I have three siblings.' \nThan waives your question away. 'There are seven seats in the van. Even with the supplies that are there, you'll be fine on space for your four. In fact, you can take some others as well if you'd like.' \nThan comes close to you and gives you a hug. A tear comes to his eye as he explains that this might be the last time that you see one another again.\n\nIf he can make it out alive, the company that owns the transportation agency he was managing has paid for a ticket out of the country for him.\nThis is his way of paying it forward to you. As he leaves your small home, you can tell that the air raid from last night seems to be subsiding. The crack of dawn marks the new day for you.\n\n'Seven seats...' you think 'Maybe there are others who need a way out of here as well.\n'"
     )
     check_space.print_encounter_text()
     input(
         colored("End of Chapter One. Thanks for playing.",
                 "cyan",
                 attrs=["bold"]))
     exit()
 def scold_omar(self):
     # your frustration spills over a bit; Omar recedes from you
     scold_omar = Encounter("scold omar")
     self.clear()
     scold_omar.encounter_text.append(
         "\nYour brow furrows as you lean forward.\n'Omar, it's so hard to look after you when your refuse to listen to me.'\n \nRegret washes over you as the words leave your lips. Your brother tenses as he rises and stalks across the room.\n'Then don't worry about me,' he quips, 'we might all be dead soon anyway.'\n \nHis boxy frame is imposing as he pulls his backpack over his left shoulder.\n'Brother, how can I let you leave without worrying?,' glancing at your sisters, you continue, 'The three of you are all that I have.'\n"
     )
     scold_omar.encounter_text.append(False)
     scold_omar.print_encounter_text()
     self.clear()
     self.choice(
         "A loud persistent knock on the door interrupts your conversation.\nYou hear Alia sit-up. Raya rolls over and lets out a little moan. \na) Let them knock for a bit longer b) Go over to the door and find out who it is.",
         self.let_them_knock, self.check_whos_there)
 def joke_with_omar(self):
     # you try to make things light; Omar smiles
     joke_with_omar = Encounter("joke with omar")
     self.clear()
     joke_with_omar.encounter_text.append(
         "\n'You know, you could probably bang a pot right next to their heads, and they'd still sleep until the sun came up.'\n \nYou see his guard loosen a bit as he lets out a quiet scoff, smiling slightly.\n'I don't think they'd appreciate it if we tested that out,' he says turning to the kitchen to grab his bag.\n \n'Don't leave yet,' you say, 'Let's wait at least until this round have moved on.'\nAnother distant blast sounds, followed by one that sounds a little closer. \n'We still have the same needs. Whether they're here or not.'\nHe's cold again. Distancing himself from you.\n\nYou respond, 'We have enough food for two more days, let's wait a few hours and see.'\n"
     )
     joke_with_omar.encounter_text.append(False)
     joke_with_omar.print_encounter_text()
     self.clear()
     self.choice(
         "A loud persistent knock on the door interrupts your conversation.\nYou hear Alia sit-up. Raya rolls over and lets out a little moan. \na) Let them knock for a bit longer b) Go over to the door and find out who it is.",
         self.let_them_knock, self.check_whos_there)
 def leave_omar_alone(self):
     # you enjoy the silence and observe your brother for a bit
     leave_omar_alone = Encounter("leave omar alone")
     self.clear()
     leave_omar_alone.encounter_text.append(
         "\nA soft blast echoes in the distance and you see a shiver go through Omar's body. \nHe acts tough when others are watching, but deep down you still see your unsure little brother in there. \n \nA calm wave passes over the room before another blast makes him stand and turn around. \nHe sees that you're awake and nods in your direction. \n \n'Omar, did you sleep at all?', you ask almost under your breath.\n \nHe shakes his head as he crosses towards the kitchen. \n \n'How could you three sleep with all the bombs last night?'\nYou turn your head the other direction to look at your little sisters who are sleeping on the couch across from yours.\n"
     )
     leave_omar_alone.encounter_text.append(False)
     leave_omar_alone.print_encounter_text()
     self.clear()
     self.choice(
         "a) Make a joking comment b) Scold your brother for staying awake all night again",
         self.joke_with_omar, self.scold_omar)
 def bother_omar(self):
     # you decide to walk over to Omar
     bother_omar = Encounter("bother omar")
     self.clear()
     bother_omar.encounter_text.append(
         "\nYou push yourself off the couch and almost silently slip across the room. \n \nNot silently enough. Omar turns his head to the side and looks at you out of the side of his eye. \n \n'Good morning, brother. Did you sleep at all?' \nHe grunts softly and shakes his head. 'I'm surprised that you three were able to.' \nYou look back at the main room and see your sisters asleep on the other sofa across from where you just were.\n"
     )
     bother_omar.encounter_text.append(False)
     bother_omar.print_encounter_text()
     self.clear()
     self.choice(
         "a) Make a joking comment b) Scold your brother for staying awake all night again",
         self.joke_with_omar, self.scold_omar)
示例#9
0
    def __init__(self):
        self.command_registry = CommandRegistry(self)
        self.item_registry = ItemRegistry(self)

        self.player = Player("AAAAA")
        self.player.inventory.add_item(
            self.item_registry.get_item("Crude Bronze Shortsword"))

        enemy = Enemy("Dummy")

        self.current_encounter = Encounter(enemy)

        self.gameloop()
 def intro_room(self):
     # first room of the game; waking up
     intro_room = Encounter("intro room")
     self.add_choice(intro_room)
     self.clear()
     intro_room.encounter_text.append(
         "It's early. \n \nYou can tell that its morning from the sound of birds outside your window, but even behind your closed eyelids, you know the sun hasn't yet peaked from beyond the horizon. \n \nYou let your eyelids part and turn your head slightly towards the door. \nYour brother, Omar is sitting across the room, perched against the window.\nHis face is dark and brooding this morning."
     )
     intro_room.encounter_text.append(False)
     intro_room.print_encounter_text()
     self.clear()
     self.choice(
         "a) You could walk over to him and ask what he's planning, or b) allow the stillness to persist for a few more moments.",
         self.bother_omar, self.leave_omar_alone)
示例#11
0
def select_encounter():
    # Define o índice do encontro que será exibido baseado no que foi selecionado
    # na list box dos encontros. Nada acontece caso não tenha sido feito a seleção
    if listbox_encounters.curselection():
        selected = listbox_encounters.curselection()
        encounter_index = selected[0]

        encounter_selected = Encounter(
            encounters_saved[encounter_index].get_title(),
            encounters_saved[encounter_index].get_creatures())

        listbox_information.delete(0, tk.END)
        listbox_information.insert(tk.END, encounter_selected.get_title())

        # Esse for serve para formatar o texto do encontro de tal forma a ficar corretamente
        # disposto linha a linha no listbox sem ultrapassar um certo limite horizontal
        for creature in encounter_selected.get_creatures():
            # Define o número máximo de palavras que uma linha pode ter:
            max_line_size = 38

            lines = creature.get_text().split("\n")

            for line in lines:
                words = line.split(" ")

                # Se o tamanho do parágrafo exceder o número máximo de palavras permitida,
                # é organizado para que apenas haja no máximo um número n de palavras por linha:
                if len(words) > max_line_size:
                    text_size = 0
                    text = ""

                    for word in words:
                        # Se o tamanho do texto for igual ao tamanho máximo, é impresso o
                        # texto atual no listbox, o conteúdo do texto é apagado e o tamanho
                        # atual do texto retorna ao valor inicial, que é 0
                        if text_size == max_line_size:
                            listbox_information.insert(tk.END, text)
                            text_size = 0
                            text = ""
                        # As palavras são adicionadas ao texto enquanto o tamanho máximo
                        # não for alcançado:
                        else:
                            text += word + " "

                        text_size += 1

                # Caso contrário, exibe-se normalmente no listbox o conteúdo da linha
                else:
                    listbox_information.insert(tk.END, line)
 def check_supplies(self):
     # you ask first about the supplies that you must carry
     check_supplies = Encounter("check supplies")
     self.clear()
     check_supplies.encounter_text.append(
         "\n'What are the supplies that I'm taking?' you say jumping right into the job details.\n'You were always a hard worker,' Than says smirking. He explains that you have a few gurneys and a lot of surgical supples that have to be taken.\n'Overall,' he continues, 'It should leave space enough for seven people if you really are pushing it. But definitely enough space for the people that I see here.'\nThan comes close to you and gives you a hug. A tear comes to his eye as he explains that this might be the last time that you see one another again."
     )
     check_supplies.encounter_text.append(
         "\n\nIf he can make it out alive, the company that owns the transportation agency he was managing has paid for a ticket out of the country for him.\nThis is his way of paying it forward to you. As he leaves your small home, you can tell that the air raid from last night seems to be subsiding. The crack of dawn marks the new day for you.\n\n'Seven seats...' you think 'Maybe there are others who need a way out of here as well.\n'"
     )
     check_supplies.print_encounter_text()
     input(
         colored("End of Chapter One. Thanks for playing.",
                 "cyan",
                 attrs=["bold"]))
     exit()
 def check_whos_there(self):
     # you go to the door
     check_whos_there = Encounter("check whos there")
     self.clear()
     check_whos_there.encounter_text.append(
         "\nYou walk over to the door and ask in a calm voice, 'who is it?'\nAlia is standing in front on the couch now, arms crossed in her defiant, eleven-year-old way. \nA voice from the other side of the door responds, 'Its your lifeline. I have good news for you, if you'll let me in.'\n\nYou would recognize Than's voice anywhere. Omar is a few feet behind you as you take steps toward the door. He signals for you to use the peephole to confirm Than's identity.\nYou lean towards the closed door and look through the small bit of glass. Outside you see a short, stocky man with dark hair and ruddy cheeks. It's your boss at the transportation agency.\nYour hand reaches for the deadbolt lock and you open the door slowly, allowing Than to come in.\n\nNow, even Raya is sitting up looking at the man who has come in to your house.\n"
     )
     check_whos_there.encounter_text.append(False)
     check_whos_there.encounter_text.append(
         "\n'Young one, its good to see you again!' he exclaims.\n'It's so dangerous for you to be outside like that, Than.'\n'Yes, I know,' he responds. 'But I had to come here with news for you. Which brings me to the reason for my visit.\n\n'I can't stay long. But you've been good to me, good to the agency. \nAs a final goodbye, I have a van waiting for you outside. It has supplies that need to be delievered...' \nYou interrupt, 'Than, this doesn't sound like a goodbye present.' \n'Let me finish,' he continues. 'The supplies need to be delivered to a hospital in the next town over. In the much safer town that still has a working hospital. There is space in this van.' he steps toward you and leans forward, 'take your family and be safe before its too late.'"
     )
     check_whos_there.encounter_text.append(False)
     check_whos_there.print_encounter_text()
     self.clear()
     self.choice(
         "'Than.' you sigh, 'Thank you for this.' a) ask about the supplies b) ask about the amount of space that there is in the vehicle",
         self.check_supplies, self.check_space)
示例#14
0
    def __init__(self):
        pygame.init()
        self.clock = pygame.time.Clock()
        self.font = pygame.font.SysFont("Arial", 18)
        self.settings = Settings()
        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption("Alienz")
        self.logger = Logger(self)

        self.earth = Earth(self)
        self.bullets = pygame.sprite.Group()
        self.ships = pygame.sprite.Group()
        self.enemies = pygame.sprite.Group()

        self.is_encounter_active = False
        self.encounter = Encounter(self)
示例#15
0
def roll_dices():
    selected = listbox_encounters.curselection()
    encounter_index = selected[0]

    enemies = encounters_saved[encounter_index].get_creatures()
    enemies_change = []

    print("tamanho de enemies =", len(enemies))

    characters = []

    for i in range(len(encounters_saved[0].get_creatures())):
        characters.append(
            Creature(encounters_saved[0].get_creatures()[i].get_text()))

    for i in range(len(enemies)):
        enemies_change.append(Creature(enemies[i].get_text()))
        enemies_change[i].set_name("Inimigo " + str(i + 1) + " - " +
                                   enemies[i].get_name())

    characters_encounter = Encounter(encounters_saved[0].get_title(),
                                     characters)
    enemies_encounter = Encounter(
        encounters_saved[encounter_index].get_title(), enemies_change)

    creatures_in_battle = []

    for i in range(len(enemies_encounter.get_creatures())):
        creatures_in_battle.append(enemies_encounter.get_creatures()[i])

    for i in range(len(characters_encounter.get_creatures())):
        creatures_in_battle.append(characters_encounter.get_creatures()[i])

    #creatures_in_battle = enemies_encounter.get_creatures() + characters.get_creatures()

    for i in range(len(creatures_in_battle)):
        dice_roll = randint(1, 20)
        initiative = creatures_in_battle[i].get_initiative()

        print(dice_roll)
        print(initiative)

        creatures_in_battle[i].set_initiative(dice_roll + initiative)

    creatures_in_battle = sorted(creatures_in_battle, key=initiative_sort_key)

    listbox_roll.delete(0, tk.END)

    for creature in creatures_in_battle:
        listbox_roll.insert(
            tk.END,
            creature.get_name() + " = " + str(creature.get_initiative()))
 def let_them_knock(self):
     # someone is knocking; maybe they'll go away
     let_them_knock = Encounter("let them knock")
     self.clear()
     let_them_knock.encounter_text.append(
         "\nThe knock rings louder the second time around. You look at Omar and hold your hand up towards him as if to tell him not to move yet.\n \n'I come in peace!' a voice calls out from beyond the door. 'And I have your last paycheck.' You would recognize Than's voice anywhere.\nOmar is a few feet behind you as you take steps toward the door. He signals for you to use the peephole to confirm Than's identity.\n You lean towards the closed door and look through the small bit of glass. Outside you see a short, stocky man with dark hair and ruddy cheeks. It's your boss at the transportation agency.\nYour hand reaches for the deadbolt lock and you open the door slowly, allowing Than to come in.\n\nAlia is standing in front on the couch now, arms crossed in her defiant, eleven-year-old way. Even Raya is sitting up looking at the man who has come in to your house.\n"
     )
     let_them_knock.encounter_text.append(False)
     let_them_knock.encounter_text.append(
         "'You could've gotten me killed making me stand outside like that!' Than sighs, the redness in his face spreading from adrenaline. \n'I've never known you to be so rude to a visitor before.' He's referencing your desk work at the transportation agency.\nYou sigh. 'Can't be too careful these days. I'm sorry for putting you at risk, Than.'\n'Yes, I know,' he responds. 'Your heart is too big for that. Which brings me to the reason for my visit.\n\n'I can't stay long. But you've been good to me, good to the agency."
     )
     let_them_knock.encounter_text.append(
         "\nAs a final goodbye, I have a van waiting for you outside. It has supplies that need to be delievered...' \nYou interrupt, 'Than, this doesn't sound like a goodbye present.' \n'Let me finish,' he continues. 'The supplies need to be delivered to a hospital in the next town over. In the much safer town that still has a working hospital. There is space in this van.' he steps toward you and leans forward, 'take your family and be safe before its too late.'"
     )
     let_them_knock.encounter_text.append(False)
     let_them_knock.print_encounter_text()
     self.clear()
     self.choice(
         "'Than.' you sigh, 'Thank you for this.' a) ask about the supplies b) ask about the amount of space that there is in the vehicle",
         self.check_supplies, self.check_space)
示例#17
0
    def play(self):
        result = True
        while result:
            encounter = Encounter.random(self.player)
            result = encounter.run()
            eventhandler(InfoEvent(''))
        eventhandler(InfoEvent(self.player.stats(True) + '\n'))

        score = self.player.gold
        score += sum(i.value for i in self.player.inventory)
        score += int((self.player.level - 1) * 1.1 * BASE_XP_NEEDED / 10)
        score += self.player.xp
        eventhandler(InfoEvent('Score: {}'.format(score)))
        return score
示例#18
0
def update_information():
    listbox_encounters.delete(0, tk.END)

    with open("data/encounters.txt", "r") as file:
        i = 0
        creature_text = ""
        creatures = []
        previous_line = ""
        encounter_end = False

        for line in file:
            if (i == 0):
                listbox_encounters.insert(tk.END,
                                          str(i + 1) + "º - Encontro: " + line)

                title = line
                i += 1

            else:
                # Se o encontro acabou na linha passada, é salvo o título do próximo encontro:
                if encounter_end is True:
                    listbox_encounters.insert(
                        tk.END,
                        str(i + 1) + "º - Encontro: " + line)

                    title = line
                    encounter_end = False
                    i += 1
                # Se ambas as linhas, atual e anterior, estiverem vazias, significará
                # que o encontro acabou:
                elif (not line.strip() and not previous_line.strip()):
                    encounters_saved.append(Encounter(title, creatures))
                    encounter_end = True
                    creatures = []
                # Se apenas a atual estiver vazia, significa que a descrição de uma criatura acabou:
                elif (not line.strip()):
                    creatures.append(Creature(creature_text))
                    creature_text = ""
                # Se não for nenhuma das anteriores, significará que a criatura ainda está sendo descrita:
                else:
                    creature_text += line

            # Salva o conteúdo da linha anterior:
            previous_line = line
def processBatch(a_b):
    a, b = a_b
    d = DatastoreClient()
    p = Patient()
    e = Encounter()
    m = Medication()
    o = Observations()
    dr = DiagnosticReport()
    md = MedicationDispense()
    pr = Procedure()

    all_patient = sorted(p.all_patient())

    for i in range(a, b):
        if i >= len(all_patient):
            break
        id = all_patient[i]
        getPatientRecords(d, p, e, m, o, dr, md, pr, id)

    return True
示例#20
0
    def getInfo(self, path):
        conn = self.getConnection()
        c = conn.cursor()

        c.execute("""SELECT * FROM encounters WHERE filename = ?""", (path, ))
        enc = c.fetchone()
        #print(enc)

        info = None
        e = None

        if enc is not None:
            info = EncounterInfo(*enc)

        if enc is None:
            e = Encounter(path)
            logTime, loglength = e.getLogLength()
            c.execute(
                """SELECT * FROM encounters WHERE timestamp = ? AND loglength = ?""",
                (
                    logTime,
                    loglength,
                ))
            enc = c.fetchone()

        if enc is None:
            e.parseQuick()
            playerDict = {}
            for p in e.players:
                # playerDict += "%s::%s" % (e.entities[p].account, e.entities[p].character)
                # if i < len(e.players) - 1:
                #     playerDict += "\n"
                playerDict[e.entities[p].account] = {}
                playerDict[e.entities[p].
                           account]['character'] = e.entities[p].character
                playerDict[e.entities[p].account]['prof'] = e.entities[p].prof
                playerDict[
                    e.entities[p].account]['elite'] = e.entities[p].elite

            playerDict = json.dumps(playerDict)

            #print(playerDict)

            info = EncounterInfo(e.startTime, loglength, path, e.kill,
                                 e.lowestBossHealth, e.encounterLength, "", "",
                                 e.entities[e.boss_addr].name, playerDict)
            c.execute("""INSERT INTO encounters VALUES(?,?,?,?,?,?,?,?,?,?)""",
                      (e.startTime, loglength, path, e.kill,
                       e.lowestBossHealth, e.encounterLength, "", "",
                       e.entities[e.boss_addr].name, playerDict))
            conn.commit()
            info.new = True
        #
        # c.execute("""SELECT * FROM players WHERE timestamp = ? AND loglength = ?""", (info.timestamp, info.loglength,))
        # players = c.fetchone()
        #
        # if players == None:
        #     if e == None:
        #         e = Encounter(path)
        #
        #     if len(e.players) == 0:
        #         e.parseQuick()
        #
        #     info.players = e.players
        #     while(len(info.players < 10)):
        #         info.players.append("-1")
        #
        #     c.execute("""INSERT INTO players VALUES(?,?,?,?,?,?,?,?,?,?,?,?)""", (info.timestamp, info.loglength, *info.players))
        #     conn.commit()

        return info
示例#21
0
class Game:
    command_return_flags = []
    gamerunning = True
    command_registry = None
    item_registry = None
    player = None
    current_encounter = None

    def __init__(self):
        self.command_registry = CommandRegistry(self)
        self.item_registry = ItemRegistry(self)

        self.player = Player("AAAAA")
        self.player.inventory.add_item(
            self.item_registry.get_item("Crude Bronze Shortsword"))

        enemy = Enemy("Dummy")

        self.current_encounter = Encounter(enemy)

        self.gameloop()

    def gameloop(self):
        while self.gamerunning:
            if self.check_player_dead():
                print_player_death_message()
                return

            # Get player command input
            inputstring = input("\nWhat do you do?: ")
            command = self.command_registry.get_command(
                inputstring.split(" ")[0])

            # Check if command can be used
            if command is not None and\
                    ((self.current_encounter is None and command.can_be_used_outside_encounter) or
                     (self.current_encounter is not None and command.can_be_used_during_encounter)):
                flags = command.action(self, inputstring)
                self.add_command_return_flags(flags)
            else:
                print(f"\nInvalid command '{inputstring.split(' ')[0]}'!\n"
                      f"Type 'help' for a list of all available commands.")
                self.add_command_return_flag(CommandReturnFlag.SKIP_EVERYTHING)

            if self.check_player_dead():
                print_player_death_message()
                return

            # Let enemies act if there is an encounter
            if not self.check_command_return_flag(
                    CommandReturnFlag.SKIP_EVERYTHING):
                if self.current_encounter is not None:
                    self.current_encounter.enemies_act(self)
                    if len(self.current_encounter.enemies) == 0:
                        print("You won the encounter!")
                        self.current_encounter = None

                if self.check_player_dead():
                    print_player_death_message()
                    return

            self.clear_command_return_flags()

    def check_player_dead(self) -> bool:
        # Check if player is dead
        if self.player.hp < 1:
            self.gamerunning = False
            return True
        return False

    # Command return flag methods
    def add_command_return_flag(self, flag):
        if not self.command_return_flags.__contains__(flag):
            self.command_return_flags.append(flag)

    def add_command_return_flags(self, flags):
        if flags is not None:
            for flag in flags:
                self.add_command_return_flag(flag)

    def remove_command_return_flag(self, flag):
        if self.command_return_flags.__contains__(flag):
            self.command_return_flags.remove(flag)

    def check_command_return_flag(self, flag):
        return self.command_return_flags.__contains__(flag)

    def clear_command_return_flags(self):
        self.command_return_flags = []
示例#22
0
 def addEncounterToQuest(self, title):
     # creates many encounters
     encounter = Encounter(title)
     __encounters.insert(encounter)
示例#23
0
 def _update_encounter_status(self):
     self.encounter.check_encounter()
     #print(self.is_encounter_active)
     if self.is_encounter_active == False:
         self.encounter = Encounter(self)
示例#24
0
class EncounterInfoModel(QAbstractItemModel):

    TXT_SUBSQUAD = "Grp"
    TXT_CLASS = ""
    TXT_CHARACTER = "Character"
    TXT_ACCOUNT = "Display Name"
    TXT_DPS = "DPS"
    TXT_BOSS_DPS = "Boss DPS"
    TXT_DMG_TOTAL = "Total"
    TXT_DMG_BOSS = "Total Boss"
    TXT_INCOMING = "Damage In"
    TXT_IN_DPS = "DPS In"
    TXT_DOWN = "Downs"
    TXT_DEAD = "Dead"

    headers = [TXT_SUBSQUAD, TXT_CLASS, TXT_CHARACTER, TXT_ACCOUNT, TXT_DPS, TXT_BOSS_DPS, TXT_DMG_TOTAL, TXT_DMG_BOSS, TXT_DOWN, TXT_DEAD]

    fullOnlyHeaders = [TXT_DOWN, TXT_DEAD, TXT_DPS, TXT_BOSS_DPS, TXT_DMG_TOTAL, TXT_DMG_BOSS]

    progressSignal = pyqtSignal(str, int)

    def __init__(self, parent = None):
        super(EncounterInfoModel, self).__init__()
        self.encounter = None
        self.path = ""
        self.resourceHandler = None
        self.nodes = []
        self.highestRowValue = -1
        self.totalWidth = 0
        self.headerWidths = []
        self.ready = False
        self.sortColumn = 4

        self.callback = None

    def setSortColumn(self, section):
        if self.headers[section] in [self.TXT_DPS, self.TXT_DMG_TOTAL, self.TXT_DMG_BOSS, self.TXT_BOSS_DPS]:
            self.sortColumn = section
            self.findHighestValue()

    def reset(self):
        self.encounter = None
        self.nodes = []
        self.path = ""

    def setup(self, path):
        self.resourceHandler = ResourceHandler()
        self.reset()
        self.path = path
        self.encounter = Encounter(path)
        self.encounter.progressSignal.connect(self.emitProgress)
        self.encounter.quickFinished.connect(self.quickParseFinished)
        job = Job(self.encounter.parseQuick)
        Worker.ThreadPool.start(job)

    def emitProgress(self, s,i):
        self.progressSignal.emit(s,i)

    def getEncounter(self):
        return self.encounter

    def quickParseFinished(self):
        self.layoutAboutToBeChanged.emit()
        self.nodes = []
        for p in self.encounter.players:
            self.nodes.append(EncounterNode(p))
        self.layoutChanged.emit()
        self.emitChange()
        self.encounter.fullFinished.connect(self.emitChange)
        self.encounter.fullFinished.connect(self.findHighestValue)
        job = Job(self.encounter.parseFull)
        Worker.ThreadPool.start(job)

    def emitChange(self):
        self.dataChanged.emit(self.createIndex(0, 0), self.createIndex(len(self.nodes) - 1, len(self.headers) - 1))

    def index(self, row: int, column: int, parent: QModelIndex = ...):
        return self.createIndex(row, column, self.nodes[row])

    def parent(self, child: QModelIndex):
        return QModelIndex()

    def rowCount(self, parent: QModelIndex = ...):
        return len(self.nodes)

    def columnCount(self, parent: QModelIndex = ...):
        return len(self.headers)

    def data(self, index: QModelIndex, role: int = ...):

        if not index.isValid():
            return QVariant()

        node: EncounterNode = index.internalPointer()
        p: Entity = self.encounter.entities[node.player]
        h = self.headers[index.column()]

        if h == self.TXT_CLASS and role == Qt.DecorationRole:
            if node.pixmap is None:
                try:
                    #print("was none")
                    specInfo = self.resourceHandler.getSpecialization(p.elite, p.prof)
                    p = QPixmap()
                    p.loadFromData(specInfo[self.resourceHandler.PROFESSION_ICON])
                    p = p.scaled(QSize(20, 20), Qt.KeepAspectRatio, Qt.SmoothTransformation)
                    node.pixmap = p
                except Exception as e:
                    return QVariant()
            return node.pixmap

        if role == Qt.TextAlignmentRole:
            if h in [self.TXT_SUBSQUAD, self.TXT_CLASS, self.TXT_DEAD, self.TXT_DOWN, self.TXT_DPS, self.TXT_BOSS_DPS, self.TXT_DMG_BOSS, self.TXT_DMG_TOTAL]:
                return Qt.AlignCenter

        if role == Qt.DisplayRole:

            if h == self.TXT_SUBSQUAD:
                return p.subsquad
            if h == self.TXT_CHARACTER:
                return p.character
            if h == self.TXT_ACCOUNT:
                return p.account
            if h == self.TXT_BOSS_DPS:
                return self.encounter.getBossDps(node.player)
            if h == self.TXT_DPS:
                return self.encounter.getTotalDps(node.player)
            if h == self.TXT_DMG_TOTAL:
                return p.damage.totalOut
            if h ==  self.TXT_DMG_BOSS:
                return self.encounter.getBossDamage(node.player)
            if h == self.TXT_DOWN:
                return p.downed
            if h == self.TXT_DEAD:
                return p.dead
            return QVariant()

        if role == Qt.BackgroundRole:
            if not self.encounter.fullComplete:
                return QVariant()
            rightBound = self.headerWidths[index.column()]/self.totalWidth
            leftBound = 0
            if index.column() > 0:
                leftBound = self.headerWidths[index.column() - 1]/self.totalWidth

            # barBound = self.encounter.getTotalDps(node.player)/self.highestRowValue
            if self.highestRowValue == 0:
                barBound = 0
            else:
                barBound = self.data(self.createIndex(index.row(), self.sortColumn, node), Qt.DisplayRole)/self.highestRowValue

            profColor = QColor(*reference.CLASS_COLORS[p.prof], 60)
            if rightBound <= barBound:
                return profColor
            elif leftBound >= barBound:
                return QVariant()
            else:
                colpercent = rightBound - leftBound
                colwidth = 0
                if index.column() > 0:
                    colwidth = self.headerWidths[index.column()] - self.headerWidths[index.column() - 1]
                else:
                    colwidth = self.headerWidths[index.column()]
                toFill = barBound-leftBound

                gradient = QLinearGradient(0, 0, colwidth, 0)
                gradient.setColorAt(toFill/colpercent, profColor)
                gradient.setColorAt((toFill/colpercent) + .000001, QColor('white'))
                brush = QBrush(gradient)
                return brush

    def findHighestValue(self):
        self.highestRowValue = 0
        # for player in self.encounter.players:
        #     d = self.encounter.getTotalDps(player)
        #     if self.highestRowValue < d:
        #         self.highestRowValue = d
        for i in range(0, self.rowCount()):
            val = self.data(self.createIndex(i, self.sortColumn, self.nodes[i]), Qt.DisplayRole)
            if self.highestRowValue < val:
                self.highestRowValue = val
        #print("Highest: %s" % self.highestRowValue)

    def headerData(self, section: int, orientation: Qt.Orientation, role: int = ...):
        if orientation == Qt.Vertical:
            return QVariant()

        if role == Qt.DisplayRole:
            return self.headers[section]

        if role == Qt.InitialSortOrderRole:
            h = self.headers[section]
            if h in [self.TXT_CHARACTER, self.TXT_ACCOUNT, self.TXT_CLASS]:
                return Qt.AscendingOrder
            else:
                return Qt.DescendingOrder
            return QVariant()
示例#25
0
class Alienz:
    # This is the overall class to manage game assets and behaviour

    def __init__(self):
        pygame.init()
        self.clock = pygame.time.Clock()
        self.font = pygame.font.SysFont("Arial", 18)
        self.settings = Settings()
        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption("Alienz")
        self.logger = Logger(self)

        self.earth = Earth(self)
        self.bullets = pygame.sprite.Group()
        self.ships = pygame.sprite.Group()
        self.enemies = pygame.sprite.Group()

        self.is_encounter_active = False
        self.encounter = Encounter(self)

    def run_game(self):
        # main loop for the game
        while True:
            self._check_events()
            self._update_screen()
            self._update_ships()
            self._update_enemies()
            self._update_bullets()
            self._check_collisions()
            self._update_encounter_status()
            self.clock.tick(60)

    def _check_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_a:
                    self.earth.create_factory()
                elif event.key == pygame.K_s:
                    self.earth.create_ship()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                pos = pygame.mouse.get_pos()
                print(pos)

    def _update_screen(self):
        self.screen.fill(self.settings.bg_color)
        self.earth.blitme()
        for factory in self.earth.factories:
            factory.blitme()
        for ship in self.earth.ships:
            ship.blitme()
        for enemy in self.encounter.enemies:
            enemy.blitme()
        for bullet in self.bullets:
            bullet.blitme()

        self.screen.blit(update_fps(self), (3, 0))
        self.screen.blit(
            log_message(self, self.logger.log_message, self.logger.color),
            (800, 0))

        pygame.display.flip()

    def _update_ships(self):
        for ship in self.earth.ships:
            ship.update_position()

    def _update_enemies(self):
        for enemy in self.encounter.enemies:
            enemy.update_position()

    def _update_bullets(self):
        for bullet in self.bullets:
            bullet.update_position()

    def _check_collisions(self):
        collisions = pygame.sprite.groupcollide(self.bullets, self.enemies,
                                                False, False)
        for bullet in collisions:
            collisions[bullet][0].receive_damage(bullet.damage)
            bullet.kill()

    def _update_encounter_status(self):
        self.encounter.check_encounter()
        #print(self.is_encounter_active)
        if self.is_encounter_active == False:
            self.encounter = Encounter(self)
示例#26
0
def load_default_camp():
    # Encounter List Init
    DEFAULT_ENC = list()
    DEFAULT_ENC.append(1)

    foe_lists = list()
    prop_list = list()
    for i in range(3):
        foe_lists.append(list())
        prop_list.append(list())

    # Verdant Wilds: 0      Jagged Pass: 1      Rivermouth: 2
    foe_lists[0].append(deepcopy(c_monsters["Needle Blight"]))
    foe_lists[0].append(deepcopy(c_monsters["Needle Blight"]))
    foe_lists[0].append(deepcopy(c_monsters["Twig Blight"]))
    foe_lists[0].append(deepcopy(c_monsters["Twig Blight"]))
    foe_lists[0].append(deepcopy(c_monsters["Twig Blight"]))
    foe_lists[1].append(deepcopy(c_monsters["Basilisk"]))
    for num in range(5):
        foe_lists[2].append(deepcopy(c_monsters["Aarakocra"]))

    boulder = Inanimate("boulder", icon="./assets/boulder.png", item_code=0, details="A boulder to block paths")
    boulder.set_coors(2, 5)
    prop_list[0].append(deepcopy(boulder))
    boulder.set_coors(7, 4)
    prop_list[0].append(deepcopy(boulder))

    boulder.set_coors(5, 8)
    prop_list[1].append(deepcopy(boulder))
    boulder.set_coors(5, 7)
    prop_list[1].append(deepcopy(boulder))
    boulder.set_coors(6, 6)
    prop_list[1].append(deepcopy(boulder))
    boulder.set_coors(7, 5)
    prop_list[1].append(deepcopy(boulder))
    boulder.set_coors(8, 5)
    prop_list[1].append(deepcopy(boulder))

    for x_coors in range(15):
        boulder.set_coors(x_coors, 0)
        prop_list[2].append(deepcopy(boulder))

    boulder.set_coors(7, 10)
    prop_list[2].append(deepcopy(boulder))
    boulder.set_coors(7, 11)
    prop_list[2].append(deepcopy(boulder))
    boulder.set_coors(6, 11)
    prop_list[2].append(deepcopy(boulder))
    boulder.set_coors(7, 12)
    prop_list[2].append(deepcopy(boulder))

    # Non-combat Encounters
    DEFAULT_ENC.append(Encounter("[Zinnia] The Leaky Tap", bkgd="./assets/tavern.jpg"))
    DEFAULT_ENC.append(Encounter("[Zinnia] Al's Apothecary", bkgd="./assets/apothecary.jpg"))
    DEFAULT_ENC.append(Encounter("[Zinnia] The Bazaar", bkgd="./assets/bazaar.jpg"))

    DEFAULT_ENC.append(Encounter("[Adgard] Coral Inn", bkgd="./assets/coralinn.jpg"))
    DEFAULT_ENC.append(Encounter("[Adgard] Bard's Den", bkgd="./assets/tavern2.jpg"))
    DEFAULT_ENC.append(Encounter("[Adgard] Crownguard HQ", bkgd="./assets/guardhq.jpg"))

    # Combat Encounters
    DEFAULT_ENC.append(CEncounter("Verdant Wilds", bkgd="./assets/verdantwilds.jpg", anim=foe_lists[0], inanim=prop_list[0]))
    DEFAULT_ENC.append(CEncounter("Jagged Pass", bkgd="./assets/jaggedpass.jpg", anim=foe_lists[1], inanim=prop_list[1]))
    DEFAULT_ENC.append(CEncounter("Rivermouth", bkgd="./assets/rivermouth.jpg", anim=foe_lists[2], inanim=prop_list[2]))

    return DEFAULT_ENC
示例#27
0
    def test_encounter(self):
        encounter = Encounter()

        char1 = Character.create(
            name="Player A",
            start_class="Fighter",
            str_modify=6,
            dex_modify=2,
            con_modify=4,
            int_modify=2,
            wis_modify=0,
            chr_modify=0,
            unit_main_hand_weapon=SHORT_SWORD_MEDIUM,
            unit_off_hand_weapon=LIGHT_WOOD_SHIELD_MEDIUM,
            unit_armor=SPLINT_MAIL_MEDIUM,
        )
        char1.team = "party"
        char1.ask_ability_bonus = MagicMock(return_value="unit_str")

        char1.gain_level("Fighter")
        char1.gain_level("Fighter")
        char1.gain_level("Fighter")
        print(
            "Char stats: HP:%d/%d %s" %
            (char1.unit_hp, char1.unit_hp_max, char1.get_base_attack_bonus()))
        char1.get_command = MagicMock(return_value=["attack", "1"])

        # char2 = Character.create(
        #     name="Player B",
        #     start_class="Fighter",
        #     str_modify=6,
        #     dex_modify=2,
        #     con_modify=4,
        #     int_modify=2,
        #     wis_modify=0,
        #     chr_modify=0,
        #     init_weapon=SHORT_SWORD_MEDIUM,
        #     )
        # char2.team = "party"
        # char2.gain_level("Fighter")
        # char2.gain_level("Fighter")
        # char2.gain_level("Fighter")
        # print("Char stats: HP:%d/%d %s" % (char2.unit_hp, char2.unit_hp_max, char2.get_base_attack_bonus()))
        # char2.get_command = MagicMock(return_value=["attack", "2"])

        gob1 = Goblin.create(name='goblin', unit_level=5)
        gob2 = GoblinCaster.create(name='goblin caster', unit_level=5)
        gob3 = GoblinHealer.create(name='goblin header', unit_level=7)
        encounter.add_unit(char1)
        # encounter.add_unit(char2)
        encounter.add_unit(gob1)
        encounter.add_unit(gob2)
        encounter.add_unit(gob3)

        win_team = None
        try:
            encounter.run_until_exception()
        except BattleFinishedException as e:
            win_team = e.team_win
            print("team %s wins!" % win_team)
            print("unit dead:", encounter.unit_dead_list)
示例#28
0
    def set_vitals(self, bundle, prefix=None):
        """Attaches the patient vitals to the given patient bundle"""

        # blood pressure measurements
        bps = []

        # other vitals data
        othervitals = []

        if self.pid in VitalSigns.vitals:

            encounters = []

            # for each vital of this patient
            for v in VitalSigns.vitals[self.pid]:
                # print v.asTabString()
                encounter_id = None

                # Look for encounter of same type on the same date...
                e = [
                    i for i in encounters
                    if i.has_key("id") and i['date'] == v.start_date
                    and i['type'] == v.encounter_type
                ]
                if len(e) > 0:
                    encounter_id = e[0]['id']
                else:
                    encounter_id = uid(None, v.id, prefix)
                    encounters.append({
                        'date': v.start_date,
                        'type': v.encounter_type,
                        'id': encounter_id
                    })

                    # Add the encounter tot the transaction bundle
                    if GENERATION_MAP["Encounter"]:
                        bundle["entry"].append(
                            Entry(
                                Encounter(
                                    {
                                        'start_date': v.start_date,
                                        'end_date': v.end_date,
                                        'encounter_type': v.encounter_type,
                                        'pid': self.pid,
                                        'id': encounter_id
                                    }, prefix)))

                for vt in VitalSigns.vitalTypes:
                    try:
                        othervitals.append(getVital(v, vt, encounter_id))
                    except:
                        pass

                # Find and prepare blood pressure measurements
                try:
                    systolic = getVital(v, VitalSigns.systolic, encounter_id)
                    diastolic = getVital(v, VitalSigns.diastolic, encounter_id)
                    bp = systolic  # just use that as base structure
                    bp['systolic'] = int(systolic['value'])
                    bp['diastolic'] = int(diastolic['value'])
                    bp['site'] = v.bp_site
                    bp['id'] = v.id
                    bp['pid'] = self.pid

                    # site
                    if bp['site']:
                        for pc in VitalSigns.bpPositionCodes:
                            if pc['name'] == bp['site']:
                                bp['site_code'] = pc['code']
                                bp['site_system'] = pc['system']

                    # method
                    bp['method'] = v.bp_method
                    if bp['method']:
                        for pc in VitalSigns.bpPositionCodes:
                            if pc['name'] == bp['method']:
                                bp['method_code'] = pc['code']
                                bp['method_system'] = pc['system']

                    # position
                    bp['position'] = v.bp_position
                    if bp['position']:
                        for pc in VitalSigns.bpPositionCodes:
                            if pc['name'] == bp['position']:
                                bp['position_code'] = pc['code']
                                bp['position_system'] = pc['system']

                    bps.append(bp)

                except:
                    pass

        if GENERATION_MAP["BloodPressure"]:
            for bp in bps:
                bundle["entry"].append(Entry(BloodPressure(bp, prefix)))

        # Append other vitals as Observation entries to the transaction bundle
        if GENERATION_MAP["Vitals"]:
            for o in othervitals:
                if "units" in o.keys():
                    o["id"] = '%s-%s' % (uid(
                        None, None, prefix), o["name"].lower().replace(
                            ' ', '').replace('_', ''))
                    o["unitsCode"] = o["units"]
                    o["categoryCode"] = "vital-signs"
                    o["categoryDisplay"] = "Vital Signs"
                    o["pid"] = self.pid
                bundle["entry"].append(Entry(Observation(o, prefix)))

        return bundle
示例#29
0
    def gen_creature(self):
        print("gen_creature")
        new_creature = Encounter()
        template = preset_data()
        enc_type = self.ui.comboBox_type.itemText(
            self.ui.comboBox_type.currentIndex())
        attributes = template.get_options(enc_type,'attribute')
        attacks = template.get_options(enc_type,'weapon')
        misc  = template.get_options(enc_type,'misc')
        cr_from_ui = self.ui.spinBox_CR.value()
        num_in_group = self.ui.spinBox_group.value()
        TargetCR = cr_from_ui - self.sqrt(num_in_group)
        new_creature.set_option('speed',self.locomotives)
        new_creature.set_option('size', str(self.ui.comboBox_size.itemText(
            self.ui.comboBox_size.currentIndex())))
        new_creature.set_option('name', str(self.ui.lineEdit_Name.text()))
        new_creature.set_option('encountergroupOf', int(self.ui.spinBox_group.value()))
        new_creature.set_option('cr', TargetCR)
        stats = template.get(TargetCR)
        for stat in stats.keys():
            new_creature.set_option(stat, stats[stat])
        options = self.help_collect_options()
        print("things after")
        for opt in options:
            print("option")
            for attribute in attributes:
                # print("attribute")
                if opt in attribute[0]:
###################################################                    # wtf??
                    self.data['abilities'].append(attribute[0])
                    # maybe
                    # .......
###################################################
            pos_atk = opt[0:-8]
            for weapon in attacks:
                # print("weapon")
                if pos_atk in weapon[2:]:
                    attacks = new_creature.get_option('atk_weapon')
                    if not weapon in attacks:
                        attacks.append(weapon)
                        new_creature.set_option('atk_weapon', attacks)
            pos_misc = opt[0:-5]
            for action in misc:
                # print("actions")
                if pos_misc in action[2:]:
                    misc_actions = new_creature.get_option('misc_actions')
                    if not misc in misc_actions:
                        misc_actions.append(misc)
                        new_creature.set_option('misc_actions',
                                                 misc_actions)
        print("after loops")
        new_creature.set_option('STR',self.ui.spinBox_STR.value())
        new_creature.set_option('DEX',self.ui.spinBox_DEX.value())
        new_creature.set_option('CON',self.ui.spinBox_CON.value())
        new_creature.set_option('WIS',self.ui.spinBox_WIS.value())
        new_creature.set_option('INT',self.ui.spinBox_INT.value())
        new_creature.set_option('CHA',self.ui.spinBox_CHA.value())
        new_creature.gen_actions()
        print("after gen_actions")
        return new_creature