Search in sources :

Example 21 with ColorConverter

use of common.tetfu.common.ColorConverter in project solution-finder by knewjade.

the class SetupEntryPoint method run.

@Override
public void run() throws FinderException {
    output("# Setup Field");
    // Setup init field
    Field initField = settings.getInitField();
    Verify.field(initField);
    // Setup need filled field
    Field needFilledField = settings.getNeedFilledField();
    Verify.needFilledField(needFilledField);
    // Setup not filled field
    Field notFilledField = settings.getNotFilledField();
    // Setup max height
    int maxHeight = settings.getMaxHeight();
    Verify.maxClearLineUnder10(maxHeight);
    // Setup reserved blocks
    BlockField reservedBlocks = settings.getReservedBlock();
    if (settings.isReserved()) {
        Verify.reservedBlocks(reservedBlocks);
        for (int y = maxHeight - 1; 0 <= y; y--) {
            StringBuilder builder = new StringBuilder();
            for (int x = 0; x < 10; x++) {
                if (reservedBlocks.getBlock(x, y) != null)
                    builder.append(reservedBlocks.getBlock(x, y).getName());
                else if (!initField.isEmpty(x, y))
                    builder.append('X');
                else if (!needFilledField.isEmpty(x, y))
                    builder.append('*');
                else if (!notFilledField.isEmpty(x, y))
                    builder.append('_');
                else
                    builder.append('.');
            }
            output(builder.toString());
        }
    } else {
        for (int y = maxHeight - 1; 0 <= y; y--) {
            StringBuilder builder = new StringBuilder();
            for (int x = 0; x < 10; x++) {
                if (!initField.isEmpty(x, y))
                    builder.append('X');
                else if (!needFilledField.isEmpty(x, y))
                    builder.append('*');
                else if (!notFilledField.isEmpty(x, y))
                    builder.append('_');
                else
                    builder.append('.');
            }
            output(builder.toString());
        }
    }
    // Setup min depth
    // 最低でも必要なミノ数
    int minDepth = Verify.minDepth(needFilledField);
    output();
    // ========================================
    // Output user-defined
    DropType dropType = settings.getDropType();
    output("# Initialize / User-defined");
    output("Max height: " + maxHeight);
    output("Drop: " + dropType.name().toLowerCase());
    output("Searching patterns:");
    // Setup patterns
    List<String> patterns = settings.getPatterns();
    PatternGenerator generator = Verify.patterns(patterns, minDepth);
    // Output patterns
    for (String pattern : patterns) output("  " + pattern);
    // Setup output file
    MyFile base = new MyFile(settings.getOutputBaseFilePath());
    base.mkdirs();
    base.verify();
    output();
    // ========================================
    // Setup core
    output("# Initialize / System");
    int core = Runtime.getRuntime().availableProcessors();
    // Output system-defined
    output("Version = " + FinderConstant.VERSION);
    output("Available processors = " + core);
    output("Need Pieces = " + minDepth);
    output();
    // ========================================
    output("# Search");
    output("  -> Stopwatch start");
    Stopwatch stopwatch = Stopwatch.createStartedStopwatch();
    // Initialize
    MinoFactory minoFactory = new MinoFactory();
    MinoShifter minoShifter = new MinoShifter();
    ColorConverter colorConverter = new ColorConverter();
    SizedBit sizedBit = decideSizedBitSolutionWidth(maxHeight);
    TaskResultHelper taskResultHelper = new BasicMinoPackingHelper();
    SolutionFilter solutionFilter = new ForPathSolutionFilter(generator, maxHeight);
    ThreadLocal<BuildUpStream> buildUpStreamThreadLocal = createBuildUpStreamThreadLocal(dropType, maxHeight);
    OneFumenParser fumenParser = new OneFumenParser(minoFactory, colorConverter);
    // ミノリストの作成
    long deleteKeyMask = getDeleteKeyMask(notFilledField, maxHeight);
    SeparableMinos separableMinos = SeparableMinos.createSeparableMinos(minoFactory, minoShifter, sizedBit, deleteKeyMask);
    // 絶対に置かないブロック
    List<InOutPairField> inOutPairFields = InOutPairField.createInOutPairFields(sizedBit, notFilledField);
    // 絶対に置く必要があるブロック
    ArrayList<BasicSolutions> basicSolutions = new ArrayList<>();
    List<ColumnField> needFillFields = InOutPairField.createInnerFields(sizedBit, needFilledField);
    {
        Field freeze = needFilledField.freeze(sizedBit.getHeight());
        for (ColumnField innerField : needFillFields) {
            // 最小限の部分だけを抽出する
            Field freeze1 = freeze.freeze(sizedBit.getHeight());
            for (int y = 0; y < sizedBit.getHeight(); y++) {
                int width = sizedBit.getWidth();
                for (int x = 0; x < width; x++) freeze1.removeBlock(x, y);
                for (int x = width + 3; x < 10; x++) freeze1.removeBlock(x, y);
            }
            OnDemandBasicSolutions solutions = new OnDemandBasicSolutions(separableMinos, sizedBit, innerField.getBoard(0), freeze1);
            basicSolutions.add(solutions);
            freeze.slideLeft(sizedBit.getWidth());
        }
    }
    // 探索
    SetupPackSearcher searcher = new SetupPackSearcher(inOutPairFields, basicSolutions, sizedBit, solutionFilter, taskResultHelper, needFillFields);
    List<Result> results = getResults(initField, sizedBit, buildUpStreamThreadLocal, searcher);
    output("     Found solution = " + results.size());
    stopwatch.stop();
    output("  -> Stopwatch stop : " + stopwatch.toMessage(TimeUnit.MILLISECONDS));
    output();
    // ========================================
    output("# Output file");
    HTMLBuilder<FieldHTMLColumn> htmlBuilder = new HTMLBuilder<>("Setup result");
    results.parallelStream().forEach(result -> {
        List<MinoOperationWithKey> operationWithKeys = result.getMemento().getSeparableMinoStream(sizedBit.getWidth()).map(SeparableMino::toMinoOperationWithKey).collect(Collectors.toList());
        Field allField = initField.freeze(maxHeight);
        Operations operations = OperationTransform.parseToOperations(allField, operationWithKeys, sizedBit.getHeight());
        List<? extends Operation> operationList = operations.getOperations();
        for (Operation operation : operationList) {
            Mino mino = minoFactory.create(operation.getPiece(), operation.getRotate());
            int x = operation.getX();
            int y = operation.getY();
            allField.put(mino, x, y);
        }
        // 譜面の作成
        String encode = fumenParser.parse(operationWithKeys, initField, maxHeight);
        String name = operationWithKeys.stream().map(OperationWithKey::getPiece).map(Piece::getName).collect(Collectors.joining());
        String link = String.format("<a href='http://fumen.zui.jp/?v115@%s' target='_blank'>%s</a>", encode, name);
        String line = String.format("<div>%s</div>", link);
        htmlBuilder.addColumn(new FieldHTMLColumn(allField, maxHeight), line);
    });
    ArrayList<FieldHTMLColumn> columns = new ArrayList<>(htmlBuilder.getRegisteredColumns());
    columns.sort(Comparator.comparing(FieldHTMLColumn::getTitle).reversed());
    try (BufferedWriter bufferedWriter = base.newBufferedWriter()) {
        for (String line : htmlBuilder.toList(columns, true)) {
            bufferedWriter.write(line);
            bufferedWriter.newLine();
        }
        bufferedWriter.flush();
    } catch (IOException e) {
        throw new FinderExecuteException(e);
    }
    output();
    // ========================================
    output("# Finalize");
    output("done");
}
Also used : OnDemandBasicSolutions(searcher.pack.solutions.OnDemandBasicSolutions) MyFile(entry.path.output.MyFile) Stopwatch(lib.Stopwatch) ForPathSolutionFilter(entry.path.ForPathSolutionFilter) TaskResultHelper(searcher.pack.task.TaskResultHelper) Result(searcher.pack.task.Result) BufferedWriter(java.io.BufferedWriter) ColumnField(core.column_field.ColumnField) InOutPairField(searcher.pack.InOutPairField) Field(core.field.Field) SeparableMinos(searcher.pack.SeparableMinos) InOutPairField(searcher.pack.InOutPairField) ColorConverter(common.tetfu.common.ColorConverter) SeparableMino(searcher.pack.separable_mino.SeparableMino) Mino(core.mino.Mino) MinoFactory(core.mino.MinoFactory) BuildUpStream(common.buildup.BuildUpStream) PatternGenerator(common.pattern.PatternGenerator) OneFumenParser(entry.path.output.OneFumenParser) HTMLBuilder(output.HTMLBuilder) ColumnField(core.column_field.ColumnField) BasicMinoPackingHelper(searcher.pack.task.BasicMinoPackingHelper) IOException(java.io.IOException) EntryPoint(entry.EntryPoint) BasicSolutions(searcher.pack.calculator.BasicSolutions) OnDemandBasicSolutions(searcher.pack.solutions.OnDemandBasicSolutions) SetupPackSearcher(searcher.pack.task.SetupPackSearcher) SizedBit(searcher.pack.SizedBit) ForPathSolutionFilter(entry.path.ForPathSolutionFilter) SolutionFilter(searcher.pack.memento.SolutionFilter) MinoShifter(core.mino.MinoShifter) DropType(entry.DropType) FinderExecuteException(exceptions.FinderExecuteException)

