Ir para conteúdo

Criando um arquivo de formatação


Manolo8

Posts Recomendados

Eai pessoal, estou criando um arquivo de formatação para o meu plugin SimpleMachines para criar os livros customizados...

 

Estive fazendo um código pra percorrer o arquivo e fazer uns bagu-i ai, e obtive esse código:

 

 

package com.github.manolo8.simplemachines.utils;

import com.github.manolo8.simplemachines.utils.book.Node;
import com.github.manolo8.simplemachines.utils.replace.Replace;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class BookFactory {

    private Map<String, Replace> formatters;
    private List<Replace> pages;
    private int a = 0;

    public BookFactory() {

    }

    public void generateDefaults(String template) {
        String[] lines = template.split("\n");

        List<Node> nodes = new ArrayList<>();
        
        while (a < lines.length) {
            Node node = findNextNode(lines);
            nodes.add(node);
            System.out.println();
            System.out.println();
            System.out.println(node.getKey());
            System.out.println(node.getValue());
            System.out.println(Arrays.toString(node.getTemplate()));
            System.out.println();
            System.out.println();
        }

    }

    public Node findNextNode(String[] source) {
        Node node = new Node();

        int start = a;
        int begin = 0;
        int end = 0;
        boolean tag = true;

        StringBuilder builder = new StringBuilder();
        while (a < source.length) {
            String string = source[a];
            a++;
            if (string.equals("[end]")) {
                end = a-1;
                break;
            }
            int i = 0;

            if (tag)
                while (string.length() > i) {
                    char f = string.charAt(i);
                    i++;
                    if (f == '[') tag = false;
                    else {
                        if (f == ']') {
                            String[] vl = builder.toString().split("-");
                            node.setKey(vl[0]);
                            node.setValue(vl[1]);
                            begin = a;
                            builder.setLength(0);
                            break;
                        }
                        builder.append(f);
                    }
                }
        }
        String[] template = new String[end - begin];
        System.arraycopy(source, begin, template, 0, end - begin);
        node.setTemplate(template);
        return node;
    }

    public static void main(String[] args) {
        String template = "[formatter-cost]\n" +
                "&c-> {material}\n" +
                "[end]\n" +
                "\n" +
                "[formatter-production]\n" +
                "&c-> {name} - {speed}x\n" +
                "&bQueima por {ticks}\n" +
                "[end]\n" +
                "\n" +
                "[page-0]\n" +
                "&d&l--{name}--\n" +
                "&aCusto do livro:\n" +
                "{cost}\n" +
                "&aClique em um bloco de\n" +
                "ferro para iniciar a\n" +
                "construção da máquina!\n" +
                "[end]\n" +
                "\n" +
                "[page-1]\n" +
                "&a&l-----Produção:-----\n" +
                "{production}\n" +
                "&aVá para a próxima página\n" +
                "para ver os combustíveis!\n" +
                "[end]\n" +
                "\n" +
                "[page-2]\n" +
                "&a&l---Combustíveis:---\n" +
                "{fuel}\n" +
                "[end]\n" +
                "\n" +
                "[page-3]\n" +
                "Exemplo de página\n" +
                "[end]\n" +
                "\n" +
                "[page-4]\n" +
                "Exemplo de outra página\n" +
                "Suporta até 50 páginas\n" +
                "[end]";

        new BookFactory().generateDefaults(template);
    }
}

 

 

 

Output:

 

 

 

formatter
cost
[&c-> {material}]
 
formatter
production
[&c-> {name} - {speed}x, &bQueima por {ticks}]
 
page
0
[&d&l--{name}--, &aCusto do livro:, {cost}, &aClique em um bloco de, ferro para iniciar a, construção da máquina!]
 
page
1
[&a&l-----Produção:-----, {production}, &aVá para a próxima página, para ver os combustíveis!]
 
page
2
[&a&l---Combustíveis:---, {fuel}]
 
page
3
[Exemplo de página]
 
page
4
[Exemplo de outra página, Suporta até 50 páginas]

 

 

 

Arquivo fonte:

 

 

[formatter-cost]
&c-> {material}
[end]

[formatter-production]
&c-> {name} - {speed}x
&bQueima por {ticks}
[end]

[page-0]
&d&l--{name}--
&aCusto do livro:
{cost}
&aClique em um bloco de
ferro para iniciar a
construção da máquina!
[end]

