class Node():
    """A node class for A* Pathfinding"""

    def __init__(self, parent=None, position=None):
        self.parent = parent
        self.position = position

        self.g = 0
        self.h = 0
        self.f = 0

    def __eq__(self, other):
        return self.position == other.position


def astar(maze, start, end):
    """Returns a list of tuples as a path from the given start to the given end in the given maze"""

    # Create start and end node
    start_node = Node(None, start)
    start_node.g = start_node.h = start_node.f = 0
    end_node = Node(None, end)
    end_node.g = end_node.h = end_node.f = 0

    # Initialize both open and closed list
    open_list = []
    closed_list = []

    # Add the start node
    open_list.append(start_node)

    # Loop until you find the end
    while len(open_list) > 0:

        # Get the current node
        current_node = open_list[0]
        current_index = 0
        for index, item in enumerate(open_list):
            if item.f < current_node.f:
                current_node = item
                current_index = index

        # Pop current off open list, add to closed list
        open_list.pop(current_index)
        closed_list.append(current_node)

        # Found the goal
        if current_node == end_node:
            path = []
            current = current_node
            while current is not None:
                path.append(current.position)
                current = current.parent
            return path[::-1] # Return reversed path

        # Generate children
        children = []
        for new_position in [(0, -1), (0, 1), (-1, 0), (1, 0), (-1, -1), (-1, 1), (1, -1), (1, 1)]: # Adjacent squares

            # Get node position
            node_position = (current_node.position[0] + new_position[0], current_node.position[1] + new_position[1])

            # Make sure within range
            if node_position[0] > (len(maze) - 1) or node_position[0] < 0 or node_position[1] > (len(maze[len(maze)-1]) -1) or node_position[1] < 0:
                continue

            # Make sure walkable terrain
            if maze[node_position[0]][node_position[1]] != 0:
                continue

            # Create new node
            new_node = Node(current_node, node_position)

            # Append
            children.append(new_node)

        # Loop through children
        for child in children:

            # Child is on the closed list
            for closed_child in closed_list:
                if child == closed_child:
                    continue

            # Create the f, g, and h values
            child.g = current_node.g + 1
            child.h = ((child.position[0] - end_node.position[0]) ** 2) + ((child.position[1] - end_node.position[1]) ** 2)
            child.f = child.g + child.h

            # Child is already in the open list
            for open_node in open_list:
                if child == open_node and child.g > open_node.g:
                    continue

            # Add the child to the open list
            open_list.append(child)
import pygame

pygame.init()


class cube():
    def __init__(self,pos,color = (255,0,0)):
        self.pos = pos
        self.color = color
    def draw(self,win):
        x = self.pos[0]*60
        y =self.pos[1]*60
        pygame.draw.rect(win,self.color,(x,y,60,60))




def drawGrid(w, rows, surface):
    sizeBtwn = w // rows  # Gives us the distance between the lines

    x = 0  # Keeps track of the current x
    y = 0  # Keeps track of the current y
    for l in range(rows):  # We will draw one vertical and one horizontal line each loop
        x = x + sizeBtwn
        y = y + sizeBtwn

        pygame.draw.line(surface, (255,255,255), (x,0),(x,w))
        pygame.draw.line(surface, (255,255,255), (0,y),(w,y))

def redrawWindow(win):
    win.fill((0,0,0))
    for cube in cubes:
        cube.draw(win)
    drawGrid(WIDTH,rows,win)
    pygame.display.update()

def main():
    global WIDTH,rows,cubes
    finish = False
    cubes = []
    WIDTH = 600
    rows = 10
    win = pygame.display.set_mode((WIDTH,WIDTH))
    clock = pygame.time.Clock()
    FPS = 60
    run = True
    while run:
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            if event.type == pygame.MOUSEBUTTONDOWN:
                x , y = pygame.mouse.get_pos()
                row = x //60
                col = y //60
                if len(cubes) ==0:
                    cubes.append(cube((row,col),(0,0,255)))
                elif len(cubes) ==1:
                    cubes.append(cube((row,col),(0,255,0)))
                else:
                    cubes.append(cube((row,col)))
            keys = pygame.key.get_pressed()
            if event.type == pygame.KEYDOWN:
                finish = True
                path = path_finding()
                for pos in path:
                    if not(pos == path[0]) and not(pos ==path[-1]):
                        pygame.draw.rect(win,(128,0,128),(pos[0]*60,pos[1]*60,60,60))
                drawGrid(WIDTH,rows,win)
                pygame.display.update()



        if not(finish):
            redrawWindow(win)


def path_finding():

    maze = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]


    start = cubes[0].pos
    end = cubes[1].pos
    a = len(cubes)
    for i in range(a):
        if i > 1:
            x ,y=cubes[i].pos
            maze[x][y] = 1 


    path = astar(maze, start, end)
    return path


main()
