# puzzlegen.frontend

View Source

      1from puzzlegen.core import GridInitializer, PuzzleLogic, BFSSolver, PuzzleBatchGenerator
      2
      3class SinglePuzzle:
      4    """
      5    User-facing interface for generating and solving a single Match-3 puzzle instance.
      6    Wraps the core logic to provide a simplified API.
      7    """
      8    def __init__(self, nb_blocks, colors, nb_moves, grid_size, stack_probability=0.75, blocks_gap=1):
      9        """
     10        Initialize the SinglePuzzle frontend.
     11
     12        Args:
     13
     14            nb_blocks (int): Total number of blocks to place on the grid.
     15
     16            colors (list of str): List of colors to use for the blocks.
     17
     18            nb_moves (int): Upper bound on the number of moves in the optimal solution. The generator ensures the puzzle can be solved in at most this number of moves.
     19
     20            grid_size (tuple of int): Dimensions of the grid as (rows, columns).
     21
     22            stack_probability (float, optional): Probability of stacking blocks vertically. Default is 0.75.
     23
     24            blocks_gap (int, optional): Maximum allowed gap between blocks during generation (e.g., 1 means at most one empty cell). Default is 1.
     25        """
     26        self.grid = GridInitializer(grid_size, nb_blocks, colors, nb_moves, stack_probability, blocks_gap)
     27        self.solver = None
     28        self.solution = None
     29
     30    def generate(self):
     31        """Randomly generate a puzzle grid based on the parameters defined in the SinglePuzzle instance."""
     32        self.grid.initialize_grid()
     33
     34    def show(self):
     35        """Display the initial state of the puzzle grid."""
     36        self.grid.print_initial_grid()
     37
     38    def solve(self):
     39        """
     40        Attempt to solve the puzzle using BFS. The search is limited to solutions within a maximum number of moves (`nb_moves`).
     41
     42        Returns:
     43            solution (dict or None):
     44                A dictionary containing the move history and block states leading to the solution,
     45                or None if no solution exists within `nb_moves` (meaning the solution requires more moves).
     46        """
     47        self.solver = BFSSolver(self.grid, PuzzleLogic())
     48        is_solvable, solution = self.solver.perform_all_blocks_moves()
     49        self.solution = solution if is_solvable else None
     50        return self.solution
     51
     52    def show_solution(self):
     53        """Display the solution path if one was found."""
     54        if self.solution:
     55            BFSSolver.print_history(self.solution, self.grid.grid_size, show=True)
     56        else:
     57            print("No solution found.")
     58
     59class PuzzleBatch:
     60    """
     61    Frontend interface for generating and exporting multiple puzzles with varying parameters.
     62    Useful for statistical analysis or dataset creation.
     63    """
     64    def __init__(self, blocks_range, colors_range, colors_blocks, nb_moves, grid_size, nb_attempts = 5, stack_probability=0.75, blocks_gap=1):
     65        """
     66        Initialize the batch puzzle generator.
     67
     68        Args:
     69
     70            blocks_range (tuple of int): Range of block counts to iterate over as (min_blocks, max_blocks).
     71                For each block count in this range, puzzles will be generated.
     72
     73            colors_range (tuple of int): Range of color counts to iterate over as (min_colors, max_colors).
     74                For each color count in this range, puzzles will be generated.
     75
     76            colors_blocks (list of str): Pool of possible block colors to choose from.
     77
     78            nb_moves (int): Maximum number of moves allowed in the optimal solution.
     79                The generator attempts to create puzzles solvable within this limit.
     80
     81            grid_size (tuple of int): Dimensions of the puzzle grid as (rows, columns).
     82
     83            nb_attempts (int, optional): Number of attempts to generate a solvable puzzle for each
     84                combination of blocks and colors. If no valid puzzle is found after these attempts,
     85                no puzzle is generated for that combination. Default is 5.
     86
     87            stack_probability (float, optional): Probability to stack blocks vertically during generation.
     88                Default is 0.75.
     89            blocks_gap (int, optional): Maximum allowed gap between blocks during generation (e.g., 1 means at most one empty cell). Default is 1.
     90        """
     91        self.generator = PuzzleBatchGenerator(
     92            blocks_range, colors_range, colors_blocks, nb_moves, grid_size, nb_attempts, stack_probability, blocks_gap
     93        )
     94        self.generated = False
     95
     96    def generate(self):
     97        """Generate a batch of puzzles based on the configured parameter ranges."""
     98        self.batch = self.generator.generate_puzzles()
     99        self.generator.compute_stats()
    100        self.generated = True
    101
    102    def show_stats(self):
    103        """Display statistical charts for the generated batch (e.g., bar chart and pie chart)."""
    104        if self.generated:
    105            self.generator.print_charts(show=True)
    106        else:
    107            print("Batch not generated.")
    108
    109    def save_pdf(self, filename):
    110        """
    111        Export all puzzle grids in the batch as a PDF.
    112
    113        Args:
    114            filename (str): Output filename for the PDF.
    115        """
    116        if self.generated:
    117            self.generator.print_and_save_batch(filename=filename)
    118            print(f"PDF saved as {filename}")
    119        else:
    120            print("Batch not generated.")
    121
    122    def save_csv(self, filename):
    123        """
    124        Export puzzle metadata and configuration results as a CSV file.
    125
    126        Args:
    127            filename (str): Output filename for the CSV.
    128        """
    129        if self.generated:
    130            self.generator.save_results_as_csv(filename=filename)
    131            print(f"CSV saved as {filename}")
    132        else:
    133            print("Batch not generated.")

