import random from PIL import Image, ImageDraw from .base import Job class MazeJob(Job): def get_name(self): return "BLUDISTE" def print_body(self, p): # Width and Height in cells. # Total width in chars = 2 * w + 1. # w=15 -> 31 chars (Fits comfortably on 80mm printers, tight on 58mm) w = 14 h = 32 maze = self.generate_maze(w, h) p.text("Najdi cestu z S do E:\n\n") # Generate and print image img = self._generate_image(maze) p.set(align='center') p.image(img, impl="bitImageColumn") p.set(align='left') p.text("\n") def _generate_image(self, maze): # Cell size in pixels cell_size = 16 rows = len(maze) cols = len(maze[0]) w, h = cols * cell_size, rows * cell_size # Create new 1-bit image (White background) # '1' mode = 1-bit pixels, black and white, stored with one pixel per byte img = Image.new('1', (w, h), 1) draw = ImageDraw.Draw(img) for r in range(rows): for c in range(cols): # Draw walls as black rectangles if maze[r][c] == '#': x = c * cell_size y = r * cell_size # fill=0 means Black in '1' mode draw.rectangle([x, y, x + cell_size, y + cell_size], fill=0) return img def generate_maze(self, width, height): rows = 2 * height + 1 cols = 2 * width + 1 # Initialize grid with walls maze = [['#' for _ in range(cols)] for _ in range(rows)] # Starting cell (1, 1) stack = [(1, 1)] maze[1][1] = ' ' while stack: x, y = stack[-1] # Directions: Up, Down, Left, Right (step 2 to jump over walls) directions = [(0, -2), (0, 2), (-2, 0), (2, 0)] random.shuffle(directions) moved = False for dx, dy in directions: nx, ny = x + dx, y + dy # Check bounds (ensure we stay within the outer border) if 1 <= nx < rows - 1 and 1 <= ny < cols - 1: if maze[nx][ny] == '#': # If unvisited maze[nx][ny] = ' ' # Mark cell as path maze[x + dx // 2][y + dy // 2] = ' ' # Knock down wall stack.append((nx, ny)) moved = True break if not moved: stack.pop() # Create Entrance (S) and Exit (E) maze[1][0] = 'S' maze[rows - 2][cols - 1] = 'E' return maze