[page-1]
&a&l-----Produção:-----
{production}
&aVá para a próxima página
para ver os combustíveis!
[end]

[page-2]
&a&l---Combustíveis:---
{fuel}
[end]

[page-3]
Exemplo de página
[end]

[page-4]
Exemplo de outra página
Suporta até 50 páginas
[end]

 

 

 

Claro que vou usar ainda um reader para ler de um arquivo no formato .txt e vou fazer mais umas modificações para o sistema funcionar como eu espero que funcione...

 

Se alguém for usar/ou quer o código final (Com um outro sistema de formatador que eu também fiz, para usar em conjunto) Deixa nos comentários ai '-'

Link para o comentário
Compartilhar em outros sites

 

H06ZXm4.png

 

 

Código final

 

Node.java

 

 

public class Node {

    private String key;
    private String value;
    private String[] template;

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String[] getTemplate() {
        return template;
    }

    public String getTemplateAsString() {
        StringBuilder builder = new StringBuilder();
        for (String string : template) builder.append(string).append("\n");
        return builder.toString().replaceAll("&", "§");
    }

    public void setTemplate(String[] template) {
        this.template = template;
    }
}
 

 

 

 

NodeFactory.java

 

 

public class NodeFactory {

    private int a;

    public List<Node> findNodes(String[] lines) {
        List<Node> nodes = new ArrayList<>();
        a = 0;
        while (a < lines.length) nodes.add(findNextNode(lines));
        return nodes;
    }

    public List<Node> findNodes(File file) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF8"));

        List<String> lines = new ArrayList<>();

        String ln;
        while ((ln = bufferedReader.readLine()) != null) lines.add(ln);

        return findNodes(lines.toArray(new String[0]));
    }

    private Node findNextNode(String[] source) {
        Node node = new Node();

        int begin = 0;
        int end = 0;
        boolean tag = true;

        StringBuilder builder = new StringBuilder();
        while (a < source.length) {
            String string = source[a];
            a++;
            if (string.length() > 0 && string.charAt(0) == '#') continue;
            if (string.equals("[end]")) {
                end = a - 1;
                break;
            }

            if (!tag) continue;

            int i = 0;
            while (string.length() > i) {
                char f = string.charAt(i);
                i++;
                if (f == '[') tag = false;
                else if (f == ']') {
                    String[] vl = builder.toString().split("-");
                    node.setKey(vl[0]);
                    node.setValue(vl[1]);
                    begin = a;
                    builder.setLength(0);
                    break;
                } else builder.append(f);
            }
        }
        String[] template = new String[end - begin];
        System.arraycopy(source, begin, template, 0, end - begin);
        node.setTemplate(template);
        return node;
    }
}
 

 

 

 

BookFactory.java

 

 

 

public class BookFactory {

    private Map<String, Replace> formatters;
    private Map<String, String> materials;
    private List<Replace> pages;
    private Replace loreReplace;
    private int a = 0;

    public BookFactory(File file) throws IOException {
        formatters = new HashMap<>();
        materials = new HashMap<>();
        pages = new ArrayList<>();

        List<Node> nodes = new NodeFactory().findNodes(file);

        for (Node node : nodes) {
            if (node.getKey().equals("formatter")) {
                Replace replace = new Replace(node.getTemplateAsString()).compile();
                formatters.put(node.getValue(), replace);
                continue;
            }

            if (node.getKey().equals("page")) {
                Replace replace = new Replace(node.getTemplateAsString()).compile();
                pages.add(replace);
                continue;
            }

            if (node.getKey().equals("lore")) {
                loreReplace = new Replace(node.getTemplateAsString()).compile();
                continue;
            }

            if (node.getKey().equals("material")) {
                String[] template = node.getTemplate();
                materials.put(node.getValue(), template.length > 0 ? template[0] : "WRONG");
            }
        }
    }

