make in python a labyrinth and an ai that tries to learn it and make it userfriendly…
- User
make in python a labyrinth and an ai that tries to learn it and make it userfriendly full of features logs rich and informations on screen\
- Assistant
make in python a labyrinth and an ai that tries to learn it and make it userfriendly full of features logs rich and informations on screen\
Creating a comprehensive labyrinth (maze) application with an AI that learns to navigate it involves several components:
We'll use Python along with the pygame library for the graphical interface. The AI will utilize a simple pathfinding algorithm (like Depth-First Search) to navigate the maze. For a more advanced learning AI, techniques like Reinforcement Learning can be used, but that would be more complex.
Below is a complete Python script that accomplishes the above. Make sure you have pygame installed. You can install it using:
pip install pygame
import pygame
import sys
import random
from collections import deque
import logging
# Initialize logging
logging.basicConfig(level=logging.INFO, format='%(message)s')
logger = logging.getLogger()
# Constants
CELL_SIZE = 20
MAZE_WIDTH = 25
MAZE_HEIGHT = 25
SCREEN_WIDTH = CELL_SIZE * MAZE_WIDTH
SCREEN_HEIGHT = CELL_SIZE * MAZE_HEIGHT + 100 # Extra space for logs
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
GRAY = (220, 220, 220)
# Directions
DIRS = [(-1, 0), (1, 0), (0, -1), (0, 1)]
class Maze:
def __init__(self, width, height):
self.width = width
self.height = height
self.grid = [[1 for _ in range(width)] for _ in range(height)]
self.generate_maze()
def generate_maze(self):
def carve(x, y):
dirs = DIRS[:]
random.shuffle(dirs)
for dx, dy in dirs:
nx, ny = x + dx*2, y + dy*2
if 0 <= nx < self.height and 0 <= ny < self.width and self.grid[nx][ny] == 1:
self.grid[nx][ny] = 0
self.grid[x + dx][y + dy] = 0
carve(nx, ny)
start_x, start_y = 0, 0
self.grid[start_x][start_y] = 0
carve(start_x, start_y)
def draw(self, screen):
for x in range(self.height):
for y in range(self.width):
rect = pygame.Rect(y * CELL_SIZE, x * CELL_SIZE, CELL_SIZE, CELL_SIZE)
if self.grid[x][y] == 1:
pygame.draw.rect(screen, BLACK, rect)
else:
pygame.draw.rect(screen, WHITE, rect)
class AI:
def __init__(self, maze):
self.maze = maze
self.start = (0, 0)
self.end = (maze.height - 1, maze.width - 1)
self.path = []
self.visited = set()
self.queue = deque()
self.queue.append((self.start, [self.start]))
self.found = False
logger.info("AI initialized. Starting search...")
def step(self):
if self.queue and not self.found:
current, path = self.queue.popleft()
if current in self.visited:
return
self.visited.add(current)
logger.info(f"Visiting: {current}")
if current == self.end:
self.path = path
self.found = True
logger.info("Exit found!")
return
x, y = current
for dx, dy in DIRS:
nx, ny = x + dx, y + dy
if 0 <= nx < self.maze.height and 0 <= ny < self.maze.width:
if self.maze.grid[nx][ny] == 0 and (nx, ny) not in self.visited:
self.queue.append(( (nx, ny), path + [(nx, ny)] ))
else:
logger.info("No more nodes to explore.")
def draw(self, screen):
for pos in self.visited:
x, y = pos
rect = pygame.Rect(y * CELL_SIZE, x * CELL_SIZE, CELL_SIZE, CELL_SIZE)
pygame.draw.rect(screen, GRAY, rect)
for pos in self.path:
x, y = pos
rect = pygame.Rect(y * CELL_SIZE, x * CELL_SIZE, CELL_SIZE, CELL_SIZE)
pygame.draw.rect(screen, GREEN, rect)
# Draw start and end
sx, sy = self.start
ex, ey = self.end
pygame.draw.rect(screen, BLUE, pygame.Rect(sy * CELL_SIZE, sx * CELL_SIZE, CELL_SIZE, CELL_SIZE))
pygame.draw.rect(screen, RED, pygame.Rect(ey * CELL_SIZE, ex * CELL_SIZE, CELL_SIZE, CELL_SIZE))
def main():
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Maze AI Navigator")
clock = pygame.time.Clock()
font = pygame.font.SysFont(None, 24)
maze = Maze(MAZE_WIDTH, MAZE_HEIGHT)
ai = AI(maze)
running = True
ai_steps = 0
logs = []
max_logs = 5
while running:
screen.fill(WHITE)
maze.draw(screen)
ai.draw(screen)
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# AI steps
if not ai.found:
ai.step()
ai_steps += 1
# Display logs
log_surface = pygame.Surface((SCREEN_WIDTH, 100))
log_surface.fill(GRAY)
y_offset = 10
for i, handler in enumerate(logger.handlers):
pass # To keep potential multiple handlers, but here we have one
# Get logger records
for i, record in enumerate(logger.handlers[0].stream.buffer):
if i >= max_logs:
break
text = font.render(record.decode(), True, BLACK)
log_surface.blit(text, (10, y_offset))
y_offset += 20
screen.blit(log_surface, (0, CELL_SIZE * MAZE_HEIGHT))
pygame.display.flip()
clock.tick(10) # AI steps per second
pygame.quit()
sys.exit()
if __name__ == "__main__":
main()
Maze class generates a random maze using a recursive backtracking (Depth-First Search) algorithm.AI class uses Breadth-First Search (BFS) to find the shortest path from the start to the end of the maze. It logs each visited node.logging library. For on-screen display, you might need to implement a custom logging handler.While the above script provides a foundational implementation, here are ways to enhance user-friendliness and feature richness:
To display logs within the pygame window, we can create a custom logging handler:
class PygameLogHandler(logging.Handler):
def __init__(self):
super().__init__()
self.log_messages = deque(maxlen=10) # Adjust the number of log lines
def emit(self, record):
log_entry = self.format(record)
self.log_messages.append(log_entry)
# Usage in the main script
# Replace the logging setup with the custom handler
def main():
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Maze AI Navigator")
clock = pygame.time.Clock()
font = pygame.font.SysFont(None, 24)
# Setup custom logging handler
log_handler = PygameLogHandler()
log_handler.setFormatter(logging.Formatter('%(message)s'))
logger.addHandler(log_handler)
logger.setLevel(logging.INFO)
maze = Maze(MAZE_WIDTH, MAZE_HEIGHT)
ai = AI(maze)
running = True
ai_steps = 0
while running:
screen.fill(WHITE)
maze.draw(screen)
ai.draw(screen)
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# AI steps
if not ai.found:
ai.step()
ai_steps += 1
# Display logs
log_surface = pygame.Surface((SCREEN_WIDTH, 100))
log_surface.fill(GRAY)
y_offset = 10
for log in list(log_handler.log_messages):
text = font.render(log, True, BLACK)
log_surface.blit(text, (10, y_offset))
y_offset += 20
screen.blit(log_surface, (0, CELL_SIZE * MAZE_HEIGHT))
pygame.display.flip()
clock.tick(10) # AI steps per second
pygame.quit()
sys.exit()
PygameLogHandler captures log messages and stores them in a deque for on-screen display.main function, replacing the default handler with the custom one.This script provides a foundational framework for a maze generator and an AI navigator. Depending on your requirements, you can expand upon this by implementing more sophisticated AI algorithms, enhancing the user interface, adding user controls, and improving logging and information display.
Feel free to modify and enhance the script to better suit your needs!
Not yet included in a published release.