class SinglePuzzle: View Source

     4class SinglePuzzle:
     5    """
     6    User-facing interface for generating and solving a single Match-3 puzzle instance.
     7    Wraps the core logic to provide a simplified API.
     8    """
     9    def __init__(self, nb_blocks, colors, nb_moves, grid_size, stack_probability=0.75, blocks_gap=1):
    10        """
    11        Initialize the SinglePuzzle frontend.
    12
    13        Args:
    14
    15            nb_blocks (int): Total number of blocks to place on the grid.
    16
    17            colors (list of str): List of colors to use for the blocks.
    18
    19            nb_moves (int): Upper bound on the number of moves in the optimal solution. The generator ensures the puzzle can be solved in at most this number of moves.
    20
    21            grid_size (tuple of int): Dimensions of the grid as (rows, columns).
    22
    23            stack_probability (float, optional): Probability of stacking blocks vertically. Default is 0.75.
    24
    25            blocks_gap (int, optional): Maximum allowed gap between blocks during generation (e.g., 1 means at most one empty cell). Default is 1.
    26        """
    27        self.grid = GridInitializer(grid_size, nb_blocks, colors, nb_moves, stack_probability, blocks_gap)
    28        self.solver = None
    29        self.solution = None
    30
    31    def generate(self):
    32        """Randomly generate a puzzle grid based on the parameters defined in the SinglePuzzle instance."""
    33        self.grid.initialize_grid()
    34
    35    def show(self):
    36        """Display the initial state of the puzzle grid."""
    37        self.grid.print_initial_grid()
    38
    39    def solve(self):
    40        """
    41        Attempt to solve the puzzle using BFS. The search is limited to solutions within a maximum number of moves (`nb_moves`).
    42
    43        Returns:
    44            solution (dict or None):
    45                A dictionary containing the move history and block states leading to the solution,
    46                or None if no solution exists within `nb_moves` (meaning the solution requires more moves).
    47        """
    48        self.solver = BFSSolver(self.grid, PuzzleLogic())
    49        is_solvable, solution = self.solver.perform_all_blocks_moves()
    50        self.solution = solution if is_solvable else None
    51        return self.solution
    52
    53    def show_solution(self):
    54        """Display the solution path if one was found."""
    55        if self.solution:
    56            BFSSolver.print_history(self.solution, self.grid.grid_size, show=True)
    57        else:
    58            print("No solution found.")

User-facing interface for generating and solving a single Match-3 puzzle instance. Wraps the core logic to provide a simplified API.

SinglePuzzle( nb_blocks, colors, nb_moves, grid_size, stack_probability=0.75, blocks_gap=1) View Source

     9    def __init__(self, nb_blocks, colors, nb_moves, grid_size, stack_probability=0.75, blocks_gap=1):
    10        """
    11        Initialize the SinglePuzzle frontend.
    12
    13        Args:
    14
    15            nb_blocks (int): Total number of blocks to place on the grid.
    16
    17            colors (list of str): List of colors to use for the blocks.
    18
    19            nb_moves (int): Upper bound on the number of moves in the optimal solution. The generator ensures the puzzle can be solved in at most this number of moves.
    20
    21            grid_size (tuple of int): Dimensions of the grid as (rows, columns).
    22
    23            stack_probability (float, optional): Probability of stacking blocks vertically. Default is 0.75.
    24
    25            blocks_gap (int, optional): Maximum allowed gap between blocks during generation (e.g., 1 means at most one empty cell). Default is 1.
    26        """
    27        self.grid = GridInitializer(grid_size, nb_blocks, colors, nb_moves, stack_probability, blocks_gap)
    28        self.solver = None
    29        self.solution = None

Initialize the SinglePuzzle frontend.

Args:

    nb_blocks (int): Total number of blocks to place on the grid.

    colors (list of str): List of colors to use for the blocks.

    nb_moves (int): Upper bound on the number of moves in the optimal solution. The generator ensures the puzzle can be solved in at most this number of moves.

    grid_size (tuple of int): Dimensions of the grid as (rows, columns).

    stack_probability (float, optional): Probability of stacking blocks vertically. Default is 0.75.

    blocks_gap (int, optional): Maximum allowed gap between blocks during generation (e.g., 1 means at most one empty cell). Default is 1.

