跳到正文

剪贴板

剪贴板 25utt86n

原文
剪贴板信息

剪贴板信息

收录
更新
Python
import pygame
import sys
import math

# Initialize pygame
pygame.init()

# Color definitions
BACKGROUND = (240, 240, 245)
GRID_COLOR = (200, 200, 210)
ROOM_COLOR = (255, 255, 255)
WALL_COLOR = (100, 100, 120)
OPEN_DOOR_COLOR = (100, 200, 100)  # Green for open doors
LOCKED_DOOR_COLOR = (220, 80, 80)   # Red for locked doors
START_COLOR = (180, 220, 255)       # Start point color
END_COLOR = (255, 220, 180)         # End point color
TEXT_COLOR = (20, 20, 30)
PATH_COUNT_BG = (255, 255, 200)     # Path count background

# Maze parameters
ROOM_SIZE = 80          # Size of each room
DOOR_THICKNESS = 12     # Door thickness (increased for better clicking)
WALL_THICKNESS = 2      # Wall thickness
MARGIN = 50             # Margin around maze

class Maze:
    def __init__(self, n=5, m=5):
        self.n = n
        self.m = m
        # Initialize all doors as open
        # right_doors[i][j] indicates door from (i,j) to (i,j+1)
        self.right_doors = [[True for _ in range(m-1)] for _ in range(n)]
        # down_doors[i][j] indicates door from (i,j) to (i+1,j)
        self.down_doors = [[True for _ in range(m)] for _ in range(n-1)]

        # Calculate path counts to each room
        self.path_counts = [[0 for _ in range(m)] for _ in range(n)]
        self.calculate_paths()

    def calculate_paths(self):
        """Calculate number of paths from start to each room"""
        # Initialize all path counts to 0
        self.path_counts = [[0 for _ in range(self.m)] for _ in range(self.n)]

        # Start point has 1 path
        self.path_counts[0][0] = 1

        # Dynamic programming to calculate path counts
        for i in range(self.n):
            for j in range(self.m):
                # If can come from left
                if j > 0 and self.right_doors[i][j-1]:  # Door from (i,j-1) to (i,j) is open
                    self.path_counts[i][j] += self.path_counts[i][j-1]
                # If can come from top
                if i > 0 and self.down_doors[i-1][j]:   # Door from (i-1,j) to (i,j) is open
                    self.path_counts[i][j] += self.path_counts[i-1][j]

    def toggle_right_door(self, i, j):
        """Toggle right door state"""
        if 0 <= i < self.n and 0 <= j < self.m-1:
            self.right_doors[i][j] = not self.right_doors[i][j]
            self.calculate_paths()
            return True
        return False

    def toggle_down_door(self, i, j):
        """Toggle down door state"""
        if 0 <= i < self.n-1 and 0 <= j < self.m:
            self.down_doors[i][j] = not self.down_doors[i][j]
            self.calculate_paths()
            return True
        return False

    def get_door_at_pos(self, x, y, room_size, margin):
        """Get door at given pixel coordinates"""
        # Calculate room indices
        room_i = (y - margin) // room_size
        room_j = (x - margin) // room_size

        # Check if in valid range
        # if room_i < 0 or room_i >= self.n or room_j < 0 or room_j >= self.m:
        #     return None, None, None

        # Calculate relative position within room
        rel_x = (x - margin) % room_size
        rel_y = (y - margin) % room_size

        # Check if clicked on right door (right edge area of room)
        # Increased click area for better usability
        if rel_x > room_size - DOOR_THICKNESS*3:
            return "right", room_i, room_j

        # Check if clicked on down door (bottom edge area of room)
        if rel_y > room_size - DOOR_THICKNESS*3:
            return "down", room_i, room_j

        return None, None, None

def format_number(num):
    """Format large numbers for display"""
    return str(num)

def get_maze_dimensions_from_console():
    """Get maze dimensions from console input"""
    print("=== Maze Path Count Visualization Tool ===")
    print("Instructions:")
    print("- Click on doors to lock/unlock them")
    print("- Green: door open | Red: door locked")
    print("- Numbers show paths from start to each room")
    print("- Press 'R' to reset all doors to open")
    print("- Press 'ESC' to exit")
    print()

    while True:
        try:
            rows = int(input("Enter number of rows (1-15, recommended 5-8): "))
            if 1 <= rows <= 15:
                break
            else:
                print("Please enter a number between 1 and 15.")
        except ValueError:
            print("Please enter a valid integer.")

    while True:
        try:
            cols = int(input("Enter number of columns (1-15, recommended 5-8): "))
            if 1 <= cols <= 15:
                break
            else:
                print("Please enter a number between 1 and 15.")
        except ValueError:
            print("Please enter a valid integer.")

    return rows, cols

