I'm not very confident about this piece of code I created, it basically takes a file like this:
## #
## ## #
#B # #
# ## ##
##
A######
Then proceeds to draw a maze in the window.
The class Maze has 3 variables: columns, rows and maze_layout (a matrix each location is a character) example 2x2 maze: [["#" "A"],["#","B"]].
The code is this:
import pygame
import sys
import os
# Size of each square on the Maze
MAZE_SQUARESIZE = 40
# Colors
GREEN = (34, 139, 34)
ROSERED = (180, 75, 95)
DARKGRAY = (69, 69, 69)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
DARKPURPLE = (48, 25, 52)
# Creates a Maze with pygame
class Maze:
def __init__(self, filename):
if not os.path.isfile(filename):
raise FileNotFoundError("File not found:", filename)
with open(filename, 'r') as file:
self.maze_layout = [list(line.rstrip('\n')) for line in file.readlines()]
self.cols = len(self.maze_layout[0])
self.rows = len(self.maze_layout)
def display_maze(self, screen):
self.draw_grid(screen)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
# Drawing functions for maze
def draw_grid(self, window):
for x in range(self.rows):
for y in range(self.cols):
rect = pygame.Rect(y * MAZE_SQUARESIZE, x * MAZE_SQUARESIZE, MAZE_SQUARESIZE, MAZE_SQUARESIZE)
if self.maze_layout[x][y] == "#":
pygame.draw.rect(window, DARKPURPLE, rect)
elif self.maze_layout[x][y] == " ":
pygame.draw.rect(window, WHITE, rect, 1)
elif self.maze_layout[x][y] == "A":
pygame.draw.rect(window, ROSERED, rect)
elif self.maze_layout[x][y] == "B":
pygame.draw.rect(window, GREEN, rect)
def main():
pygame.init()
filename = "maze1.txt"
maze = Maze(filename)
screen = pygame.display.set_mode((maze.cols * MAZE_SQUARESIZE, maze.rows * MAZE_SQUARESIZE))
maze.display_maze(screen)
pygame.quit()
if __name__ == "__main__":
main()
If someone could find ways to improve this code, I would be very grateful. I'm open to any sort of criticism.