grid
solver
solution
def generate(self): View Source

    31    def generate(self):
    32        """Randomly generate a puzzle grid based on the parameters defined in the SinglePuzzle instance."""
    33        self.grid.initialize_grid()

Randomly generate a puzzle grid based on the parameters defined in the SinglePuzzle instance.

def show(self): View Source

    35    def show(self):
    36        """Display the initial state of the puzzle grid."""
    37        self.grid.print_initial_grid()

Display the initial state of the puzzle grid.

def solve(self): View Source

    39    def solve(self):
    40        """
    41        Attempt to solve the puzzle using BFS. The search is limited to solutions within a maximum number of moves (`nb_moves`).
    42
    43        Returns:
    44            solution (dict or None):
    45                A dictionary containing the move history and block states leading to the solution,
    46                or None if no solution exists within `nb_moves` (meaning the solution requires more moves).
    47        """
    48        self.solver = BFSSolver(self.grid, PuzzleLogic())
    49        is_solvable, solution = self.solver.perform_all_blocks_moves()
    50        self.solution = solution if is_solvable else None
    51        return self.solution

Attempt to solve the puzzle using BFS. The search is limited to solutions within a maximum number of moves (`nb_moves`).

Returns: solution (dict or None): A dictionary containing the move history and block states leading to the solution, or None if no solution exists within `nb_moves` (meaning the solution requires more moves).

def show_solution(self): View Source

    53    def show_solution(self):
    54        """Display the solution path if one was found."""
    55        if self.solution:
    56            BFSSolver.print_history(self.solution, self.grid.grid_size, show=True)
    57        else:
    58            print("No solution found.")

Display the solution path if one was found.

class PuzzleBatch: View Source

     60class PuzzleBatch:
     61    """
     62    Frontend interface for generating and exporting multiple puzzles with varying parameters.
     63    Useful for statistical analysis or dataset creation.
     64    """
     65    def __init__(self, blocks_range, colors_range, colors_blocks, nb_moves, grid_size, nb_attempts = 5, stack_probability=0.75, blocks_gap=1):
     66        """
     67        Initialize the batch puzzle generator.
     68
     69        Args:
     70
     71            blocks_range (tuple of int): Range of block counts to iterate over as (min_blocks, max_blocks).
     72                For each block count in this range, puzzles will be generated.
     73
     74            colors_range (tuple of int): Range of color counts to iterate over as (min_colors, max_colors).
     75                For each color count in this range, puzzles will be generated.
     76
     77            colors_blocks (list of str): Pool of possible block colors to choose from.
     78
     79            nb_moves (int): Maximum number of moves allowed in the optimal solution.
     80                The generator attempts to create puzzles solvable within this limit.
     81
     82            grid_size (tuple of int): Dimensions of the puzzle grid as (rows, columns).
     83
     84            nb_attempts (int, optional): Number of attempts to generate a solvable puzzle for each
     85                combination of blocks and colors. If no valid puzzle is found after these attempts,
     86                no puzzle is generated for that combination. Default is 5.
     87
     88            stack_probability (float, optional): Probability to stack blocks vertically during generation.
     89                Default is 0.75.
     90            blocks_gap (int, optional): Maximum allowed gap between blocks during generation (e.g., 1 means at most one empty cell). Default is 1.
     91        """
     92        self.generator = PuzzleBatchGenerator(
     93            blocks_range, colors_range, colors_blocks, nb_moves, grid_size, nb_attempts, stack_probability, blocks_gap
     94        )
     95        self.generated = False
     96
     97    def generate(self):
     98        """Generate a batch of puzzles based on the configured parameter ranges."""
     99        self.batch = self.generator.generate_puzzles()
    100        self.generator.compute_stats()
    101        self.generated = True
    102
    103    def show_stats(self):
    104        """Display statistical charts for the generated batch (e.g., bar chart and pie chart)."""
    105        if self.generated:
    106            self.generator.print_charts(show=True)
    107        else:
    108            print("Batch not generated.")
    109
    110    def save_pdf(self, filename):
    111        """
    112        Export all puzzle grids in the batch as a PDF.
    113
    114        Args:
    115            filename (str): Output filename for the PDF.
    116        """
    117        if self.generated:
    118            self.generator.print_and_save_batch(filename=filename)
    119            print(f"PDF saved as {filename}")
    120        else:
    121            print("Batch not generated.")
    122
    123    def save_csv(self, filename):
    124        """
    125        Export puzzle metadata and configuration results as a CSV file.
    126
    127        Args:
    128            filename (str): Output filename for the CSV.
    129        """
    130        if self.generated:
    131            self.generator.save_results_as_csv(filename=filename)
    132            print(f"CSV saved as {filename}")
    133        else:
    134            print("Batch not generated.")

