def run(n, a, display): # s = ( (1,2,4,7,5,3,0,8,6),(2,0) ) # t = ( (1,2,3,4,5,6,7,8,0),(2,2) ) for i in range(n * n): if a[i] == 0: idx = i s = (tuple(a), (idx // n, idx % n)) a = [] for i in range(1, n * n): a.append(i) a.append(0) t = (tuple(a), (n - 1, n - 1)) algo = Astar(n, s, t) while True: if not algo.found: idx = algo.search() drawBoard(n, idx[0], display) if idx == t: path = algo.createPath() time.sleep(3) for idx in path: drawBoard(n, idx[0], display) time.sleep(2) for event in pygame.event.get(): if event.type == pygame.QUIT: exit()
def main(): pygame.init() # Taking input from user n = int(input("Enter grid size:")) Sx, Sy = [int(x) for x in input("Enter knight coords:").split()] Tx, Ty = [int(x) for x in input("Enter queen coords:").split()] # Setting up the screen and images res = (n*pixels,n*pixels) gameDisplay = pygame.display.set_mode(res) queen = pygame.image.load("queen.png") knight = pygame.image.load("knight.png") # Initializing the board and the algo createChessboard(gameDisplay,n) placeEntity(queen,Ty,Tx,gameDisplay) d = Astar(n,Sx,Sy,Tx,Ty) # game loop running = True while running: if not d.found: # returns current node and previous node t, prev = d.search() placeEntity(knight,t[1],t[0],gameDisplay) markVisited(prev[1],prev[0],gameDisplay) pygame.display.update() time.sleep(.2) if t == (Tx,Ty): createChessboard(gameDisplay,n) placeEntity(queen,Ty,Tx,gameDisplay) placeEntity(knight,Sy,Sx,gameDisplay) path = d.createPath() for i,j in path[1:]: markVisited(j,i,gameDisplay) pygame.display.update() continue for event in pygame.event.get(): if event.type == pygame.QUIT: running = False break print("Target position ",(Tx,Ty)," reached: ",d.visited[Tx][Ty]) pygame.quit()