themaze_utils.py

Created by mathieu-croslacoste

Created on September 16, 2025

8.73 KB

Dependency of https://my.numworks.com/python/mathieu-croslacoste/themaze


from time import sleep as P
from random import randint as R,seed as S
import math
#dim=(30,8)
dim=(38,8)
def Clr():print("\n"*(dim[1]+1))
class Curseur:
 def __init__(s):s.Btns=[];s.id=0
class Btn:
 def __init__(s,cur,Txt):cur.Btns.append(s);s.cur=cur;s.txt=Txt
 def GetStr(s):
  if s.cur.Btns[s.cur.id]==s:return s.txt
  else:return s.txt.replace("["," ").replace("]"," ")
class Img:
 def __init__(s,dat):s.dat=dat
class StrVar:
 def __init__(s,dat):s.dat=dat
class Gui:
 def __init__(s):s.cur=Curseur();s.Widgets=[];s._lastCmd=""
 def Clr(s):s.Widgets=[];s._lastCmd="";s.cur.id=0;s.cur.Btns=[]
 def WidgetId(s,adress):
  for i in range(len(s.Widgets)):
   if s.Widgets[i][0]==adress:return i
 def Print(s):
  Screen=[]
  for i in range(dim[1]):
   temp=[]
   for o in range(dim[0]):temp.append(" ")
   Screen.append(temp)
  for i in s.Widgets:
   Txt=""
   try:
    if type(i[0])==Img:
     x,y=i[3],i[2];indY=0
     for y1 in i[0].dat:
      indX=0
      for x1 in y1:
       try:Screen[indY+y][indX+x]=x1
       except:0
       indX+=1
      indY+=1
    else:
     if type(i[0])==str:Txt=i[0]
     elif type(i[0])==StrVar:Txt=str(i[0].dat)
     elif type(i[0])==Btn:Txt=i[0].GetStr()
     if i[1]=="PlaceCenter":
      x=int((dim[0]/2)-math.ceil(len(Txt)/2));x1=0
      for l in Txt:Screen[i[2]][x+x1]=l;x1+=1
     elif i[1]=="Locate":
      x=i[3];x1=0
      for l in Txt:Screen[i[2]][x+x1]=l;x1+=1
   except:0
  for i in Screen:
   line=""
   for o in i:line+=o
   print(line)
 def Draw(s):
  s.Print()
  cmd=input();s._lastCmd=cmd
  if cmd=="":return s.cur.id,cmd,s.cur.Btns[s.cur.id]
  else:return None,cmd,None
 def DelWidget(s,adress):
  if type(adress)==Btn:s.cur.Btns.remove(adress);s.cur.id=0
  for i in range(len(s.Widgets)):
   if s.Widgets[i][0]==adress:del s.Widgets[i];return
 def PlaceCenter(s,obj,Ln):s.Widgets.append([obj,"PlaceCenter",Ln])
 def Locate(s,obj,Ln,Col):s.Widgets.append([obj,"Locate",Ln,Col])
 def UpCursor(s):
  if s._lastCmd in"8462":
   x,y=0,0
   for i in s.Widgets:
    if type(i[0])!=Btn:continue
    Txt=i[0].GetStr()
    if i[0]==s.cur.Btns[s.cur.id]:
     if i[1]=="PlaceCenter":x=int((dim[0]/2)-math.ceil(len(Txt)/2));y=i[2]
     elif i[1]=="Locate":x,y=i[3],i[2]
   dir=[None,100]
   for i in s.Widgets:
    if type(i[0])!=Btn:continue
    dis=100;x1,y1=0,0;Txt=i[0].GetStr()
    if i[1]=="PlaceCenter":x1,y1=int((dim[0]/2)-math.ceil(len(Txt)/2)),i[2]
    elif i[1]=="Locate":x1,y1=i[3],i[2]
    dis=math.sqrt(((y1-y)**2)+(x1-x)**2)
    if s._lastCmd=="8":
     if y1<y and dis<dir[1]:dir=[i[0],dis]
    if s._lastCmd=="2":
     if y1>y and dis<dir[1]:dir=[i[0],dis]
    if s._lastCmd=="4":
     if x1<x and dis<dir[1]:dir=[i[0],dis]
    if s._lastCmd=="6":
     if x1>x and dis<dir[1]:dir=[i[0],dis]
   if dir[0]!=None:s.cur.id=s.cur.Btns.index(dir[0])
 def BtnInput(s):
  retour=None
  while retour==None:
   retour,_,_=s.Draw()
   if retour==None:s.UpCursor()
  return retour