Example 22 with ColorConverter

use of common.tetfu.common.ColorConverter in project solution-finder by knewjade.

the class SetupSettingParser method loadTetfu.

private CommandLineWrapper loadTetfu(String data, CommandLineParser parser, Options options, CommandLineWrapper wrapper, SetupSettings settings) throws FinderParseException {
    // テト譜面のエンコード
    List<TetfuPage> decoded = encodeTetfu(data);
    // 指定されたページを抽出
    int page = wrapper.getIntegerOption("page").orElse(1);
    TetfuPage tetfuPage = extractTetfuPage(decoded, page);
    // コメントの抽出
    String comment = tetfuPage.getComment();
    List<String> splitComment = Arrays.stream(comment.split(" ")).map(String::trim).filter(s -> !s.isEmpty()).collect(Collectors.toList());
    // コマンド引数を配列に変換
    String[] commentArgs = new String[splitComment.size()];
    splitComment.toArray(commentArgs);
    // オプションとして読み込む
    try {
        CommandLine commandLineTetfu = parseToCommandLine(options, parser, commentArgs);
        CommandLineWrapper newWrapper = new NormalCommandLineWrapper(commandLineTetfu);
        wrapper = new PriorityCommandLineWrapper(Arrays.asList(wrapper, newWrapper));
    } catch (FinderParseException ignore) {
    }
    // 固定ピースの指定があるか
    // Optional<Boolean> reservedOption = wrapper.getBoolOption("reserved");
    // reservedOption.ifPresent(settings::setReserved);
    // マージン色の指定があるか
    Optional<String> fillColorOption = wrapper.getStringOption("fill");
    if (fillColorOption.isPresent()) {
        settings.setFillColorType(fillColorOption.get());
    }
    // マージン色の指定があるか
    Optional<String> marginColorOption = wrapper.getStringOption("margin");
    if (marginColorOption.isPresent()) {
        settings.setMarginColorType(marginColorOption.get());
    }
    // フィールドを設定
    ColoredField coloredField = tetfuPage.getField();
    if (tetfuPage.isPutMino()) {
        ColorType colorType = tetfuPage.getColorType();
        Rotate rotate = tetfuPage.getRotate();
        int x = tetfuPage.getX();
        int y = tetfuPage.getY();
        ColorConverter colorConverter = new ColorConverter();
        Mino mino = new Mino(colorConverter.parseToBlock(colorType), rotate);
        coloredField.putMino(mino, x, y);
    }
    // 最大削除ラインの設定
    Optional<Integer> maxHeightOption = wrapper.getIntegerOption("line");
    int maxHeight = maxHeightOption.orElse(coloredField.getUsingHeight());
    if (settings.isReserved()) {
        Field initField = FieldFactory.createField(maxHeight);
        Field needFilledField = FieldFactory.createField(maxHeight);
        Field notFilledField = FieldFactory.createField(maxHeight);
        ColorType marginColorType = settings.getMarginColorType();
        ColorType fillColorType = settings.getFillColorType();
        for (int y = 0; y < maxHeight; y++) {
            for (int x = 0; x < 10; x++) {
                ColorType colorType = coloredField.getColorType(x, y);
                if (colorType.equals(marginColorType)) {
                    coloredField.setColorType(ColorType.Empty, x, y);
                } else if (colorType.equals(fillColorType)) {
                    coloredField.setColorType(ColorType.Empty, x, y);
                    needFilledField.setBlock(x, y);
                } else {
                    switch(colorType) {
                        case Gray:
                            initField.setBlock(x, y);
                            notFilledField.setBlock(x, y);
                            coloredField.setColorType(ColorType.Empty, x, y);
                            break;
                        case Empty:
                            notFilledField.setBlock(x, y);
                            break;
                        default:
                            break;
                    }
                }
            }
        }
        settings.setFieldWithReserved(initField, needFilledField, notFilledField, coloredField, maxHeight);
    } else {
        Field initField = FieldFactory.createField(maxHeight);
        Field needFilledField = FieldFactory.createField(maxHeight);
        Field notFilledField = FieldFactory.createField(maxHeight);
        ColorType marginColorType = settings.getMarginColorType();
        ColorType fillColorType = settings.getFillColorType();
        for (int y = 0; y < maxHeight; y++) {
            for (int x = 0; x < 10; x++) {
                ColorType colorType = coloredField.getColorType(x, y);
                if (colorType.equals(marginColorType)) {
                // skip
                } else if (colorType.equals(fillColorType)) {
                    needFilledField.setBlock(x, y);
                } else {
                    switch(colorType) {
                        case Empty:
                            notFilledField.setBlock(x, y);
                            break;
                        case Gray:
                        default:
                            initField.setBlock(x, y);
                            notFilledField.setBlock(x, y);
                            break;
                    }
                }
            }
        }
        settings.setField(initField, needFilledField, notFilledField, maxHeight);
    }
    return wrapper;
}
Also used : TetfuPage(common.tetfu.TetfuPage) Arrays(java.util.Arrays) ColorType(common.tetfu.common.ColorType) org.apache.commons.cli(org.apache.commons.cli) Tetfu(common.tetfu.Tetfu) FinderParseException(exceptions.FinderParseException) ColoredFieldFactory(common.tetfu.field.ColoredFieldFactory) MinoFactory(core.mino.MinoFactory) Charset(java.nio.charset.Charset) FieldFactory(core.field.FieldFactory) LinkedList(java.util.LinkedList) Path(java.nio.file.Path) NormalCommandLineWrapper(entry.NormalCommandLineWrapper) Files(java.nio.file.Files) IOException(java.io.IOException) ColorConverter(common.tetfu.common.ColorConverter) Rotate(core.srs.Rotate) Collectors(java.util.stream.Collectors) List(java.util.List) Field(core.field.Field) Paths(java.nio.file.Paths) PriorityCommandLineWrapper(entry.PriorityCommandLineWrapper) Optional(java.util.Optional) CommandLineWrapper(entry.CommandLineWrapper) ColoredField(common.tetfu.field.ColoredField) Mino(core.mino.Mino) TetfuPage(common.tetfu.TetfuPage) ColoredField(common.tetfu.field.ColoredField) Rotate(core.srs.Rotate) Field(core.field.Field) ColoredField(common.tetfu.field.ColoredField) NormalCommandLineWrapper(entry.NormalCommandLineWrapper) FinderParseException(exceptions.FinderParseException) NormalCommandLineWrapper(entry.NormalCommandLineWrapper) PriorityCommandLineWrapper(entry.PriorityCommandLineWrapper) CommandLineWrapper(entry.CommandLineWrapper) ColorType(common.tetfu.common.ColorType) ColorConverter(common.tetfu.common.ColorConverter) Mino(core.mino.Mino) PriorityCommandLineWrapper(entry.PriorityCommandLineWrapper)

