Beispiel #1
0
 def __init__(self, name):
     map_data = load_json("static/maps.JSON", name)
     self.name = name
     self.npcs = load_json("static/npcs.JSON", self.name)
     self.special = None
     self.locations = map_data["locations"]
     self.passive = map_data["passive"]
Beispiel #2
0
        async def on_message(message):
            from interpreter.interpreter import Interpreter
            message_and_reply_json = load_json(paths.message_and_reply)
            for key_message in message_and_reply_json.keys():

                actual = message_and_reply_json[key_message]

                to_read = [
                    'expected message', 'reply', 'reaction', 'conditions',
                    'delete', 'pin', 'delay', 'kick', 'ban', 'where reaction',
                    'where reply'
                ]
                to_insert = dict()

                for each in to_read:
                    to_insert[each] = None
                    if each in actual:
                        to_insert[each] = actual[each]

                await Interpreter.message_and_reply(
                    self,
                    message=message,
                    conditions=to_insert['conditions'],
                    expected_message=to_insert['expected message'],
                    reply=to_insert['reply'],
                    reaction=to_insert['reaction'],
                    delete=to_insert['delete'],
                    pin=to_insert['pin'],
                    delay=to_insert['delay'],
                    kick=to_insert['kick'],
                    ban=to_insert['ban'],
                    where_reply=to_insert['where reply'],
                    where_reaction=to_insert['where reaction'])
Beispiel #3
0
 def load(self, name):
     this_char =  load_json("saves/characters.JSON", name)
     self.name = name
     self.classrole = this_char["classrole"]
     self.xp = this_char["xp"]
     self.calc_level()
     return self
Beispiel #4
0
 def update_token(self):
     '''atualiza o token no arquivo "config.json" e na interface.'''
     from functions import load_json, save_json
     entrada:str = self.inserir_token.get()
     if len(entrada) == 59:
         self.inserir_token.delete(0, tk.END)
         current_dict = load_json(path.config)
         current_dict['token'] = entrada
         save_json(path.config, current_dict)
         self.token_atual['text'] = f'Seu token atual é:\n{entrada}'
Beispiel #5
0
def start_scenario(player):

    map_data = load_json("static/maps.JSON")

    options = [x for x in map_data if map_data[x]["min_level"] <= player.level]
    print("player level: ", player.level)
    map_decision = print_choices('Where would you like to travel?', options)
    clear()
    this_map = Map(map_decision)
    this_encounter = Encounter(this_map)
    this_encounter.start_encounter()
Beispiel #6
0
 def load_info_messages(self):
     '''carrega todas as mensagens do arquivo "message and reply.json" e insere no listbox de 
     mensagens.'''
     import json
     from functions import load_json, save_json
     try:
         all_messages = load_json(path.message_and_reply)
     except json.decoder.JSONDecodeError:
         pass
     else:
         for x in all_messages.keys():
             self.todas_mensagens.insert(tk.END, x)
Beispiel #7
0
def loadsave(DEBUG):
    choices = list(load_json("saves/characters.JSON").keys())
    choice_list = create_options(choices)
    character_name = choices[int(
        input(f'Select your character name from the following\n{choice_list}\n'
              )) - 1]
    this_char = Character()
    this_char.load(character_name)
    system('cls')
    print(f'{this_char.name} loaded, your adventure continues...')
    sleep(2)
    system('cls')
    return this_char
Beispiel #8
0
    def load_info(self):
        from functions import load_json, save_json
        if self.load:
            messages_json: dict = load_json(path.message_and_reply)
            todas_info: dict = messages_json[self.load]
            if 'expected message' in todas_info:
                expected_message = todas_info['expected message']
                if expected_message:
                    for x in expected_message:
                        self.listbox_messages.insert(tk.END, x)
            if 'reply' in todas_info:
                reply = todas_info['reply']
                if reply:
                    for x in reply:
                        self.listbox_replys.insert(
                            tk.END, '¨'.join(x)) if type(
                                x) == list else self.listbox_replys.insert(
                                    tk.END, x)
            if 'reaction' in todas_info:
                reaction = todas_info['reaction']
                if reaction:
                    list(
                        map(
                            lambda x: self.listbox_reactions.insert(
                                tk.END, ' '.join(x)), reaction))
            if 'conditions' in todas_info:
                conditions = todas_info['conditions']
                if conditions:
                    for x in conditions:
                        self.listbox_conditions.insert(tk.END, x)
            if 'pin' in todas_info:
                pin = todas_info['pin']
                if pin == True:
                    self.pin_or_del.set('Fixar')
            if 'delete' in todas_info:
                delete = todas_info['delete']
                if delete == True:
                    self.pin_or_del.set('Remover')

            if 'delay' in todas_info:
                delay = todas_info['delay']
                self.delay_variable.set(delay)

            if 'where reply' in todas_info:
                where_reply = todas_info['where reply']
                self.variable_where_reply.set(where_reply)

            if 'where reaction' in todas_info:
                where_reaction = todas_info['where reaction']
                self.variable_where_reaction.set(where_reaction)
