Further enhance the Smart Agent algorithm. Make it generate live. ` import pygame import…
- User
Further enhance the Smart Agent algorithm. Make it generate live.
import pygame import random # Initialize Pygame pygame.init() # Maze dimensions WIDTH, HEIGHT = 800, 800 ROWS, COLS = 40, 40 CELL_SIZE = WIDTH // COLS # Colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) GREEN = (0, 255, 0) RED = (255, 0, 0) BLUE = (0, 0, 255) # Set up the display WIN = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Smart Agent Maze Generator") class Cell: def __init__(self, row, col): self.row = row self.col = col self.walls = {'N': True, 'S': True, 'E': True, 'W': True} self.visited = False def draw(self, win): x = self.col * CELL_SIZE y = self.row * CELL_SIZE if self.visited: pygame.draw.rect(win, WHITE, (x, y, CELL_SIZE, CELL_SIZE)) # Draw walls if self.walls['N']: pygame.draw.line(win, BLACK, (x, y), (x + CELL_SIZE, y), 2) if self.walls['S']: pygame.draw.line(win, BLACK, (x, y + CELL_SIZE), (x + CELL_SIZE, y + CELL_SIZE), 2) if self.walls['E']: pygame.draw.line(win, BLACK, (x + CELL_SIZE, y), (x + CELL_SIZE, y + CELL_SIZE), 2) if self.walls['W']: pygame.draw.line(win, BLACK, (x, y), (x, y + CELL_SIZE), 2) def get_neighbors(cell, grid): neighbors = [] directions = {'N': (-1, 0), 'S': (1, 0), 'E': (0, 1), 'W': (0, -1)} for direction, (dr, dc) in directions.items(): r, c = cell.row + dr, cell.col + dc if 0 <= r < ROWS and 0 <= c < COLS: neighbor = grid[r][c] if not neighbor.visited: neighbors.append((direction, neighbor)) return neighbors def remove_walls(current, next_cell, direction): opposites = {'N': 'S', 'S': 'N', 'E': 'W', 'W': 'E'} current.walls[direction] = False next_cell.walls[opposites[direction]] = False def smart_agent_maze(): grid = [[Cell(r, c) for c in range(COLS)] for r in range(ROWS)] stack = [] # Starting point current = grid[0][0] current.visited = True stack.append(current) while stack: # Find all unvisited neighbors neighbors = get_neighbors(current, grid) if neighbors: # Scoring directions based on number of unvisited neighbors of neighbors scored_neighbors = [] for direction, neighbor in neighbors: score = len(get_neighbors(neighbor, grid)) scored_neighbors.append((score, (direction, neighbor))) # Choose the direction with the highest score scored_neighbors.sort(reverse=True, key=lambda x: x[0]) max_score = scored_neighbors[0][0] top_choices = [choice for choice in scored_neighbors if choice[0] == max_score] chosen = random.choice(top_choices)[1] direction, chosen_cell = chosen remove_walls(current, chosen_cell, direction) chosen_cell.visited = True stack.append(chosen_cell) current = chosen_cell else: # Backtrack current = stack.pop() return grid def draw_maze(win, grid): for row in grid: for cell in row: cell.draw(win) def main(): run = True clock = pygame.time.Clock() grid = smart_agent_maze() while run: clock.tick(60) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False WIN.fill(BLACK) draw_maze(WIN, grid) # Highlight start and end pygame.draw.rect(WIN, GREEN, (0, 0, CELL_SIZE, CELL_SIZE)) pygame.draw.rect(WIN, RED, ((COLS -1)*CELL_SIZE, (ROWS -1)*CELL_SIZE, CELL_SIZE, CELL_SIZE)) pygame.display.update() pygame.quit() if __name__ == "__main__": main() - Assistant
To enhance your Smart Agent algorithm for live maze generation, we'll modify the existing code to visualize the maze creation process in real-time. This involves updating the maze incrementally and rendering each step on the screen as it's processed. Here's how you can achieve this:
-
Convert the Maze Generation to a Generator:
- Use Python's generator functionality to yield control back to the main loop after each significant step in the maze generation. This allows the maze to be built and displayed incrementally.
-
Update the Main Loop to Handle Incremental Generation:
- Modify the
mainloop to fetch the next step from the generator and update the display accordingly.
- Modify the
-
Enhance Visualization:
- Highlight the current cell being processed.
- Optionally, visualize the stack to show the path being explored.
Below is the enhanced version of your Smart Agent maze generator with live generation capabilities:
import pygame import random import sys # Initialize Pygame pygame.init() # Maze dimensions WIDTH, HEIGHT = 800, 800 ROWS, COLS = 40, 40 CELL_SIZE = WIDTH // COLS # Colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) GREEN = (0, 255, 0) LIGHT_GREEN = (144, 238, 144) RED = (255, 0, 0) BLUE = (0, 0, 255) YELLOW = (255, 255, 0) PURPLE = (160, 32, 240) # Set up the display WIN = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Smart Agent Maze Generator - Live Visualization") class Cell: def __init__(self, row, col): self.row = row self.col = col self.walls = {'N': True, 'S': True, 'E': True, 'W': True} self.visited = False def draw(self, win, color=WHITE): x = self.col * CELL_SIZE y = self.row * CELL_SIZE if self.visited: pygame.draw.rect(win, color, (x, y, CELL_SIZE, CELL_SIZE)) # Draw walls if self.walls['N']: pygame.draw.line(win, BLACK, (x, y), (x + CELL_SIZE, y), 2) if self.walls['S']: pygame.draw.line(win, BLACK, (x, y + CELL_SIZE), (x + CELL_SIZE, y + CELL_SIZE), 2) if self.walls['E']: pygame.draw.line(win, BLACK, (x + CELL_SIZE, y), (x + CELL_SIZE, y + CELL_SIZE), 2) if self.walls['W']: pygame.draw.line(win, BLACK, (x, y), (x, y + CELL_SIZE), 2) def get_neighbors(cell, grid): neighbors = [] directions = {'N': (-1, 0), 'S': (1, 0), 'E': (0, 1), 'W': (0, -1)} for direction, (dr, dc) in directions.items(): r, c = cell.row + dr, cell.col + dc if 0 <= r < ROWS and 0 <= c < COLS: neighbor = grid[r][c] if not neighbor.visited: neighbors.append((direction, neighbor)) return neighbors def remove_walls(current, next_cell, direction): opposites = {'N': 'S', 'S': 'N', 'E': 'W', 'W': 'E'} current.walls[direction] = False next_cell.walls[opposites[direction]] = False def smart_agent_maze_generator(): grid = [[Cell(r, c) for c in range(COLS)] for r in range(ROWS)] stack = [] # Starting point current = grid[0][0] current.visited = True stack.append(current) while stack: # Yield the current state for visualization yield grid, stack, current # Find all unvisited neighbors neighbors = get_neighbors(current, grid) if neighbors: # Scoring directions based on number of unvisited neighbors of neighbors scored_neighbors = [] for direction, neighbor in neighbors: score = len(get_neighbors(neighbor, grid)) scored_neighbors.append((score, (direction, neighbor))) # Choose the direction with the highest score scored_neighbors.sort(reverse=True, key=lambda x: x[0]) max_score = scored_neighbors[0][0] top_choices = [choice for choice in scored_neighbors if choice[0] == max_score] chosen = random.choice(top_choices)[1] direction, chosen_cell = chosen remove_walls(current, chosen_cell, direction) chosen_cell.visited = True stack.append(chosen_cell) current = chosen_cell else: # Backtrack current = stack.pop() if stack: current = stack[-1] # Final yield to display the complete maze yield grid, stack, current def draw_maze(win, grid, stack, current): win.fill(BLACK) for row in grid: for cell in row: cell.draw(win) # Highlight the stack (path) for cell in stack: if cell != current: x = cell.col * CELL_SIZE y = cell.row * CELL_SIZE pygame.draw.rect(win, LIGHT_GREEN, (x, y, CELL_SIZE, CELL_SIZE)) # Highlight the current cell x = current.col * CELL_SIZE y = current.row * CELL_SIZE pygame.draw.rect(win, YELLOW, (x, y, CELL_SIZE, CELL_SIZE)) # Highlight start and end pygame.draw.rect(win, GREEN, (0, 0, CELL_SIZE, CELL_SIZE)) pygame.draw.rect(win, RED, ((COLS -1)*CELL_SIZE, (ROWS -1)*CELL_SIZE, CELL_SIZE, CELL_SIZE)) # Optional: Draw walls again to cover any overlapping colors for row in grid: for cell in row: cell.draw(win) def main(): run = True clock = pygame.time.Clock() maze_generator = smart_agent_maze_generator() # Initial draw try: grid, stack, current = next(maze_generator) except StopIteration: grid = [] stack = [] current = None while run: clock.tick(60) # Adjust FPS as needed for visualization speed for event in pygame.event.get(): if event.type == pygame.QUIT: run = False pygame.quit() sys.exit() # Update the maze generation try: grid, stack, current = next(maze_generator) except StopIteration: # Maze generation complete pass draw_maze(WIN, grid, stack, current) pygame.display.update() pygame.quit() if __name__ == "__main__": main()Key Enhancements Explained
-
Generator Function (
smart_agent_maze_generator):- Converts the maze generation process into a generator that yields the current state (
grid,stack, andcurrentcell) after each step. This allows the main loop to fetch and render each step incrementally.
- Converts the maze generation process into a generator that yields the current state (
-
Main Loop Adjustments:
- The
mainfunction initializes the generator and retrieves the first state. - Within the game loop, it attempts to get the next state from the generator using
next(maze_generator). If the generator is exhausted (StopIteration), it means the maze generation is complete. - The loop also handles Pygame events to allow the window to close gracefully.
- The
-
Visualization Enhancements (
draw_maze):- Stack Visualization: Cells in the stack (the path being explored) are highlighted in
LIGHT_GREEN, giving a visual representation of the algorithm's current path. - Current Cell Highlighting: The current cell being processed is highlighted in
YELLOWto indicate the algorithm's focus. - Start and End Points: The start cell is colored
GREEN, and the end cell is coloredREDto distinguish them clearly. - Drawing Order: After highlighting, walls are drawn again to ensure they are visible over any colored cells.
- Stack Visualization: Cells in the stack (the path being explored) are highlighted in
-
Performance Considerations:
- The
clock.tick(60)controls the frames per second (FPS). Adjust this value to speed up or slow down the visualization as desired.
- The
-
Graceful Exit:
- The program handles
pygame.QUITevents, allowing users to close the window at any time without errors.
- The program handles
Additional Suggestions
-
Speed Control: You can add keyboard controls to allow users to speed up or slow down the maze generation by adjusting the
clock.tick()parameter dynamically. -
Pathfinding Visualization: After the maze is generated, you could implement a pathfinding algorithm (like A*) to find and visualize the shortest path from start to end.
-
User Interface Elements: Adding buttons or a sidebar with information (like steps taken, current position, etc.) can enhance the user experience.
This enhanced version provides a live, step-by-step visualization of the maze generation process, making it easier to understand how the Smart Agent algorithm explores and builds the maze.
-