Example 23 with ColorConverter

use of common.tetfu.common.ColorConverter in project solution-finder by knewjade.

the class SetupSettings method setFieldWithReserved.

void setFieldWithReserved(Field initField, Field needFilledField, Field notFilledField, ColoredField coloredField, int maxHeight) {
    BlockField blockField = new BlockField(maxHeight);
    for (int y = 0; y < maxHeight; y++) {
        for (int x = 0; x < 10; x++) {
            ColorConverter colorConverter = new ColorConverter();
            ColorType colorType = colorConverter.parseToColorType(coloredField.getBlockNumber(x, y));
            switch(colorType) {
                case Gray:
                case Empty:
                    break;
                default:
                    Piece piece = colorConverter.parseToBlock(colorType);
                    blockField.setBlock(piece, x, y);
                    break;
            }
        }
    }
    setMaxHeight(maxHeight);
    setInitField(initField);
    setNeedFilledField(needFilledField);
    setNotFilledField(notFilledField);
    setReservedBlock(blockField);
}
Also used : BlockField(common.datastore.BlockField) Piece(core.mino.Piece) ColorConverter(common.tetfu.common.ColorConverter) ColorType(common.tetfu.common.ColorType)

Example 24 with ColorConverter

use of common.tetfu.common.ColorConverter in project solution-finder by knewjade.