validGui=Gui()
def BoxValidCnfrm(txt):
 validGui.Clr();gui=validGui;txt=txt.split(" ");gui.Locate("#"*dim[0],0,0);y=1
 while len(txt):
  msg=""
  while len(txt)and len(msg)+len(txt[0])<dim[0]-3:msg+=" "+txt.pop(0)
  gui.Locate(msg,y,0);y+=1
 gui.Locate("#"*dim[0],dim[1]-1,0);gui.Locate(Btn(gui.cur," [OUI] "),dim[1]-1,int((dim[0]/4)-math.ceil(7/2))+1);gui.Locate(Btn(gui.cur," [NON] "),dim[1]-1,int((3*dim[0]/4)-math.ceil(7/2)));return gui.BtnInput()==0
guiConfOK=Gui()
def BoxConfOK(txt):
 guiConfOK.Clr();gui=guiConfOK;txt=txt.split(" ");gui.Locate("#"*dim[0],0,0);y=1
 while len(txt):
  msg=""
  while len(txt)and len(msg)+len(txt[0])<dim[0]-3:msg+=" "+txt.pop(0)
  gui.Locate(msg,y,0);y+=1
 gui.Locate("#"*dim[0],dim[1]-1,0);gui.PlaceCenter(Btn(gui.cur," [OK] "),dim[1]-1);gui.Draw();return 1
def MainMenu():Clr();gui=Gui();Titre="The Master Maze";gui.PlaceCenter((len(Titre)+2)*"=",0);gui.PlaceCenter(" "+Titre+" ",1);gui.PlaceCenter((len(Titre)+2)*"=",2);gui.PlaceCenter(Btn(gui.cur,"[Commencer une partie]"),4);gui.PlaceCenter(Btn(gui.cur,"[Entrer un code]"+" "*6),5);gui.PlaceCenter(Btn(gui.cur,"[Quitter]"+" "*12),7);return gui.BtnInput()
class C_Maze:
 def __init__(s,w,h,seed,symbols=None):
  s.init_symbols(symbols);s.w=w;s.h=h;s.seed=seed;s.path=[];s.player=(0,0);s.grid=[]
  for col in range(w):
   temp=[]
   for row in range(h):temp.append(w*row+col)
   s.grid.append(temp)
  s.portals={};s.gen()
 def __repr__(s):return s.toStr()
 def toStr(s):
  t=''
  for col in range(s.w):t+=s.wall_c+s.wall_h
  t+=s.wall_c+'\n'
  for row in range(s.h):
   if row==0:t+=s.wall_v+s.start
   else:t+=s.wall_v+s.empty
   for col in range(1,s.w):
    if s.grid[col-1][row]in s.portals[s.grid[col][row]]:c=s.empty
    else:c=s.wall_v
    if row==s.h-1 and col==s.w-1:c+=s.end
    else:c+=s.empty
    t+=c
   t+=s.wall_v+'\n'
   for col in range(s.w):
    c=s.wall_h;key=s.grid[col][row]
    if row+1<s.h and s.grid[col][row+1]in s.portals[key]:c=s.empty
    t+=s.wall_c+c
   t+=s.wall_c+'\n'
  t+=s.empty;return t
 def init_symbols(s,symbols):s.start=symbols[0];s.end=symbols[1];s.wall_h=symbols[2];s.wall_v=symbols[3];s.wall_c=symbols[4];s.empty=' '
 def gen(s):
  edges_ordered=[]
  for row in range(s.h):
   for col in range(s.w):    
    cell=(col,row);left_cell=(col-1,row);down_cell=(col,row-1);near=[]
    if col>0:near.append((left_cell,cell))
    if row>0:near.append((down_cell,cell))
    edges_ordered.extend(near)
  S(s.seed);edges=[]
  while len(edges_ordered)>0:edges.append(edges_ordered.pop(R(0,len(edges_ordered))-1))
  disjoint_set=DisjointSet()
  for row in range(0,s.h):
   for col in range(0,s.w):key=s.grid[col][row];disjoint_set.make_set(key);s.portals[key]={}
  edge_count=0;key_count=s.grid[s.w-1][s.h-1]
  while edge_count<key_count:
   edge=edges.pop();key_a=s.grid[edge[0][0]][edge[0][1]];key_b=s.grid[edge[1][0]][edge[1][1]];set_a=disjoint_set.find(key_a);set_b=disjoint_set.find(key_b)
   if set_a!=set_b:edge_count+=1;s.portals[key_a][key_b]=1;s.portals[key_b][key_a]=1;disjoint_set.union(set_a,set_b)
