mod_maze.py

Created by antarctus

Created on May 08, 2023

1.11 KB

Module permettant de créer des labyrinthes de toutes dimensions, en utilisant l’algorithme de Kruskal.

Contient deux fonctions, une maze(WIDTH,HEIGHT) qui renvoit une liste à deux dimensions avec la taille spécifié (bien penser à mettre deux nombres impairs) et draw_laby(map_) qui trace le labyrinthe fourni.
Vous pouvez comprendre de manière très claire cet algorithme avec visual maze


from math import *
from kandinsky import *
from random import *


def maze(WIDTH,HEIGHT):
  map_=[[(y%2)*(x%2)*(x//2+y//2*(WIDTH//2)+1) for y in range(HEIGHT)] for x in range(WIDTH)]

  def replace_all(n1,n2):
    nonlocal map_
    for l in map_:
      if n1 in l:
        for i in range(len(l)):
          if l[i]==n1:
            l[i]=n2

  def is_diff(x,y):
    if y%2:
      return (map_[x-1][y],map_[(x+1)%WIDTH][y])
    return (map_[x][y-1],map_[x][(y+1)%HEIGHT])

  poss=[(x*2+(y%2==0),y) for y in range(1,HEIGHT-1) for x in range(y%2,(WIDTH-1)//2)]
  for j in range(len(poss)):
    i=randint(0,len(poss)-1)
    x,y=poss[i]
    d=is_diff(x,y)
    if d[0]!=d[1]:
      replace_all(max(d),min(d))
      map_[x][y]=min(d)
    del poss[i]
  return map_

def draw_laby(map_):
  WIDTH=len(map_)
  HEIGHT=len(map_[0])
  fill_rect(0,0,320,222,(200,)*3)
  C_WIDTH=320//WIDTH
  C_HEIGHT=222//HEIGHT

  for x in range(WIDTH):
    for y in range(HEIGHT):
      if map_[x][y]==0:
        fill_rect(x*C_WIDTH,y*C_HEIGHT,C_WIDTH,C_HEIGHT,(100,)*3)
      else:
        fill_rect(x*C_WIDTH,y*C_HEIGHT,C_WIDTH,C_HEIGHT,(200,)*3)

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.