the class FigUtilEntryPoint method run.

@Override
public void run() throws FinderException {
    output("# Setup");
    output("Version = " + FinderConstant.VERSION);
    MinoFactory minoFactory = new MinoFactory();
    ColorConverter colorConverter = new ColorConverter();
    FrameType frameType = settings.getFrameType();
    File outputFile = new File(settings.getOutputFilePath());
    output();
    output("# Generate");
    output("  -> Stopwatch start");
    Stopwatch stopwatch = Stopwatch.createStartedStopwatch();
    List<TetfuPage> usingTetfuPages = useTetfuPages();
    FigFormat figFormat = settings.getFigFormat();
    FigWriter figWriter = createFigWriter(minoFactory, colorConverter, frameType, outputFile, figFormat, usingTetfuPages);
    generate(figWriter, usingTetfuPages);
    stopwatch.stop();
    output("  -> Stopwatch stop : " + stopwatch.toMessage(TimeUnit.MILLISECONDS));
}
Also used : TetfuPage(common.tetfu.TetfuPage) FigWriter(util.fig.output.FigWriter) FrameType(util.fig.FrameType) Stopwatch(lib.Stopwatch) ColorConverter(common.tetfu.common.ColorConverter) MinoFactory(core.mino.MinoFactory) File(java.io.File)

