Beispiel #1
0
def is_ascii(word):
    if type(word) == str:
        for letter in word:
            if ascii_letters.find(letter) == -1 and letter != " ":
                return False
                break
        return True
    else:
        raise TypeError("Must be an string type.")
Beispiel #2
0
 def get_difference(self, train_model, key):
     difference = 0
     for symbol in train_model:
         shifted_symbol = ALPHABET[(ALPHABET.find(symbol) - key) %
                                   ALPHABET_SIZE]
         if shifted_symbol in self.model.keys():
             difference += fabs(self.model[shifted_symbol] -
                                train_model[symbol])
         else:
             difference += fabs(train_model[symbol])
     return difference
Beispiel #3
0
def charcount(c):
    global word
    cnt = 0
    for i in word:
        p = ascii_letters.find(c)
        if p > 26:
            if i == ascii_letters[p] or i == ascii_letters[p - 26]:
                cnt = cnt + 1
        else:
            if i == ascii_letters[p] or i == ascii_letters[p + 26]:
                cnt = cnt + 1
    return cnt
Beispiel #4
0
def charsearch(c):
    global word
    for i in range(len(word)):
        p = ascii_letters.find(c)
        if p > 26:
            if word[i] == ascii_letters[p] or word[i] == ascii_letters[p - 26]:
                return i
        else:
            if word[i] == ascii_letters[p] or word[i] == ascii_letters[p + 26]:
                return i
    else:
        return -1
Beispiel #5
0
def resolve_second_puzzle(polymer):
    shortest_polymer_length = 9999

    for letter in ascii_lowercase:
        letter_index = ascii_letters.find(letter)
        letter_uppercase = ascii_letters[letter_index + 26]

        temp_polymer = polymer

        temp_polymer = list(
            filter(lambda a: a != letter and a != letter_uppercase,
                   temp_polymer))
        temp_polymer_length = resolve_first_puzzle(temp_polymer)

        if temp_polymer_length < shortest_polymer_length:
            shortest_polymer_length = temp_polymer_length

    print("Shortest polymer we can produce: " + str(shortest_polymer_length))
Beispiel #6
0
def encrypt(message, shift):
    result = []
    capitals = len(al) / 2
    is_string = False
    if isinstance(message, (basestring)):
        is_string = True
        message = [message]
    for line in message:
        processed = ""
        for character in line:
            i = al.find(character)
            if i > -1:
                j = (i + shift) % capitals
                processed += al[j] if i < capitals else al[j + capitals]
            elif i == -1:
                processed += character
        result.append(processed)
    return result if not is_string else result[0]
Beispiel #7
0
def hillAlgorithm(text, key, option):
    matrix_key = np.matrix(key)

    #inv(A) = 1/det(A) * cof(A).T
    #cof(A).T = inv(A) * det(A)
    #k^-1 = d^-1 * adj(k)
    #Para desencriptar se requiere hallar la matriz inversa modular
    #El proceso es parecido a hallar la inversa se debe multiplicar
    #la matriz de cofactores por el inverso modular del determinante
    #de A y sacarle el modulo 26
    if option != '1':
        det_matrix = abs(round(np.linalg.det(matrix_key), 1))
        cof_matrix = matrix_key.I * det_matrix
        inv_modular = extendedEuclidean(det_matrix, 26)[1] % 26
        matrix_key = (cof_matrix * inv_modular) % 26

    block_size = matrix_key.shape[0]
    text = formatText(block_size, text)

    solution = []

    #Recorre el texto plano en bloques multiplicando cada bloque
    #por la matriz llave
    for i in range(0, len(text), block_size):
        codes_letters = []
        for j in range(block_size):
            codes_letters.append(ascii_letters.find(text[i + j]))

        vector_block_text = np.array(codes_letters)

        #Multiplica el vector de letras por la llave con modulo 26
        solution_block = np.array((vector_block_text * matrix_key) % 26)

        #Recorre el arreglo de numpy para sacar los elementos
        solution += [
            ascii_letters[int(round(item, 1))] for item in solution_block[0]
        ]

    return formatSolution(solution, block_size)
Beispiel #8
0
def resolve_first_puzzle(polymer):
    current_index = 0

    while polymer.__len__() - 1 > current_index:
        current_letter_index = ascii_letters.find(polymer[current_index])

        if current_letter_index < 26:
            current_letter_equivalent = current_letter_index + 26

        else:
            current_letter_equivalent = current_letter_index - 26

        if polymer[current_index +
                   1] == ascii_letters[current_letter_equivalent]:
            del polymer[current_index:current_index + 2]
            if current_index > 0:
                current_index -= 1

        else:
            current_index += 1

    print("Units remaining after fully reacting: " + str(polymer.__len__()))
    return polymer.__len__()