Beispiel #9
0
 def remove_message(self):
     '''remove a mensagem selecionada do listbox de mensagens e a deleta do arquivo "message and 
     reply.json".'''
     from functions import load_json, save_json
     lista_nomes = self.todas_mensagens.get(0, tk.END)
     try:
         selecionado = self.todas_mensagens.curselection()[0]
     except IndexError:
         pass
     else:
         nome_selecionado:str = lista_nomes[selecionado]
         self.todas_mensagens.delete(selecionado)
         message_and_reply_json = load_json(path.message_and_reply)
         del message_and_reply_json[nome_selecionado]
         save_json(path.message_and_reply, message_and_reply_json)
Beispiel #10
0
    def __init__(self):
        client = discord.Client()
        token = load_json(paths.config)['token']
        clear_txt(paths.log)

        @client.event
        async def on_ready():
            write_log(hora_atual() + ' Bot inicializado.', paths.log)

        @client.event
        async def on_message(message):
            from interpreter.interpreter import Interpreter
            message_and_reply_json = load_json(paths.message_and_reply)
            for key_message in message_and_reply_json.keys():

                actual = message_and_reply_json[key_message]

                to_read = [
                    'expected message', 'reply', 'reaction', 'conditions',
                    'delete', 'pin', 'delay', 'kick', 'ban', 'where reaction',
                    'where reply'
                ]
                to_insert = dict()

                for each in to_read:
                    to_insert[each] = None
                    if each in actual:
                        to_insert[each] = actual[each]

                await Interpreter.message_and_reply(
                    self,
                    message=message,
                    conditions=to_insert['conditions'],
                    expected_message=to_insert['expected message'],
                    reply=to_insert['reply'],
                    reaction=to_insert['reaction'],
                    delete=to_insert['delete'],
                    pin=to_insert['pin'],
                    delay=to_insert['delay'],
                    kick=to_insert['kick'],
                    ban=to_insert['ban'],
                    where_reply=to_insert['where reply'],
                    where_reaction=to_insert['where reaction'])

        client.run(token)
Beispiel #11
0
def newgame(DEBUG):

    char_name = input("Type a character name and press Enter\n")
    name_exist_check = load_json('saves/characters.JSON')
    if char_name in list(name_exist_check.keys()):
        confirm_overwrite = input(
            f'This will delete your existing character named {char_name}, would you like to continue anyway\ny/n?'
        ).lower()
        if 'n' in confirm_overwrite:
            return start(DEBUG)
    class_role_options = list(classnames.keys())
    options = '\n'.join(
        [f'[{count + 1}]: ' + x for count, x in enumerate(class_role_options)])
    char_class = class_role_options[
        int(input(f'Chose one of the following classes:\n{options}\n')) - 1]
    char_object = Character(char_name, char_class)
    char_object.save()
    system('cls')
    print(
        f'New Character {char_object.name} created. Your adventure begins...')
    sleep(2)
    system('cls')
    return char_object
