Respetar el original: Python algoritmo de generación de laberinto: pantalla gráfica para lograr
Información de gráficos laberinto
código que describe
GameSearch.py
código completo
Laberinto Información Gráfico
Pygame realiza mediante cuatro tipos de una pantalla gráfica laberinto algoritmo, como se muestra, hay cuatro botones, haciendo clic con el botón del ratón para el algoritmo de conmutación que genera un laberinto. Pulsar cualquier tecla para generar un laberinto, mientras que la adición del algoritmo A * pathfinding, para representar cuatro algoritmos diferentes para generar laberinto, punto rojo es el punto de partida y el punto final es la línea verde usando algoritmo A * obtenido desde el principio hasta el final.
Código Descripción
implementación del código tiene cuatro archivos
GameMap.py: Guardar tipo Mapa de información básica laberinto, una nota en la parte delantera del algoritmo laberinto introducido en un lado por separado en un archivo.
MazeGenerator.py: Este es el código que implementa cuatro tipos laberinto algoritmo, en un solo archivo.
AStarSearch.py: * Un algoritmo para lograr, se introduce en la parte delantera del artículo A * algoritmo.
GameSearch.py: Código de pygame escrito usando una pantalla gráfica del laberinto
en frente de tres documentos se han dicho aquí, el orador principal en GameSearch.py
GameSearch.py
parámetros de configuración de laberinto, el tamaño de cada unidad de laberinto REC_SIZE, REC_WIDTH y REC_HEIGHT son el ancho y la longitud del laberinto, pueden ser modificados, pero los requisitos de instalación laberinto algoritmo de generación, debe ser impar.
REC_SIZE = 10
REC_WIDTH = 51 # must be odd number
REC_HEIGHT = 51 # must be odd number
BUTTON_HEIGHT = 30
BUTTON_WIDTH = 120
SCREEN_WIDTH = REC_WIDTH * REC_SIZE
SCREEN_HEIGHT = REC_HEIGHT * REC_SIZE + BUTTON_HEIGHT
botón de algoritmo, __init__ función para establecer la ubicación y el tamaño de un botón, los cambios de color y desmarca la función de posición para ajustar el clic de un botón.
class Button():
def __init__(self, screen, type, x, y):
self.screen = screen
self.width = BUTTON_WIDTH
self.height = BUTTON_HEIGHT
self.button_color = (128,128,128)
self.text_color = [(0,255,0), (255,0,0)]
self.font = pygame.font.SysFont(None, BUTTON_HEIGHT*2//3)
self.rect = pygame.Rect(0, 0, self.width, self.height)
self.rect.topleft = (x, y)
self.type = type
self.init_msg()
def init_msg(self):
self.msg_image = self.font.render(generator_types[self.type], True, self.text_color[0], self.button_color)
self.msg_image_rect = self.msg_image.get_rect()
self.msg_image_rect.center = self.rect.center
def draw(self):
self.screen.fill(self.button_color, self.rect)
self.screen.blit(self.msg_image, self.msg_image_rect)
def click(self, game):
game.maze_type = self.type
self.msg_image = self.font.render(generator_types[self.type], True, self.text_color[1], self.button_color)
def unclick(self):
self.msg_image = self.font.render(generator_types[self.type], True, self.text_color[0], self.button_color)
categoría de juego, __init__ función inicializa el mapa de clase, el algoritmo de Prim seleccionados al azar por defecto y añadir algoritmo de botón. generateMaze cada función realiza una operación de entrada de tecla, el bucle se ejecuta cuatro operaciones (1 generación laberinto, 2. Generar el inicio y final 3. A * algoritmo con la trayectoria generada, 4. Quitar laberinto). check_buttons funcionan algoritmo algoritmo de laberinto están destinados para el botón seleccionado.
class Game():
def __init__(self):
pygame.init()
self.screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
self.clock = pygame.time.Clock()
self.map = Map(REC_WIDTH, REC_HEIGHT)
self.mode = 0
self.maze_type = MAZE_GENERATOR_TYPE.RANDOM_PRIM
self.buttons = []
self.buttons.append(Button(self.screen, MAZE_GENERATOR_TYPE.RECURSIVE_BACKTRACKER, 0, 0))
self.buttons.append(Button(self.screen, MAZE_GENERATOR_TYPE.RANDOM_PRIM, BUTTON_WIDTH + 10, 0))
self.buttons.append(Button(self.screen, MAZE_GENERATOR_TYPE.RECURSIVE_DIVISION, (BUTTON_WIDTH + 10) * 2, 0))
self.buttons.append(Button(self.screen, MAZE_GENERATOR_TYPE.UNION_FIND_SET, (BUTTON_WIDTH + 10) * 3, 0))
self.buttons[0].click(self)
def play(self):
self.clock.tick(30)
pygame.draw.rect(self.screen, (255, 255, 255), pygame.Rect(0, 0, SCREEN_WIDTH, BUTTON_HEIGHT))
for button in self.buttons:
button.draw()
for y in range(self.map.height):
for x in range(self.map.width):
type = self.map.getType(x, y)
if type == MAP_ENTRY_TYPE.MAP_EMPTY:
color = (255, 255, 255)
elif type == MAP_ENTRY_TYPE.MAP_BLOCK:
color = (0, 0, 0)
elif type == MAP_ENTRY_TYPE.MAP_TARGET:
color = (255, 0, 0)
else:
color = (0, 255, 0)
pygame.draw.rect(self.screen, color, pygame.Rect(REC_SIZE*x, REC_SIZE*y+BUTTON_HEIGHT, REC_SIZE, REC_SIZE))
def generateMaze(self):
if self.mode >= 4:
self.mode = 0
if self.mode == 0:
generateMap(self.map, self.maze_type)
elif self.mode == 1:
self.source = self.map.generatePos((1,1),(1, self.map.height-2))
self.dest = self.map.generatePos((self.map.width-2, self.map.width-2), (1, self.map.height-2))
self.map.setMap(self.source[0], self.source[1], MAP_ENTRY_TYPE.MAP_TARGET)
self.map.setMap(self.dest[0], self.dest[1], MAP_ENTRY_TYPE.MAP_TARGET)
elif self.mode == 2:
AStarSearch(self.map, self.source, self.dest)
self.map.setMap(self.source[0], self.source[1], MAP_ENTRY_TYPE.MAP_TARGET)
self.map.setMap(self.dest[0], self.dest[1], MAP_ENTRY_TYPE.MAP_TARGET)
else:
self.map.resetMap(MAP_ENTRY_TYPE.MAP_EMPTY)
self.mode += 1
def check_buttons(game, mouse_x, mouse_y):
for button in game.buttons:
if button.rect.collidepoint(mouse_x, mouse_y):
button.click(game)
for tmp in game.buttons:
if tmp != button:
tmp.unclick()
break
El bucle principal, el acceso a los eventos de teclado y clic del ratón, esto se relaciona principalmente con el código de pygame.
game = Game()
while True:
game.play()
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.KEYDOWN:
game.generateMaze()
break
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_x, mouse_y = pygame.mouse.get_pos()
check_buttons(game, mouse_x, mouse_y)
El código completo
implementación completa del enlace github código laberinto algoritmo de visualización gráfica
Compilador entorno
+ pygame1.9 python3.7