class DisjointSet:
 class El:
  def __init__(s,key):s.key=key;s.parent=s;s.rank=0
  def __eq__(s,other):return s.key==other.key
  def __ne__(s,other):return s.key!=other.key
 def __init__(s):s.tree={}
 def make_set(s,key):
  e=s.El(key)
  if not key in s.tree.keys():s.tree[key]=e
 def find(s,key):
  if key in s.tree.keys():
   el=s.tree[key]
   if el.parent!=el:el.parent=s.find(el.parent.key)
  return el.parent
 def union(s,elA,elB):
  rootA=s.find(elA.key);rootB=s.find(elB.key)
  if rootA!=rootB:
   if rootA.rank<rootB.rank:rootA.parent=rootB
   elif rootA.rank>rootB.rank:rootB.parent=rootA
   else:rootB.parent=rootA;rootA.rank+=1
def GetW(name):
 w=0
 for i in name.split("\n"):
  if len(i)>w:w=len(i)
 return w
def GetH(name):return len(name.split("\n"))
def GetImg(name):
 if name[0]=="\n":name=name[1:]
 Lst=name.split("\n");Screen=[]
 for i in range(GetH(name)):
  temp=[]
  for o in range(GetW(name)):temp.append(" ")
  Screen.append(temp)
 Y=0
 for i in Lst:
  X=0
  for o in i:(Screen[Y])[X]=o;X+=1
  Y+=1
 return Screen
def p1():return Img(GetImg("""
 |
_|_ o __
 I /|\\)_)
   / \\
"""))
def p2():return Img(GetImg("""
 |
_|_ o .-.
 I /|\\|.|
   / \\!_!
"""))
def p3():return Img(GetImg("""
 |     _
_|_ o | |
 I /|\\)o(
   / \\|_|
"""))
def chest():return Img(GetImg("""
  __________
 /\\____;;___\\
| /         /
./_________/
|\\         \\
| |---------|
\\ |    ))   |
 \\|_________|
"""))
def Monster1():return Img(GetImg("""
     /--------\\
    | o     o  \\
  ./| .vvvvv.  |\\
 / /| |     |  |\\\\
//' | `^vvvv'  | \\\\
    |          |  ~
     7        /
    /    /\\   \\
"""))
def Monster2():return Img(GetImg("""
 __           __
/  \\  _____  /  \\
\\__/\\/     \\/\\__/
     |     |
  __/ \\_o_/ \\__
 /  \\  { }  /  \\
 \\__/       \\__/
"""))
Dialogues=(
"Pierre","Paul","Jack",
"Un monstre apparait ! Préparez-vous à vous battre !",
"Vous ne pouvez pas sélectionner un personnage mort",
"Ha ! Je vous tiens !",
"Vous êtes foutu ! Je vais vous tuer",
"VOUS NE PASSEREZ PAS !",
"Félicitations, vous avez gagné le combat !",
"Vous avez perdu !",
"C'est l'heure de la loterie !",
("Tout commence dans un Donjon. Vous avez été enfermés pour une raison que l'on ignore,","mais vous devez absolument vous enfuir pour survivre.","Au cours de ce périple, vous devrez vous battre.","Vous êtes une équipe de 3 personnes dont vous devrez alterner"),
("Félicitations, vous êtes parvenus à arriver jusqu'a la sortie.","Vos trois personnages sont enfin libres !","Libérés, DELIVREEEEEEEES... Hurm Hurm un peu plus de sérieux et bravo !","Merci d'avoir joué")
)
class Block():
 def __init__(it):it.img=Img([])
 def Get(it):return it.img
class Wall(Block):
 def __init__(it):it.img=Img([["#","#"],["#","#"]])
class Door(Block):
 def __init__(it,gui):super().__init__();it.Btn=Btn(gui.cur,"[@]")
 def Get(it):return it.Btn
Swords=(("Petit Glaive",3),("Glaive",5),("Epée Rouillée",8),("Epée Du Soldat",12),("Master Sword",15))

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.