Beispiel #12
0
        async def on_message(message: discord.Message):
            setdelay = re.findall(r'^\!slowmode set ([0-9]+)', message.content)
            base = functions.load_json('whitelist.json')

            if isinstance(
                    message.channel,
                    discord.TextChannel) and config.slowmode and not (
                        message.author.id in base['whitelist']
                        or message.channel.id in base['channel whitelist']
                        or True in list(
                            map(
                                lambda r: True
                                if r.id in base['role whitelist'] else False,
                                message.author.roles))):
                if not message.author.id in who_cant_say:
                    who_cant_say[message.author.id] = datetime.now(
                    ) + timedelta(seconds=config.delay)
                else:
                    if datetime.now() < who_cant_say[message.author.id]:
                        await message.delete()
                        await self.send_dm(
                            f'O canal está em modo slow mode, você precisa esperar {config.delay} segundos para digitar novamente.',
                            message)
                    else:
                        del who_cant_say[message.author.id]

            if message.content.lower().startswith(
                    commands.APPEND_TO_WHITELIST):
                for var, key in [[message.mentions, 'whitelist'],
                                 [
                                     message.channel_mentions,
                                     'channel whitelist'
                                 ], [message.role_mentions, 'role whitelist']]:
                    if len(var) >= 1:
                        for m in var:
                            if not m.id in base[key]:
                                base[key].append(m.id)

                functions.save_json('whitelist.json', base)

            elif message.content.lower().startswith(
                    commands.REMOVE_FROM_WHITELIST):

                for var, key in [[message.mentions, 'whitelist'],
                                 [
                                     message.channel_mentions,
                                     'channel whitelist'
                                 ], [message.role_mentions, 'role whitelist']]:
                    if len(var) >= 1:
                        for m in var:
                            if m.id in base[key]:
                                base[key].remove(m.id)

                functions.save_json('whitelist.json', base)

            elif setdelay:
                if message.author.id == message.guild.owner_id:
                    config.delay = int(setdelay[0])
                    await self.send_dm(
                        f'O slowmode foi definido para {config.delay} segundos.',
                        message)
                else:
                    await self.send_dm(
                        'Apenas o dono do servidor pode modificar o slow mode.',
                        message)

            elif message.content.lower() == commands.TO_ACTIVE:
                if message.author.id == message.guild.owner_id:
                    config.slowmode = True
                    await self.send_dm('O slowmode foi ativado.', message)
                else:
                    await self.send_dm(
                        'Apenas o dono do servidor pode ativar ou desativar o slow mode.',
                        message)

            elif message.content.lower() == commands.TO_DESACTIVE:
                if message.author.id == message.guild.owner_id:
                    config.slowmode = False
                    await self.send_dm('O slowmode foi desativado.', message)
                else:
                    await self.send_dm(
                        'Apenas o dono do servidor pode ativar ou desativar o slow mode.',
                        message)

            elif message.content.lower() == commands.TO_LIST and isinstance(
                    message.channel, discord.TextChannel):
                members = []
                channels = []
                roles = []
                for ID in base['whitelist']:
                    members.append(message.guild.get_member(ID).name)
                for ID in base['channel whitelist']:
                    channels.append(message.guild.get_channel(ID).name)
                for ID in base['role whitelist']:
                    roles.append(message.guild.get_roles(ID).name)

                await self.send_dm(
                    f'Whitelist:\nMembros: {",".join(members) if len(members) >= 1 else "Nenhum"}\nCanais: {",".join(channels) if len(channels) >= 1 else "Nenhum"}\nCargos: {",".join(roles) if len(roles) >= 1 else "Nenhum"}',
                    message)
def perturb_KT_model(perturbation,
                     stud_params=None,
                     params_file=None,
                     directory=None):
    stud_params = stud_params or func.load_json(params_file, directory)
Beispiel #14
0
 def get_token(self):
     '''retorna o token atual salvo no arquivo "config.json".'''
     from functions import load_json
     return load_json(path.config)['token']
Beispiel #15
0
def move(array, speler):
    DRAWADJUST = 100
    WINADJUST = 1000000000
    LOSEADJUST = -1

    board = array
    player = speler

    # init moves during game
    movesduringgame = functions.load_json(f'/tmp/moves')

    big_db = functions.load_json('db.json')

    freefields = functions.free_fields(deepcopy(board))

    # did we lose when the other side moved?
    ff_json = functions.load_json(f'/tmp/freefields')

    count = ff_json['freefields']
    # print(f'SAVED FREE FIELDS: {count}')
    # print(f'CURRENT FREE FIELDS: {freefields}')

    if freefields > count:
        #we lost :(
        adjust = LOSEADJUST
        functions.update_database(movesduringgame, big_db, adjust)
        functions.save_json('db.json', big_db)
        movesduringgame = {}

    boardhash = functions.gamestate_hash(board)
    # print('\n\n<BOT> BOARD HASH', str(boardhash))

    # print('BH NOT IN BIG DB:')
    # print(boardhash not in big_db)
    if boardhash not in big_db:
        # print('inverting board')
        board = functions.invert_board(deepcopy(board))
        # print(board)
        player = 2 if player == 1 else 1
        boardhash = functions.gamestate_hash(board)
        # print('<BOT> str2' + str(boardhash))

    possiblemoves = functions.fetch_moves(big_db, boardhash)
    # print('<BOT>' + str(possiblemoves))

    newmove = functions.generate_move(possiblemoves)

    movesduringgame.update({boardhash: [newmove[0], newmove[1]]})
    # print()
    # print('<BOT> mdg ' + str(movesduringgame))
    # print('<BOT> bh ' + str(boardhash))

    board = functions.update_board(board, newmove, player)

    endgame = functions.game_end(board)

    if endgame in [3, 1, 2]:
        if endgame == 3:
            # phew, a draw
            adjust = DRAWADJUST
        elif endgame == player:
            # WE WIN!!!!11!!!!
            adjust = WINADJUST
        else:
            # WE LOST :((((((
            adjust = LOSEADJUST
        # print(big_db)
        # print('<BOT> bigdb (noup)'+str(big_db))
        # print('<BOT> mdg  '+str(movesduringgame))
        functions.update_database(movesduringgame, big_db, adjust)
        # print('<BOT> bigdb  '+str(big_db))

        functions.save_json('db.json', big_db)
        movesduringgame = {}  # reset array of played moves

    # detect if we draw or lose next turn
    free = functions.free_fields(board)

    freefields = {'freefields': free}
    if free == 1:

        emp_field = [-1, -1]
        for y in range(len(board)):
            for x in range(len(board)):
                if board[y][x] == 0:
                    emp_field = [y, x]
        # fill it with the opposing player's number
        opp_player = 2 if player == 1 else 1
        board = functions.update_board(deepcopy(board), emp_field, opp_player)
        endgame = functions.game_end(board)
        if endgame == 3:
            adjust = DRAWADJUST
        elif endgame == opp_player:
            adjust = LOSEADJUST
        functions.update_database(movesduringgame, big_db, adjust)
        functions.save_json('db.json', big_db)
        movesduringgame = {}
        freefields = {'freefields': 15}

    functions.save_json(f'/tmp/freefields', freefields)

    # write movesduringgame out to file
    functions.save_json(f'/tmp/moves', movesduringgame)

    # # print('<BOT> newmv  '+str(newmove))

    # print(f'<BOT>  {type(newmove)}, {type(newmove[0])}, {type(newmove[1])}\n\n\n\n')
    return newmove
