visual_maze.py

Created by antarctus

Created on May 08, 2023

1.32 KB

Démonstration graphique de l’algorithme de Kruskal.
Vous pouvez générer de tel labyrinthe avec mod_maze.
C’est une telle technique qui est utilisé par mon jeu ombre


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

c_coeff=[randint(0,2**16) for i in range(3)]

def get_c(n):
  return (c_coeff[0]*n%255,c_coeff[1]*n%255,c_coeff[2]*n%255)

def maze(WIDTH,HEIGHT):
  C_WIDTH=320//WIDTH
  C_HEIGHT=222//HEIGHT
  S_WIDTH=(320-WIDTH*C_WIDTH)//2
  S_HEIGHT=(222-HEIGHT*C_HEIGHT)//2

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

  def draw(x,y):
    fill_rect(S_WIDTH+x*C_WIDTH,S_HEIGHT+y*C_HEIGHT,C_WIDTH,C_HEIGHT,get_c(map_[x][y]))

  def replace_all(n1,n2):
    nonlocal map_
    for x in range(WIDTH):
      if n1 in map_[x]:
        for y in range(HEIGHT):
          if map_[x][y]==n1:
            map_[x][y]=n2
            draw(x,y)

  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])

  for x in range(WIDTH):
    for y in range(HEIGHT):
      draw(x,y)

  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)
      draw(x,y)
      sleep(0.1)
    del poss[i]
  return map_


fill_rect(0,0,320,222,(100,)*3)

maze(31,21)
#maze(63,43)