From 637b7567b446dd83b2da3b7e3b68098e7e10c6b0 Mon Sep 17 00:00:00 2001 From: Paulina Smierzchalska Date: Thu, 25 Apr 2024 22:56:18 +0200 Subject: [PATCH] Pierwsza wersja AStar --- AStar.py | 139 ++++++++++++++++++++++++++++++++++++++++++++++++++++++- App.py | 22 +++++++-- Node.py | 5 ++ 3 files changed, 162 insertions(+), 4 deletions(-) diff --git a/AStar.py b/AStar.py index db59e29..0a020cc 100644 --- a/AStar.py +++ b/AStar.py @@ -3,4 +3,141 @@ f(n) = g(n) + h(n) g(n) = dotychczasowy koszt -> dodać currentCost w Node lub brać koszt na nowo przy oddtawrzaniu ścieżki h(n) = abs(state['x'] - goalTreassure[0]) + abs(state['y'] - goalTreassure[1]) -> odległość Manhatan -> można zrobić jeszcze drugą wersje gdzie mnoży się razy 5.5 ze wzgledu na średni koszt przejścia Należy zaimplementować kolejkę priorytetową oraz zaimplementować algorytm przeszukiwania grafu stanów z uwzględnieniem kosztu za pomocą przerobienia algorytmu przeszukiwania grafu stanów -""" \ No newline at end of file +""" +import pygame +import Node +import BFS +from displayControler import NUM_X, NUM_Y +from Pole import stoneList +from queue import PriorityQueue + + +def heuristic(state, goal): + # Oblicz odległość Manhattanowską między aktualnym stanem a celem + manhattan_distance = abs(state['x'] - goal[0]) + abs(state['y'] - goal[1]) + return manhattan_distance + + +def get_cost_for_plant(plant_name): + plant_costs = { + "pszenica": 7, + "kukurydza": 9, + "ziemniak": 2, + "slonecznik": 5, + "borowka": 3, + "winogrono": 4, + "mud": 15, + "dirt": 0, + } + if plant_name in plant_costs: + return plant_costs[plant_name] + else: + # Jeśli nazwa rośliny nie istnieje w słowniku, zwróć domyślną wartość + return 0 + + +def A_star(istate, pole): + # goalTreasure = (random.randint(0,NUM_X-1), random.randint(0,NUM_Y-1)) + # #jeśli chcemy używać random musimy wykreslić sloty z kamieniami, ponieważ tez mogą się wylosować i wtedy traktor w ogóle nie rusza + #lub zrobić to jakoś inaczej, np. funkcja szukająca najmniej nawodnionej rośliny + goalTreasure = (18, 11) # Współrzędne celu + fringe = PriorityQueue() # Kolejka priorytetowa dla wierzchołków do rozpatrzenia + explored = [] # Lista odwiedzonych stanów + + # Tworzenie węzła początkowego + x = Node.Node(istate) + x.g = 0 + x.h = heuristic(x.state, goalTreasure) + fringe.put((x.g + x.h, x)) # Dodanie węzła do kolejki + + while not fringe.empty(): + _, elem = fringe.get() # Pobranie węzła z najniższym priorytetem + + if BFS.goalTest3(elem.state, goalTreasure): # Sprawdzenie, czy osiągnięto cel + path = [] + while elem.parent is not None: # Odtworzenie ścieżki + path.append([elem.parent, elem.action]) + elem = elem.parent + return path + + explored.append(elem.state) + + for resp in succ3A(elem.state): + child_state = resp[1] + if child_state not in explored: + child = Node.Node(child_state) + child.parent = elem + child.action = resp[0] + + # Pobranie nazwy rośliny z danego slotu na podstawie współrzędnych + plant_name = get_plant_name_from_coordinates(child_state['x'], child_state['y'], pole) + # Pobranie kosztu dla danej rośliny + plant_cost = get_cost_for_plant(plant_name) + + # Obliczenie kosztu ścieżki dla dziecka + child.g = elem.g + plant_cost + # Obliczenie heurystyki dla dziecka + child.h = heuristic(child.state, goalTreasure) + + in_fringe = False + for priority, item in fringe.queue: + if item.state == child.state: + in_fringe = True + if priority > child.g + child.h: + # Jeśli znaleziono węzeł w kolejce o gorszym priorytecie, zastąp go nowym + fringe.queue.remove((priority, item)) + fringe.put((child.g + child.h, child)) + break + + if not in_fringe: + # Jeśli stan dziecka nie jest w kolejce, dodaj go do kolejki + fringe.put((child.g + child.h, child)) + + for event in pygame.event.get(): + if event.type == pygame.QUIT: + quit() + + return False + + +def get_plant_name_from_coordinates(x, y, pole): + if (x, y) in pole.slot_dict: # Sprawdzenie, czy podane współrzędne znajdują się na polu + slot = pole.slot_dict[(x, y)] # Pobranie slotu na podstawie współrzędnych + if slot.plant: # Sprawdzenie, czy na slocie znajduje się roślina + return slot.plant.nazwa # Zwrócenie nazwy rośliny na slocie + else: + return None # jeśli na slocie nie ma rośliny + else: + return None # jeśli podane współrzędne są poza polem + + +#to ogólnie identyczna funkcja jak w BFS ale nie chciałam tam ruszać, żeby przypadkiem nie zapsuć do BFS, +#tylko musiałam dodac sprawdzenie kolizji, bo traktor brał sloty z Y których nie ma na planszy +def succ3A(state): + resp = [] + if state["direction"] == "N": + if state["y"] > 0 and (state['x'], state["y"] - 1) not in stoneList and is_field_available(state["x"], state["y"] - 1): + resp.append(["forward", {'x': state["x"], 'y': state["y"]-1, 'direction': state["direction"]}]) + resp.append(["right", {'x': state["x"], 'y': state["y"], 'direction': "E"}]) + resp.append(["left", {'x': state["x"], 'y': state["y"], 'direction': "W"}]) + elif state["direction"] == "S": + if state["y"] < NUM_Y and (state['x'], state["y"] + 1) not in stoneList and is_field_available(state["x"], state["y"] + 1): + resp.append(["forward", {'x': state["x"], 'y': state["y"]+1, 'direction': state["direction"]}]) + resp.append(["right", {'x': state["x"], 'y': state["y"], 'direction': "W"}]) + resp.append(["left", {'x': state["x"], 'y': state["y"], 'direction': "E"}]) + elif state["direction"] == "E": + if state["x"] < NUM_X and (state['x'] + 1, state["y"]) not in stoneList and is_field_available(state["x"] + 1, state["y"]): + resp.append(["forward", {'x': state["x"]+1, 'y': state["y"], 'direction': state["direction"]}]) + resp.append(["right", {'x': state["x"], 'y': state["y"], 'direction': "S"}]) + resp.append(["left", {'x': state["x"], 'y': state["y"], 'direction': "N"}]) + else: #state["direction"] == "W" + if state["x"] > 0 and (state['x'] - 1, state["y"]) not in stoneList and is_field_available(state["x"] - 1, state["y"]): + resp.append(["forward", {'x': state["x"]-1, 'y': state["y"], 'direction': state["direction"]}]) + resp.append(["right", {'x': state["x"], 'y': state["y"], 'direction': "N"}]) + resp.append(["left", {'x': state["x"], 'y': state["y"], 'direction': "S"}]) + + return resp + +def is_field_available(x, y): + # Sprawdzenie, czy współrzędne pola znajdują się na polu i czy pole jest dostępne + return 0 <= x < NUM_X and 0 <= y < NUM_Y and (x, y) not in stoneList \ No newline at end of file diff --git a/App.py b/App.py index a0c3ea8..51b3ebf 100644 --- a/App.py +++ b/App.py @@ -8,13 +8,16 @@ import Image import Osprzet import Ui import BFS +import AStar bfs1_flag=False bfs2_flag=False #Change this lines to show different bfs implementation -bfs3_flag=True -if bfs3_flag: - Pole.stoneFlag = True +bfs3_flag=False +Astar = True +if bfs3_flag or Astar: + Pole.stoneFlag = True + pygame.init() show_console=True @@ -72,6 +75,19 @@ def init_demo(): #Demo purpose bfsRoot3.reverse() print_to_console("Traktor porusza sie obliczona sciezka BFS") traktor.move_by_root(bfsRoot3, pole, [traktor.irrigateSlot]) + if (Astar): + aStarRoot = AStar.A_star({'x': 0, 'y': 0, 'direction': "E"}, pole) + if aStarRoot: + print("Pełna ścieżka agenta:") + aStarRoot.reverse() + for node in aStarRoot: + state = node[0].state # Pobranie stanu z obiektu Node + action = node[1] # Pobranie akcji + #print("Współrzędne pola:", state['x'], state['y'], "- Akcja:",action) # wypisuje ścieżkę i kroki które robi traktor + print_to_console("Traktor porusza się obliczoną ścieżką A*") + traktor.move_by_root(aStarRoot, pole, [traktor.irrigateSlot]) + else: + print_to_console("Nie można znaleźć ścieżki A*") # Wyświetl komunikat, jeśli nie znaleziono ścieżki diff --git a/Node.py b/Node.py index cc88608..8982784 100644 --- a/Node.py +++ b/Node.py @@ -6,3 +6,8 @@ class Node: def __init__(self, state): self.state = state + def __lt__(self, other): + """ + Definicja metody __lt__ (less than), która jest wymagana do porównywania obiektów typu Node. + """ + return self.g + self.h < other.g + other.h \ No newline at end of file