import functions as fnc
import gui

if __name__ == "__main__":
    player_name_list = fnc.load_json()
    gui.vp_start_gui(player_name_list)
    fnc.save_json()
#       Iterate over all product price listings
#       Try to find a match
#       If the match is good, add it to the list
#
#   For our purposes we assume the following:
#       Manufacturer is spelled correctly
#       Manufacturer in product listing and product has been normalized
#       It is ok to have an offline algorithm

from functions import load_json, calculate_score, get_related_products

PRODUCT_FILE = "products.txt"
LISTING_FILE = "listings.txt"
THRESHOLD = 0

listings = load_json(LISTING_FILE)
products = load_json(PRODUCT_FILE)

matches = {}

for listing in listings:
    related_products = get_related_products(listing, products)
    potential_matches = [];
    for product in related_products:
        score = calculate_score(listing, product)
        potential_matches.append({"score": score, "product": product})
    if potential_matches:
        best_match = max(potential_matches, key=lambda x: x["score"])
        if best_match["score"] >= THRESHOLD:
            product_name = best_match["product"]["product_name"];
            matches.setdefault(product_name, {}).setdefault("listings", []).append(listing)
Beispiel #18
0
    def save_all_json(self):
        '''salva toda a informação que o usuario preencheu na interface em forma de json, para que depois
        o interpretador do bot consiga interpretar'''
        import json
        from interfaces.commands.main import MainCommands
        from functions import load_json, save_json, have_in
        import re
        try:
            dict_base = load_json(path.message_and_reply)
        except json.decoder.JSONDecodeError:
            name = '1'
            dict_base = dict()
        else:
            if not self.load:
                name = '1'
                chaves_dict_base = list(dict_base.keys())
                chaves_dict_base.reverse()
                for x in chaves_dict_base:
                    try:
                        chave = int(x)
                    except ValueError:
                        pass
                    else:
                        name = str(chave + 1)
                        break
            else:
                name = self.load
                if self.new_name:
                    name = self.new_name
                    del dict_base[self.load]

        # anti-bug
        self.load = name

        dict_base[name] = {}

        lista_expected_message = self.listbox_messages.get(0, tk.END)
        dict_base[name][
            'expected message'] = lista_expected_message if not len(
                lista_expected_message) == 0 else None

        lista_reply = self.listbox_replys.get(0, tk.END)
        dict_base[name]['reply'] = list(
            map(lambda x: x.split('¨'), lista_reply)) if have_in(
                lista_reply, '¨', reverse=True
            ) else lista_reply if not len(lista_reply) == 0 else None

        lista_reactions = self.listbox_reactions.get(0, tk.END)
        dict_base[name]['reaction'] = list(
            map(lambda x: re.findall(r':[a-zA-Z_0-9]+:', x),
                lista_reactions)) if not len(lista_reactions) == 0 else None

        lista_conditions = self.listbox_conditions.get(0, tk.END)
        dict_base[name]['conditions'] = lista_conditions if not len(
            lista_conditions) == 0 else None

        if self.pin_or_del.get() == 'Fixar':
            dict_base[name]['pin'] = True
        elif self.pin_or_del.get() == 'Remover':
            dict_base[name]['delete'] = True

        dict_base[name]['where reply'] = self.variable_where_reply.get()

        dict_base[name]['where reaction'] = self.variable_where_reaction.get()

        dict_base[name]['delay'] = self.delay.get()

        save_json(path.message_and_reply, dict_base)
        MainCommands.refresh_messages(self)
 def test_load_json(self):
     # Test that function loads JSON file #
     with open('data/riddles.json', 'r') as file:
         json_decoded = json.load(file)
         self.assertEqual(load_json('data/riddles.json', 'r'), json_decoded)