Frontend interface for generating and exporting multiple puzzles with varying parameters. Useful for statistical analysis or dataset creation.

PuzzleBatch( blocks_range, colors_range, colors_blocks, nb_moves, grid_size, nb_attempts=5, stack_probability=0.75, blocks_gap=1) View Source

    65    def __init__(self, blocks_range, colors_range, colors_blocks, nb_moves, grid_size, nb_attempts = 5, stack_probability=0.75, blocks_gap=1):
    66        """
    67        Initialize the batch puzzle generator.
    68
    69        Args:
    70
    71            blocks_range (tuple of int): Range of block counts to iterate over as (min_blocks, max_blocks).
    72                For each block count in this range, puzzles will be generated.
    73
    74            colors_range (tuple of int): Range of color counts to iterate over as (min_colors, max_colors).
    75                For each color count in this range, puzzles will be generated.
    76
    77            colors_blocks (list of str): Pool of possible block colors to choose from.
    78
    79            nb_moves (int): Maximum number of moves allowed in the optimal solution.
    80                The generator attempts to create puzzles solvable within this limit.
    81
    82            grid_size (tuple of int): Dimensions of the puzzle grid as (rows, columns).
    83
    84            nb_attempts (int, optional): Number of attempts to generate a solvable puzzle for each
    85                combination of blocks and colors. If no valid puzzle is found after these attempts,
    86                no puzzle is generated for that combination. Default is 5.
    87
    88            stack_probability (float, optional): Probability to stack blocks vertically during generation.
    89                Default is 0.75.
    90            blocks_gap (int, optional): Maximum allowed gap between blocks during generation (e.g., 1 means at most one empty cell). Default is 1.
    91        """
    92        self.generator = PuzzleBatchGenerator(
    93            blocks_range, colors_range, colors_blocks, nb_moves, grid_size, nb_attempts, stack_probability, blocks_gap
    94        )
    95        self.generated = False

Initialize the batch puzzle generator.

Args:

    blocks_range (tuple of int): Range of block counts to iterate over as (min_blocks, max_blocks).
        For each block count in this range, puzzles will be generated.

    colors_range (tuple of int): Range of color counts to iterate over as (min_colors, max_colors).
        For each color count in this range, puzzles will be generated.

    colors_blocks (list of str): Pool of possible block colors to choose from.

    nb_moves (int): Maximum number of moves allowed in the optimal solution.
        The generator attempts to create puzzles solvable within this limit.

    grid_size (tuple of int): Dimensions of the puzzle grid as (rows, columns).

    nb_attempts (int, optional): Number of attempts to generate a solvable puzzle for each
        combination of blocks and colors. If no valid puzzle is found after these attempts,
        no puzzle is generated for that combination. Default is 5.

    stack_probability (float, optional): Probability to stack blocks vertically during generation.
        Default is 0.75.
    blocks_gap (int, optional): Maximum allowed gap between blocks during generation (e.g., 1 means at most one empty cell). Default is 1.

generator
generated
def generate(self): View Source

     97    def generate(self):
     98        """Generate a batch of puzzles based on the configured parameter ranges."""
     99        self.batch = self.generator.generate_puzzles()
    100        self.generator.compute_stats()
    101        self.generated = True

Generate a batch of puzzles based on the configured parameter ranges.

def show_stats(self): View Source

    103    def show_stats(self):
    104        """Display statistical charts for the generated batch (e.g., bar chart and pie chart)."""
    105        if self.generated:
    106            self.generator.print_charts(show=True)
    107        else:
    108            print("Batch not generated.")

Display statistical charts for the generated batch (e.g., bar chart and pie chart).

def save_pdf(self, filename): View Source

    110    def save_pdf(self, filename):
    111        """
    112        Export all puzzle grids in the batch as a PDF.
    113
    114        Args:
    115            filename (str): Output filename for the PDF.
    116        """
    117        if self.generated:
    118            self.generator.print_and_save_batch(filename=filename)
    119            print(f"PDF saved as {filename}")
    120        else:
    121            print("Batch not generated.")

Export all puzzle grids in the batch as a PDF.

Args: filename (str): Output filename for the PDF.

def save_csv(self, filename): View Source

    123    def save_csv(self, filename):
    124        """
    125        Export puzzle metadata and configuration results as a CSV file.
    126
    127        Args:
    128            filename (str): Output filename for the CSV.
    129        """
    130        if self.generated:
    131            self.generator.save_results_as_csv(filename=filename)
    132            print(f"CSV saved as {filename}")
    133        else:
    134            print("Batch not generated.")

Export puzzle metadata and configuration results as a CSV file.

Args: filename (str): Output filename for the CSV.