Entiendo que deseas modificar tu algoritmo de resolución de laberinto para que solo recorra y muestre el camino correcto desde el inicio hasta el final, evitando la exploración y visualización de caminos incorrectos. Para lograr esto, podemos separar el proceso de búsqueda de la animación del camino.
A continuación, te proporcionaré una versión modificada de tu código que:
- Utiliza el Algoritmo de Búsqueda en Anchura (BFS) para encontrar el camino más corto desde el inicio hasta el final del laberinto.
- Almacena el camino encontrado y luego lo muestra en pantalla sin animar la exploración de caminos incorrectos.
- Elimina la visualización de celdas visitadas que no forman parte del camino de la solución, proporcionando una visualización más limpia y enfocada únicamente en el camino correcto.
Código Modificado
import pygame
import random
from collections import deque
# Configuración del laberinto
WIDTH = 40 # Número de columnas (reducido para mejor rendimiento)
HEIGHT = 40 # Número de filas (reducido para mejor rendimiento)
CELL_SIZE = 15 # Tamaño de cada celda en píxeles
# Colores
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
START_COLOR = (0, 255, 0) # Verde
END_COLOR = (255, 0, 0) # Rojo
PATH_COLOR = (0, 0, 255) # Azul para el camino solucionado
BUTTON_COLOR = (0, 128, 0) # Verde oscuro
BUTTON_HOVER_COLOR = (0, 200, 0) # Verde claro
# Inicialización de Pygame
pygame.init()
SCREEN_WIDTH = WIDTH * CELL_SIZE
SCREEN_HEIGHT = HEIGHT * CELL_SIZE + 50 # Espacio extra para el botón
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Laberinto con Solución - Algoritmo de Kruskal")
clock = pygame.time.Clock()
class Cell:
def __init__(self, x, y):
self.x = x # Columna
self.y = y # Fila
self.walls = {'N': True, 'S': True, 'E': True, 'W': True}
self.parent = self # Para el conjunto disjunto
self.rank = 0
self.visited = False # Para la generación del laberinto
def find(self):
if self.parent != self:
self.parent = self.parent.find()
return self.parent
def union(self, other):
root1 = self.find()
root2 = other.find()
if root1 == root2:
return
if root1.rank < root2.rank:
root1.parent = root2
else:
root2.parent = root1
if root1.rank == root2.rank:
root1.rank += 1
def draw(self, surface):
x = self.x * CELL_SIZE
y = self.y * CELL_SIZE
if self.walls['N']:
pygame.draw.line(surface, WHITE, (x, y), (x + CELL_SIZE, y))
if self.walls['S']:
pygame.draw.line(surface, WHITE, (x, y + CELL_SIZE), (x + CELL_SIZE, y + CELL_SIZE))
if self.walls['E']:
pygame.draw.line(surface, WHITE, (x + CELL_SIZE, y), (x + CELL_SIZE, y + CELL_SIZE))
if self.walls['W']:
pygame.draw.line(surface, WHITE, (x, y), (x, y + CELL_SIZE))
def generate_maze():
# Crear la cuadrícula de celdas
grid = [[Cell(x, y) for y in range(HEIGHT)] for x in range(WIDTH)]
# Crear lista de paredes
walls = []
for x in range(WIDTH):
for y in range(HEIGHT):
if x > 0:
walls.append(((grid[x][y], grid[x - 1][y]), 'W')) # Pared oeste
if y > 0:
walls.append(((grid[x][y], grid[x][y - 1]), 'N')) # Pared norte
# Mezclar las paredes aleatoriamente
random.shuffle(walls)
# Aplicar el algoritmo de Kruskal
for (cell1, cell2), direction in walls:
if cell1.find() != cell2.find():
cell1.union(cell2)
# Eliminar la pared entre cell1 y cell2
if direction == 'N':
cell1.walls['N'] = False
cell2.walls['S'] = False
elif direction == 'W':
cell1.walls['W'] = False
cell2.walls['E'] = False
return grid
def draw_maze(grid, start_cell, end_cell):
screen.fill(BLACK)
for x in range(WIDTH):
for y in range(HEIGHT):
grid[x][y].draw(screen)
# Dibujar el inicio y el final
pygame.draw.rect(screen, START_COLOR, (start_cell.x * CELL_SIZE + 2, start_cell.y * CELL_SIZE + 2, CELL_SIZE - 4, CELL_SIZE - 4))
pygame.draw.rect(screen, END_COLOR, (end_cell.x * CELL_SIZE + 2, end_cell.y * CELL_SIZE + 2, CELL_SIZE - 4, CELL_SIZE - 4))
def draw_button(surface):
button_width = 100
button_height = 40
button_x = (SCREEN_WIDTH - button_width) // 2
button_y = SCREEN_HEIGHT - button_height - 5
mouse_pos = pygame.mouse.get_pos()
button_rect = pygame.Rect(button_x, button_y, button_width, button_height)
if button_rect.collidepoint(mouse_pos):
pygame.draw.rect(surface, BUTTON_HOVER_COLOR, button_rect)
else:
pygame.draw.rect(surface, BUTTON_COLOR, button_rect)
font = pygame.font.Font(None, 36)
text = font.render("Resolver", True, WHITE)
text_rect = text.get_rect(center=button_rect.center)
surface.blit(text, text_rect)
return button_rect
def bfs_solve_maze(grid, start_cell, end_cell):
queue = deque()
queue.append(start_cell)
came_from = {start_cell: None}
while queue:
current = queue.popleft()
if current == end_cell:
break
# Obtener celdas vecinas sin paredes
neighbors = []
x = current.x
y = current.y
if not current.walls['N'] and y > 0:
neighbors.append(grid[x][y - 1])
if not current.walls['S'] and y < HEIGHT - 1:
neighbors.append(grid[x][y + 1])
if not current.walls['E'] and x < WIDTH - 1:
neighbors.append(grid[x + 1][y])
if not current.walls['W'] and x > 0:
neighbors.append(grid[x - 1][y])
for neighbor in neighbors:
if neighbor not in came_from:
queue.append(neighbor)
came_from[neighbor] = current
# Reconstruir el camino
path = []
current = end_cell
while current != start_cell:
path.append(current)
current = came_from.get(current)
if current is None:
return [] # No hay camino
path.append(start_cell)
path.reverse()
return path
def animate_path(path):
for cell in path:
if cell in (path[0], path[-1]):
continue # Ya están dibujados
x = cell.x * CELL_SIZE + CELL_SIZE // 2
y = cell.y * CELL_SIZE + CELL_SIZE // 2
pygame.draw.circle(screen, PATH_COLOR, (x, y), CELL_SIZE // 4)
pygame.display.flip()
pygame.time.delay(20)
def reset_grid(grid):
for x in range(WIDTH):
for y in range(HEIGHT):
grid[x][y].visited = False
def main():
grid = generate_maze()
# Definir el punto de inicio y final
start_cell = grid[0][0] # Esquina superior izquierda
end_cell = grid[WIDTH - 1][HEIGHT - 1] # Esquina inferior derecha
draw_maze(grid, start_cell, end_cell)
pygame.display.flip()
running = True
solving = False
path_drawn = False
path = []
while running:
clock.tick(60) # Limitar a 60 FPS
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
button_rect = draw_button(screen)
if button_rect.collidepoint(event.pos) and not solving and not path_drawn:
# Iniciar la resolución del laberinto
solving = True
if solving:
# Encontrar el camino utilizando BFS
path = bfs_solve_maze(grid, start_cell, end_cell)
if path:
print("¡Laberinto resuelto!")
animate_path(path)
path_drawn = True
else:
print("No hay solución.")
solving = False
draw_maze(grid, start_cell, end_cell)
# Volver a dibujar el camino si ya fue encontrado
if path_drawn and path:
animate_path(path)
button_rect = draw_button(screen)
pygame.display.flip()
pygame.quit()
if __name__ == "__main__":
main()
Explicación de los Cambios
1. Implementación de BFS para Encontrar el Camino
Hemos reemplazado el método de resolución anterior (solve_maze_animation) con una función bfs_solve_maze que utiliza el Algoritmo de Búsqueda en Anchura (BFS) para encontrar el camino más corto desde el inicio hasta el final del laberinto. BFS es adecuado para encontrar la ruta más corta en laberintos sin pesos en las aristas.
def bfs_solve_maze(grid, start_cell, end_cell):
queue = deque()
queue.append(start_cell)
came_from = {start_cell: None}
while queue:
current = queue.popleft()
if current == end_cell:
break
# Obtener celdas vecinas sin paredes
neighbors = []
x = current.x
y = current.y
if not current.walls['N'] and y > 0:
neighbors.append(grid[x][y - 1])
if not current.walls['S'] and y < HEIGHT - 1:
neighbors.append(grid[x][y + 1])
if not current.walls['E'] and x < WIDTH - 1:
neighbors.append(grid[x + 1][y])
if not current.walls['W'] and x > 0:
neighbors.append(grid[x - 1][y])
for neighbor in neighbors:
if neighbor not in came_from:
queue.append(neighbor)
came_from[neighbor] = current
# Reconstruir el camino
path = []
current = end_cell
while current != start_cell:
path.append(current)
current = came_from.get(current)
if current is None:
return [] # No hay camino
path.append(start_cell)
path.reverse()
return path
2. Animación del Camino Encontrado
La función animate_path toma el camino encontrado y lo dibuja en pantalla de manera animada, mostrando únicamente el camino correcto.
def animate_path(path):
for cell in path:
if cell in (path[0], path[-1]):
continue # Ya están dibujados
x = cell.x * CELL_SIZE + CELL_SIZE // 2
y = cell.y * CELL_SIZE + CELL_SIZE // 2
pygame.draw.circle(screen, PATH_COLOR, (x, y), CELL_SIZE // 4)
pygame.display.flip()
pygame.time.delay(20)
3. Eliminación de la Exploración de Caminos Incorrectos
Al separar la búsqueda del camino de la animación, evitamos la visualización de pasos intermedios y caminos incorrectos. El usuario solo verá la animación del camino correcto una vez que se haya encontrado.
4. Control de Estados
Hemos agregado variables para controlar el estado de la animación y evitar que se vuelva a resolver el laberinto múltiples veces.
solving = False
path_drawn = False
path = []
5. Actualización del Ciclo Principal (main)
En el ciclo principal, al hacer clic en el botón "Resolver", se inicia la búsqueda del camino utilizando BFS. Una vez encontrado, se anima el dibujo del camino.
if event.type == pygame.MOUSEBUTTONDOWN:
button_rect = draw_button(screen)
if button_rect.collidepoint(event.pos) and not solving and not path_drawn:
# Iniciar la resolución del laberinto
solving = True
if solving:
# Encontrar el camino utilizando BFS
path = bfs_solve_maze(grid, start_cell, end_cell)
if path:
print("¡Laberinto resuelto!")
animate_path(path)
path_drawn = True
else:
print("No hay solución.")
solving = False
Además, si el camino ya ha sido encontrado y dibujado, se asegura de que se mantenga en pantalla redibujándolo constantemente.
if path_drawn and path:
animate_path(path)
Resultado
Con estos cambios, el programa generará un laberinto utilizando el algoritmo de Kruskal y, al hacer clic en el botón "Resolver", encontrará el camino más corto desde el inicio hasta el final utilizando BFS. La animación mostrará únicamente el camino correcto, sin explorar ni visualizar caminos incorrectos.
Este enfoque mejora la eficiencia visual y proporciona una experiencia más clara al mostrar únicamente la solución del laberinto.
Consideraciones Adicionales
-
Optimización de Rendimiento: Dado que estás trabajando con un laberinto de 40x40 celdas, la animación del camino debería ser lo suficientemente rápida. Sin embargo, si aumentas el tamaño del laberinto, podrías considerar optimizar la velocidad de la animación o la manera en que se dibujan las celdas.
-
Interactividad: Puedes expandir la funcionalidad para permitir la generación de nuevos laberintos después de resolver uno, o añadir botones adicionales para restablecer o regenerar el laberinto.
-
Visualización del Camino Más Corto: Al usar BFS, garantizas que el camino encontrado es el más corto en términos de número de celdas. Si prefieres otro criterio para la solución, puedes considerar otros algoritmos como A*.
Espero que estos cambios y explicaciones te ayuden a lograr el comportamiento deseado en tu programa de resolución de laberintos.