Example 25 with ColorConverter

use of common.tetfu.common.ColorConverter in project solution-finder by knewjade.

the class Main3 method viewTetfu.

private static void viewTetfu(List<TetfuElement> elements) {
    if (elements.isEmpty()) {
        System.out.printf("<p>該当なし</p>%n");
    } else {
        MinoFactory minoFactory = new MinoFactory();
        ColorConverter colorConverter = new ColorConverter();
        int sizePerOne = 40;
        int split = ((elements.size() - 1) / sizePerOne) + 1;
        for (int index = 0; index < split; index++) {
            int startIndex = index * sizePerOne;
            int toIndex = index == split - 1 ? elements.size() : startIndex + sizePerOne;
            List<TetfuElement> subList = elements.subList(startIndex, toIndex);
            Tetfu tetfu = new Tetfu(minoFactory, colorConverter);
            String encode = tetfu.encode(subList);
            if (split == 1)
                System.out.printf("<p><a href='http://fumen.zui.jp/?v115@%s' target='_blank'>全 %d パターン</a></p>%n", encode, elements.size());
            else
                System.out.printf("<p><a href='http://fumen.zui.jp/?v115@%s' target='_blank'>全 %d パターン (%d/%d)</a></p>%n", encode, elements.size(), index + 1, split);
        }
    }
}
Also used : ColorConverter(common.tetfu.common.ColorConverter) MinoFactory(core.mino.MinoFactory) Tetfu(common.tetfu.Tetfu) TetfuElement(common.tetfu.TetfuElement)

Aggregations

ColorConverter (common.tetfu.common.ColorConverter)38 MinoFactory (core.mino.MinoFactory)36 LongTest (module.LongTest)18 Test (org.junit.jupiter.api.Test)18 Tetfu (common.tetfu.Tetfu)13 ColoredField (common.tetfu.field.ColoredField)11 ColorType (common.tetfu.common.ColorType)10 FinderParseException (exceptions.FinderParseException)10 Field (core.field.Field)9 Piece (core.mino.Piece)8 Mino (core.mino.Mino)7 Rotate (core.srs.Rotate)7 List (java.util.List)7 Collectors (java.util.stream.Collectors)7 TetfuPage (common.tetfu.TetfuPage)6 ColoredFieldFactory (common.tetfu.field.ColoredFieldFactory)6 IOException (java.io.IOException)6 Arrays (java.util.Arrays)5 Optional (java.util.Optional)5 BlockField (common.datastore.BlockField)4