Maze in Python

Started by TomToad, October 14, 2019, 17:24:37

Previous topic - Next topic

TomToad

Trying to relearn Python.  Decided to test my knowledge by creating a maze.  Biggest problem I'm running into is remembering to put a : after loops and function definitions.  Here is what I came up with.
Code ('Python') Select
import random

#Will use this dictionary to aid in connecting two cells together
opposites = {'north':'south','south':'north','east':'west','west':'east'}

class Cell:
    def __init__(self,row,column):
       self.row = row
       self.column = column
       self.directions = dict() #an empty dictionary
       self.connections = {'north':False,'south':False,'east':False,'west':False} #False = wall
       self.visited = False
       
    def connect(self,direction):
        self.connections[direction[0]] = True #True = no wall
        self.directions.pop(direction[0])
        direction[1].connections[opposites[direction[0]]] = True #do the same for connecting room
        direction[1].directions.pop(opposites[direction[0]])
   
    #returns all connections that haven't been visited yet as a list of tuples
    #(direction,connected cell)
    def getDirections(self):
        directions = []
        for direction, cell in self.directions.items():
            if cell.visited == False:
                directions.append((direction,cell))
        return directions
       
class Maze:
    def __init__(self,rows,columns):
        self.rows = rows
        self.columns = columns
        self.grid = [] #The grid of cells
       
        #initialize the grid with cells
        for row in range(rows):
            self.grid.append([])
            for column in range(columns):
                self.grid[row].append(Cell(row,column))

        #Connect cells together
        for row in range(rows):
            for column in range(columns):
                if row > 0:
                    self.grid[row][column].directions['north']=self.grid[row-1][column]
                if row < rows-1:
                    self.grid[row][column].directions['south']=self.grid[row+1][column]
                if column > 0:
                    self.grid[row][column].directions['west']=self.grid[row][column-1]
                if column < columns-1:
                    self.grid[row][column].directions['east']=self.grid[row][column+1]

        self.generate()
               
    def getRandomCell(self):
        #returns a random cell from the grid
        return self.grid[random.randrange(self.rows)][random.randrange(self.columns)]
       
    def generate(self):
        #get a random cell to initiate, mark it visited, and add it to a stack
        cell = self.getRandomCell()
        cell.visited = True
        stack = [cell]
       
        #keep looping until the stack is empty
        while len(stack) > 0:
            cell = stack[-1] #get the top cell
            directions = cell.getDirections()
           
            #if this cell has directions left to choose from, then pick one
            #otherwise, remove this cell from the stack.  It's done
            if len(directions) > 0:
                #pick will be a tuple (direction,connected cell)
                pick = random.choice(directions)
                cell.connect(pick)
                stack.append(pick[1])
                pick[1].visited = True
            else:
                stack.pop()
   
    #loop through the grid and print the cells, leave gaps where there is no wall
    def out(self):
        s = '*'
        for i in range(self.columns):
            s += '***'
        print(s)
        for row in range(self.rows):
            s = '*'
            for column in range(self.columns):
                if self.grid[row][column].connections['east'] == True:
                    s += '   '
                else:
                    s += '  *'
            print(s)
            s = '*'
            for column in range(self.columns):
                if self.grid[row][column].connections['south'] == True:
                    s += '  *'
                else:
                    s += '***'
            print(s)



maze = Maze(10,10)
maze.out()


------------------------------------------------
8 rabbits equals 1 rabbyte.

RemiD

it seems mazes are popular these days ahahah  ;)

3DzForMe

Nice stuff, and in Python  ;D
BLitz3D, IDEal, AGK Studio, BMax, Java Code, Cerberus
Recent Hardware: Dell Laptop
Oldest Hardware: Commodore Amiga 1200 with 1084S Monitor & Blitz Basic 2.1

Pfaber11

How's the maze coming along ? Haven't looked at python in quite a while . Do you have a go to language ? Mines currently PureBasic  but had over a year with AGK2 and a couple of months with Python . Anyway good luck with the maze .
HP 15s i3 1.2 upto 3.4 ghz 128 gb ssd 16 gb ram 15.6 inch screen. Windows 11 home edition .  2Tb external hard drive dedicated to Linux Mint .
  PureBasic 6 and AppGameKit studio
ASUS Vivo book 15 16gb ram 256gb storage  cpu upto 4.1 ghz
HP Desktop AMD 3700 16GB ram 2 GB graphics card windows 10