    public ItemStack generateBook(BluePrint bluePrint) {
        ItemStack itemStack = new ItemStack(Material.WRITTEN_BOOK, 1);
        BookMeta meta = (BookMeta) itemStack.getItemMeta();
        meta.setDisplayName("-> " + bluePrint.getName());
        meta.setAuthor("SimpleMachines");

        StringBuilder builder = new StringBuilder();

        Replace costReplace = formatters.get("cost");
        for (ItemStack stack : bluePrint.getBuildCost()) {
            builder.append(costReplace.setValue("material", getName(stack)));
        }

        String cost = builder.toString();
        builder.setLength(0);

        Replace productionFormatter = formatters.get("production");
        for (Product product : bluePrint.getProducer().getProducts()) {
            builder.append(productionFormatter
                    .setValue("material", getName(product.getMaterial()))
                    .setValue("ticks", product.getCost()));
        }

        String production = builder.toString();

        builder.setLength(0);

        Replace fuelReplace = formatters.get("fuel");
        for (Fuel fuel : bluePrint.getFuels().getFuels()) {
            builder.append(fuelReplace
                    .setValue("material", getName(fuel.getMaterial()))
                    .setValue("speed", fuel.getSpeed())
                    .setValue("ticks", fuel.getBurnTime()));
        }

        String fuel = builder.toString();

        builder.setLength(0);

        String[] lore = loreReplace.setValue("cost", cost).build().split("\n");

        meta.setLore(Arrays.asList(lore));

        List<String> pgs = new ArrayList<>();

        for (Replace page : pages) {
            pgs.add(page.setValue("production", production)
                    .setValue("cost", cost)
                    .setValue("fuel", fuel)
                    .build());
        }

        meta.setPages(pgs);
        itemStack.setItemMeta(meta);

        return itemStack;
    }

    private String getName(ItemStack itemStack) {
        return getName(itemStack.getType());
    }

    private String getName(Material material) {
        String type = material.name().toLowerCase();
        return materials.getOrDefault(type, type);
    }
}
 

 

 

 

Para quem querer: Replace.java e Content.java:

 

 

 

public class Replace {

    private String template;
    private List<Content> contents;

    public Replace(String template) {
        this.template = template;
        this.contents = new ArrayList<>();
    }

    public boolean hasKey(String key) {
        for (Content content : contents) if (content.getKey().equals(key)) return true;
        return false;
    }

    public Replace setTemplate(String template) {
        this.template = template;
        compile();
        return this;
    }

    public Replace setValue(String key, Object value) {
        for (Content content : contents) {
            if (content.getKey().equals(key))
                content.setValue(value);
        }
        return this;
    }

    public Replace compile() {
        contents.clear();

        StringBuilder mainBuilder = new StringBuilder();

        for (int i = 0; i < template.length(); i++) {
            char c = template.charAt(i);
            if (c == '{') {
                StringBuilder builder = new StringBuilder();
                while (i < template.length()) {
                    i++;
                    c = template.charAt(i);
                    if (c == '}') break;
                    builder.append(c);
                }
                contents.add(new Content(builder.toString(), mainBuilder.toString(), ""));
                mainBuilder = new StringBuilder();
                continue;
            }
            mainBuilder.append(c);
        }
        contents.add(new Content("end", mainBuilder.toString(), ""));
        //Libera a memória
        template = null;
        return this;
    }

    public String build() {
        StringBuilder builder = new StringBuilder();

        for (Content content : contents) builder.append(content.getDef()).append(content.getValue());

        return builder.toString();
    }

    @Override
    public String toString() {
        return build();
    }
}
 

 

 

 

 

 

public class Content {

    private String key;
    private String def;
    private Object value;

    public Content(String key, String def, Object value) {
        this.key = key;
        this.def = def;
        this.value = value;
    }

    public String getKey() {
        return key;
    }

    public Content setKey(String key) {
        this.key = key;
        return this;
    }

    public String getDef() {
        return def;
    }

    public Content setDef(String def) {
        this.def = def;
        return this;
    }

    public Object getValue() {
        if (value == null) return "";
        return value;
    }

    public Content setValue(Object value) {
        this.value = value;
        return this;
    }
}
 

 

 

 

De nada

Link para o comentário
Compartilhar em outros sites

Participe da Conversa

Você pode postar agora e se cadastrar mais tarde. Se você tiver uma conta, a class='ipsType_brandedLink' href='https://gamersboard.com.br/login/' data-ipsDialog data-ipsDialog-size='medium' data-ipsDialog-title='Sign In Now'>acesse agora para postar com sua conta.
Observação: sua postagem exigirá aprovação do moderador antes de ficar visível.

Visitante
Responder

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.

Processando...
×
×
  • Criar Novo...