- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
from enum import Enum
from dataclasses import dataclass
class Pathfind:
__init__ = lambda self, maxmoves=9999: exec(f'self.maxmoves={maxmoves}')
def pathfind(self, cells):
i, found, ecords, path = 0, False, (0,0), list()
while(not found):
a = self.getbyval(cells, i)
for n in [j for sub in [self.filterneighbors(self.getneighbors(cells, x[0], x[1])) for x in a] for j in sub]:
cells[n.ccoords[1]][n.ccoords[0]].value = i+1 if cells[n.ccoords[1]][n.ccoords[0]].value>(i+1) else cells[n.ccoords[1]][n.ccoords[0]].value
if cells[n.ccoords[1]][n.ccoords[0]].ctype == CellType.END: found, ecords = True, (n.ccoords[1],n.ccoords[0])
if i<self.maxmoves: i+=1
else: return False
found, cpath = False, ecords
while(not found):
path.append(cpath)
if cpath == self.getbyval(cells, 0)[0]: return path
cell = list(filter(None, ([x if x.value==cells[cpath[0]][cpath[1]].value-1 else None for x in self.filterneighbors(self.getneighbors(cells, cpath[0], cpath[1]))])))[0]
cpath = (cell.ccoords[1],cell.ccoords[0])
listtocells = lambda self, lst: [[Cell(CellType(lst[y][x]), (x,y), 0 if lst[y][x]==2 else self.maxmoves) for x in range(len(lst[y]))] for y in range(len(lst))]
getbyval = lambda self, cells, val: [(x, y) for x in range(len(cells)) for y in range(len(cells[x])) if cells[x][y].value == val]
getneighbors = lambda self, cells, x, y: list(filter(None, [cells[x-1][y] if x>0 else None,cells[x+1][y] if x<len(cells)-1 else None,cells[x][y-1] if y>0 else None,cells[x][y+1] if y<len(cells[x])-1 else None]))
filterneighbors = lambda self, cells: list(filter(lambda cell: False if (cell is None) or cell.ctype==CellType.WALL else True, cells))
class CellType(Enum):
AIR, WALL, START, END = 0, 1, 2, 3
@dataclass
class Cell:
ctype: CellType = CellType.AIR
ccoords: tuple = (0,0)
value: int = 0