def main():
    # Get maze dimensions from console
    rows, cols = get_maze_dimensions_from_console()

    # Create maze with user-defined dimensions
    maze = Maze(rows, cols)

    # Calculate window dimensions
    maze_width = maze.m * ROOM_SIZE + 2 * MARGIN
    maze_height = maze.n * ROOM_SIZE + 2 * MARGIN

    # Create window
    screen = pygame.display.set_mode((maze_width, maze_height))
    pygame.display.set_caption(f"Maze Path Count Visualization - {rows}x{cols} Maze")

    # Fonts
    font_small = pygame.font.SysFont(None, 24)
    font_medium = pygame.font.SysFont(None, 28)
    font_large = pygame.font.SysFont(None, 32)

    # Instructions to display on screen
    instructions = [
        "Click on doors to lock/unlock",
        "Green: door open | Red: door locked",
        "Press 'R' to reset all doors",
        "Press 'ESC' to exit"
    ]

    clock = pygame.time.Clock()
    running = True

    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

            # Handle keyboard events
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    running = False
                elif event.key == pygame.K_r:
                    # Reset all doors to open
                    maze.right_doors = [[True for _ in range(maze.m-1)] for _ in range(maze.n)]
                    maze.down_doors = [[True for _ in range(maze.m)] for _ in range(maze.n-1)]
                    maze.calculate_paths()

            # Handle mouse clicks in maze area
            if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                x, y = event.pos
                # Check if clicked in maze area
                if MARGIN <= x < maze_width - MARGIN and MARGIN <= y < maze_height - MARGIN:
                    door_type, i, j = maze.get_door_at_pos(x, y, ROOM_SIZE, MARGIN)
                    if door_type == "right":
                        maze.toggle_right_door(i, j)
                    elif door_type == "down":
                        maze.toggle_down_door(i, j)

        # Draw background
        screen.fill(BACKGROUND)

        # Draw maze
        for i in range(maze.n):
            for j in range(maze.m):
                # Room rectangle
                room_rect = pygame.Rect(
                    MARGIN + j * ROOM_SIZE,
                    MARGIN + i * ROOM_SIZE,
                    ROOM_SIZE,
                    ROOM_SIZE
                )

                # Draw room background
                if i == 0 and j == 0:
                    pygame.draw.rect(screen, START_COLOR, room_rect)
                elif i == maze.n-1 and j == maze.m-1:
                    pygame.draw.rect(screen, END_COLOR, room_rect)
                else:
                    pygame.draw.rect(screen, ROOM_COLOR, room_rect)

                # Draw room border
                pygame.draw.rect(screen, GRID_COLOR, room_rect, WALL_THICKNESS)

                # Draw path count
                count = maze.path_counts[i][j]
                count_text = format_number(count)
                text_surface = font_medium.render(count_text, True, TEXT_COLOR)
                text_rect = text_surface.get_rect(center=room_rect.center)

                # Draw path count background
                count_bg_rect = text_rect.inflate(10, 6)
                pygame.draw.rect(screen, PATH_COUNT_BG, count_bg_rect, border_radius=4)
                pygame.draw.rect(screen, (180, 180, 100), count_bg_rect, 1, border_radius=4)

                screen.blit(text_surface, text_rect)

        # Draw doors with increased thickness
        # Right doors
        for i in range(maze.n):
            for j in range(maze.m-1):
                if maze.right_doors[i][j]:
                    color = OPEN_DOOR_COLOR
                else:
                    color = LOCKED_DOOR_COLOR

                # Draw door with increased thickness
                door_rect = pygame.Rect(
                    MARGIN + (j+1) * ROOM_SIZE - DOOR_THICKNESS,
                    MARGIN + i * ROOM_SIZE + ROOM_SIZE//4,
                    DOOR_THICKNESS * 2,
                    ROOM_SIZE//2
                )
                pygame.draw.rect(screen, color, door_rect)

                # If door is locked, draw a lock icon
                if not maze.right_doors[i][j]:
                    lock_rect = pygame.Rect(
                        door_rect.centerx - 6,
                        door_rect.centery - 8,
                        12, 14
                    )
                    pygame.draw.rect(screen, (100, 30, 30), lock_rect, border_radius=3)

        # Down doors
        for i in range(maze.n-1):
            for j in range(maze.m):
                if maze.down_doors[i][j]:
                    color = OPEN_DOOR_COLOR
                else:
                    color = LOCKED_DOOR_COLOR

                # Draw door with increased thickness
                door_rect = pygame.Rect(
                    MARGIN + j * ROOM_SIZE + ROOM_SIZE//4,
                    MARGIN + (i+1) * ROOM_SIZE - DOOR_THICKNESS,
                    ROOM_SIZE//2,
                    DOOR_THICKNESS * 2
                )
                pygame.draw.rect(screen, color, door_rect)

                # If door is locked, draw a lock icon
                if not maze.down_doors[i][j]:
                    lock_rect = pygame.Rect(
                        door_rect.centerx - 8,
                        door_rect.centery - 6,
                        14, 12
                    )
                    pygame.draw.rect(screen, (100, 30, 30), lock_rect, border_radius=3)

        # Draw start and end labels
        start_text = font_medium.render("Start", True, (0, 0, 100))
        screen.blit(start_text, (MARGIN + 5, MARGIN + 5))

        end_text = font_medium.render("End", True, (100, 50, 0))
        screen.blit(end_text, (MARGIN + (maze.m-1)*ROOM_SIZE + 5, MARGIN + (maze.n-1)*ROOM_SIZE + 5))

        # Draw current maze difficulty at top
        # total_paths = maze.path_counts[maze.n-1][maze.m-1]
        # difficulty_text = f"Maze Difficulty (Paths to End): {format_number(total_paths)}"
        # text_surface = font_large.render(difficulty_text, True, (40, 40, 120))
        # screen.blit(text_surface, (maze_width // 2 - text_surface.get_width() // 2, 10))

        # Draw maze size info
        # size_text = f"Maze Size: {maze.n} rows × {maze.m} columns"
        # text_surface = font_medium.render(size_text, True, (80, 80, 100))
        # screen.blit(text_surface, (maze_width - text_surface.get_width() - 10, 10))

        # Draw instructions at bottom
        # for idx, text in enumerate(instructions):
        #     text_surface = font_small.render(text, True, (80, 80, 100))
        #     screen.blit(text_surface, (10, maze_height - 20 - (len(instructions) - idx) * 25))

        # Update display
        pygame.display.flip()
        clock.tick(100)

    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()