Beispiel #9
0
def LetterChanges(str):

    # Initialise a new string to create a new sentence after the letters have been replaced
    new_string = ""

    # Find the location of each letter from the original string in the ascii string
    for letter in str:
        # Check to see if the letter is in the alphabet
        if letter in (ascii_letters or ascii_uppercase):
            # Find its position in the ascii_letters string
            ascii_position = ascii_letters.find(letter)
            # Move the position up by one and add the ascii letter at this location to the new string
            new_string += ascii_letters[ascii_position + 1]
        # If the letter is not in the alphabet (e.g. a special character or a number), add it to the new string as normal
        else:
            new_string += letter

    for letter in new_string:
        # Check to see if the letter is a vowel
        if letter in ('a', 'e', 'i', 'o', 'u'):
            # If it is a lowercase vowel, replace it with a capitalized version
            new_string = new_string.replace(letter, letter.upper())
    return new_string
Beispiel #10
0
 def next_char(char):
     pos = ascii_letters.find(char)
     if pos != -1:
         char = ascii_letters[(pos + 1) % len(ascii_letters)]
     return str(char)
Beispiel #11
0
def convert():
    parser = argparse.ArgumentParser(
        prog="Rapid Pygame level converter",
        description="""Convert Rapid Pygame level
                       file into Tiled map file or vise versa""",
        epilog="Refer to the documentation specifics about the formats",
    )
    parser.add_argument(
        "file", metavar="file", type=str, help="the Rapid Pygame level file or Tiled map file to convert"
    )
    parser.add_argument("-o", "--output", metavar="result", type=str, help="the name of the converted file")
    parser.add_argument(
        "--per-line",
        metavar="n",
        type=int,
        default=10,
        help="the number of tile images per line " "when generating tile set for Tiled. Default is 10",
    )

    args = parser.parse_args()
    try:
        # Tiled to Rapid Pygame
        tree = ET.parse(args.file)
        lvl = tree.find("layer/data").text.strip() + ","
        lvl = [x for x in lvl.split("\n")]
        result = ""
        # there can only be 61 different tiles in a given map. Should be enough
        characters = set()
        max_tile = 0
        for l in lvl:
            for c in l.strip()[:-1].split(","):
                as_int = int(c)
                final_c = c
                if as_int > 9:
                    final_c = ascii_letters[as_int - 10]
                if as_int > max_tile:
                    max_tile = as_int
                result += final_c
                characters.add(final_c)
            result += "\n"
        # take out the new line at the end
        result = result[:-1]

        header = ""
        has_collision = False
        for e in tree.findall("properties/property"):
            header += "{0} {1}\n".format(e.get("name"), e.get("value"))
            if e.get("name") == "collision":
                has_collision = True
        spawn_node = tree.find("objectgroup[@name='Controls']/object[@type='spawn']")
        if spawn_node is not None:
            header += "spawn {0} {1}\n".format(spawn_node.get("x"), spawn_node.get("y"))
        exit_node = tree.find("objectgroup[@name='Controls']/object[@type='exit']")
        if exit_node is not None:
            header += "exit {0} {1} {2} {3}\n".format(
                exit_node.get("x"), exit_node.get("y"), exit_node.get("width"), exit_node.get("height")
            )
        for e in tree.findall("imagelayer"):
            header += "background {0}\n".format(e.get("name"))
        for a in tree.findall("objectgroup[@name='Animations']/*"):
            header += "animations {0} {1} {2} {3}\n".format(a.get("name"), a.get("type"), a.get("x"), a.get("y"))
        # enable collision for all tiles by default
        if not has_collision and max_tile > 0:
            cl = "1"
            if max_tile > 1:
                cl = "1..." + str(min(9, max_tile))
            # if max_tile is less than 10, nothing will happen
            for i in range(10, max_tile + 1):
                cl += "," + ascii_letters[i - 10]
        result = header + "\n" + result
        file_name = basename(args.file).split(".")[0]
        if args.output:
            file_name = args.output
        with open(file_name, "w") as f:
            f.write(result)
        print('Conversion finished, wrote to "{0}"'.format(file_name))
        raise SystemExit
    except ParseError:
        # Rapid Pygame to Tiled
        # these configs are reflected in the map, not as properties
        excluded_configs = ["background", "exit", "spawn", "animations"]
        loader = ImageLoader(dirname(abspath(args.file)))
        pygame.display.init()
        try:
            tiles = loader.load_all(["tiles"], raw=True)
        except FileNotFoundError:
            print("CONVERSION FAILED:", 'Tile images not found in "tiles" folder where the map file is located')
            raise SystemExit
        if len(tiles.values()) == 0:
            print("CONVERSION FAILED:", 'Tile images not found in "tiles" folder where the map file is located')
            raise SystemExit
        # generate tile set
        order = sorted(tiles.keys())
        tile_width = tiles[order[0]].get_width()
        width = tile_width * min(args.per_line, len(order))
        height = ceil(len(order) / args.per_line) * tile_width
        tile_set_surf = pygame.Surface((width, height), pygame.SRCALPHA)
        for c in range(len(order)):
            x = c % args.per_line * tile_width
            y = c // args.per_line * tile_width
            tile_set_surf.blit(tiles[order[c]], (x, y))
        file_name = basename(args.file)
        if args.output:
            file_name = args.output
        pygame.image.save(tile_set_surf, file_name + ".png")

        # parse level
        with open(args.file, "r") as level_file:
            as_list = level_file.read().split("\n")
        separator = as_list.index("")
        raw_config = as_list[:separator]
        data = as_list[separator + 1 :]
        level = []
        for l in data:
            level.append([x if x.isdecimal() else str(ascii_letters.find(x) + 10) for x in l.strip()])
        # build Tiled XML
        level_width = str(len(level[0]))
        level_height = str(len(level))
        root = ET.Element("map")
        root.set("version", "1.0")
        root.set("orientation", "orthogonal")
        root.set("width", str(level_width))
        root.set("height", str(level_height))
        root.set("tilewidth", str(tile_width))
        root.set("tileheight", str(tile_width))
        # save the original config of the level into the Tiled map
        properties = ET.SubElement(root, "properties")
        background_config = []
        for l in raw_config:
            name, value = l.split(" ", 1)
            if name not in excluded_configs:
                ET.SubElement(properties, "property", name=name, value=value)
                continue
            if name == "background":
                background_config.append(l)
        for l in background_config:
            _, value = l.split(" ", 1)
            ET.SubElement(root, "imagelayer", {"name": value, "width": level_width, "height": level_height})
        tile_set = ET.SubElement(
            root,
            "tileset",
            {"firstgid": "1", "name": file_name, "tilewidth": str(tile_width), "tileheight": str(tile_width)},
        )
        ET.SubElement(tile_set, "image", {"source": file_name + ".png", "width": str(width), "height": str(height)})
        config = parse_config(raw_config)
        if "animations" in config:
            animation_layer = ET.SubElement(
                root, "objectgroup", name="Animations", width=level_width, height=level_height
            )
            for folder, interval, x, y in config["animations"]:
                ET.SubElement(
                    animation_layer, "object", {"name": str(folder), "type": str(interval), "x": str(x), "y": str(y)}
                )

        layer = ET.SubElement(
            root, "layer", {"name": file_name, "width": str(level_width), "height": str(level_height)}
        )
        csv = ""
        for l in level:
            csv += ",".join(l) + ",\n"
        csv = csv[:-2]
        ET.SubElement(layer, "data", encoding="csv").text = csv

        if "exit" in config or "spawn" in config:
            control_layer = ET.SubElement(root, "objectgroup", name="Controls", width=level_width, height=level_height)
            if "exit" in config:
                x, y, w, h = config["exit"]
                ET.SubElement(
                    control_layer,
                    "object",
                    {"type": "exit", "x": str(x), "y": str(y), "width": str(w), "height": str(h)},
                )
            if "spawn" in config:
                x, y = config["spawn"]
                ET.SubElement(control_layer, "object", {"type": "spawn", "x": str(x), "y": str(y)})
        ET.ElementTree(root).write(file_name + ".tmx", encoding="UTF-8", xml_declaration=True)
        print('Conversion finished, wrote to "{0}" and "{1}"'.format(file_name + ".png", file_name + ".tmx"))
def valor_da_palavra(palavra):
    
    return sum(ascii_letters.find(letra) + 1 for letra in palavra)
Beispiel #13
0
 def shift(self, symbol, key_position: int):
     return self.super_shift(symbol, -ALPHABET.find(self.key[key_position]))
Beispiel #14
0
def high(x):
    dic = {
        word: sum(ascii_letters.find(chr) + 1 for chr in word)
        for word in x.split()
    }
    return max(dic, key=dic.get)
def valor_da_palavra(palavra):

    return sum(ascii_letters.find(letra) + 1 for letra in palavra)