# Arup Guha
# 6/11/2024
# Example of reading a file storing a maze and displaying that
# in Pygame.

import pygame, sys
from pygame.locals import *

SCREEN_W = 1000
SCREEN_H = 600
MARGIN = 100
def main():

    # Basic set up.
    pygame.init()
    DISPLAYSURF = pygame.display.set_mode((SCREEN_W, SCREEN_H))
    pygame.display.set_caption("Load Maze from File")

    myfile = open("map.txt", "r")

    # Get the grid size.
    toks = myfile.readline().split()
    r = int(toks[0])
    c = int(toks[1])

    # Get a safe square size.
    sqsize = min( (SCREEN_W-MARGIN)//c, (SCREEN_H-MARGIN)//r)
    width = sqsize*c
    height = sqsize*r

    # Store the board here.
    board = []

    # Read each line and add it to the board.
    for i in range(r):
        tmp = myfile.readline().strip()
        board.append(tmp)

    # Close file.
    myfile.close()
        
    # Game loop.
    while True:

        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

        DISPLAYSURF.fill("white")

        # Find starting location to center.
        startx = (SCREEN_W - width)//2
        starty = (SCREEN_H - height)//2

        # Loop through the input board indexes.
        for i in range(r):
            for j in range(c):

                # Calculate the corresponding x y coordinates.
                x = startx + j*sqsize
                y = starty + i*sqsize

                # Background will be black, valid squares gold.
                if board[i][j] == 'X':
                    pygame.draw.rect(DISPLAYSURF, "black", (x, y, sqsize, sqsize), 0)
                else:
                    pygame.draw.rect(DISPLAYSURF, "gold", (x, y, sqsize, sqsize), 0)
    
        pygame.display.update()

# Run it.
main()
