This: -fixed cost sum in A* -added cost of direction change for A*2 -added function to change image of visited tile -added display of total cost

This commit is contained in:
jakzar 2024-04-28 12:58:58 +02:00
parent e448c80739
commit 7c50b44417
5 changed files with 53 additions and 18 deletions

View File

@ -72,19 +72,20 @@ def A_star(istate, pole, goalTreasure):
if BFS.goalTest3(elem.state, goalTreasure): # Sprawdzenie, czy osiągnięto cel if BFS.goalTest3(elem.state, goalTreasure): # Sprawdzenie, czy osiągnięto cel
path = [] path = []
total_cost = elem.g cost_list=[]
print("Koszt", total_cost)
while elem.parent is not None: # Odtworzenie ścieżki while elem.parent is not None: # Odtworzenie ścieżki
path.append([elem.parent, elem.action]) path.append([elem.parent, elem.action])
elem = elem.parent elem = elem.parent
for node, action in path: for node, action in path:
# Obliczanie kosztu ścieżki dla każdego pola i wyświetlanie # Obliczanie kosztu ścieżki dla każdego pola i wyświetlanie
plant_cost = get_plant_name_and_cost_from_coordinates(child_state['x'], child_state['y'], pole) plant_cost = get_plant_name_and_cost_from_coordinates(node.state['x'],node.state['y'], pole)
if action == "left" or action == "right": # Liczenie kosztu tylko dla pól nie będących obrotami if action == "left" or action == "right": # Liczenie kosztu tylko dla pól nie będących obrotami
total_cost += obrot total_cost += obrot
cost_list.append(obrot)
else: else:
total_cost += plant_cost total_cost += plant_cost
return path cost_list.append(plant_cost)
return path,cost_list,total_cost
explored.append(elem.state) explored.append(elem.state)
@ -188,22 +189,34 @@ def A_star2(istate, pole, goalTreasure):
# break # break
fringe = PriorityQueue() # Kolejka priorytetowa dla wierzchołków do rozpatrzenia fringe = PriorityQueue() # Kolejka priorytetowa dla wierzchołków do rozpatrzenia
explored = [] # Lista odwiedzonych stanów explored = [] # Lista odwiedzonych stanów
obrot = 1
# Tworzenie węzła początkowego # Tworzenie węzła początkowego
x = Node.Node(istate) x = Node.Node(istate)
x.g = 0 x.g = 0
x.h = heuristic2(x.state, goalTreasure) x.h = heuristic2(x.state, goalTreasure)
fringe.put((x.g + x.h, x)) # Dodanie węzła do kolejki fringe.put((x.g + x.h, x)) # Dodanie węzła do kolejki
total_cost=0
while not fringe.empty(): while not fringe.empty():
_, elem = fringe.get() # Pobranie węzła z najniższym priorytetem _, elem = fringe.get() # Pobranie węzła z najniższym priorytetem
if BFS.goalTest3(elem.state, goalTreasure): # Sprawdzenie, czy osiągnięto cel if BFS.goalTest3(elem.state, goalTreasure): # Sprawdzenie, czy osiągnięto cel
path = [] path = []
cost_list=[]
while elem.parent is not None: # Odtworzenie ścieżki while elem.parent is not None: # Odtworzenie ścieżki
path.append([elem.parent, elem.action]) path.append([elem.parent, elem.action])
elem = elem.parent elem = elem.parent
return path for node, action in path:
# Obliczanie kosztu ścieżki dla każdego pola i wyświetlanie
plant_cost = get_plant_name_and_cost_from_coordinates(node.state['x'],node.state['y'], pole)
if action == "left" or action == "right": # Liczenie kosztu tylko dla pól nie będących obrotami
total_cost += obrot
cost_list.append(obrot)
else:
total_cost += plant_cost
cost_list.append(plant_cost)
return path,cost_list,total_cost
explored.append(elem.state) explored.append(elem.state)
@ -217,8 +230,10 @@ def A_star2(istate, pole, goalTreasure):
# Pobranie nazwy rośliny z danego slotu na podstawie współrzędnych # Pobranie nazwy rośliny z danego slotu na podstawie współrzędnych
plant_cost = get_plant_name_and_cost_from_coordinates(child_state['x'], child_state['y'], pole) plant_cost = get_plant_name_and_cost_from_coordinates(child_state['x'], child_state['y'], pole)
# Obliczenie kosztu ścieżki dla dziecka if child.action == "left" or child.action == "right":
child.g = elem.g + plant_cost child.g = elem.g + obrot
else:
child.g = elem.g + plant_cost
# Obliczenie heurystyki dla dziecka # Obliczenie heurystyki dla dziecka
child.h = heuristic2(child.state, goalTreasure) child.h = heuristic2(child.state, goalTreasure)

31
App.py
View File

@ -15,8 +15,8 @@ import random
bfs1_flag=False bfs1_flag=False
bfs2_flag=False #Change this lines to show different bfs implementation bfs2_flag=False #Change this lines to show different bfs implementation
bfs3_flag=False bfs3_flag=False
Astar = False Astar = True
Astar2 = True Astar2 = False
if bfs3_flag or Astar or Astar2: if bfs3_flag or Astar or Astar2:
Pole.stoneFlag = True Pole.stoneFlag = True
@ -79,25 +79,38 @@ def init_demo(): #Demo purpose
print_to_console("Traktor porusza sie obliczona sciezka BFS") print_to_console("Traktor porusza sie obliczona sciezka BFS")
traktor.move_by_root(bfsRoot3, pole, [traktor.irrigateSlot]) traktor.move_by_root(bfsRoot3, pole, [traktor.irrigateSlot])
if (Astar): if (Astar):
aStarRoot = AStar.A_star({'x': 0, 'y': 0, 'direction': "E"}, pole, goalTreasure) aStarRoot,cost_list,total_cost= AStar.A_star({'x': 0, 'y': 0, 'direction': "E"}, pole, goalTreasure)
if aStarRoot: if aStarRoot:
#print("Pełna ścieżka agenta:") print("Pełna ścieżka agenta:")
aStarRoot.reverse() aStarRoot.reverse()
#for node in aStarRoot: cost_list.reverse()
# state = node[0].state # Pobranie stanu z obiektu Node i=0
# action = node[1] # Pobranie akcji for node in aStarRoot:
# print("Współrzędne pola:", state['x'], state['y'], "- Akcja:",action) # wypisuje ścieżkę i kroki które robi traktor 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,"- Koszt: ",cost_list[i])
i=i+1
print_to_console("Traktor porusza się obliczoną ścieżką A*") print_to_console("Traktor porusza się obliczoną ścieżką A*")
traktor.move_by_root(aStarRoot, pole, [traktor.irrigateSlot]) traktor.move_by_root(aStarRoot, pole, [traktor.irrigateSlot])
print("Koszt:", total_cost)
else: else:
print_to_console("Nie można znaleźć ścieżki A*") # Wyświetl komunikat, jeśli nie znaleziono ścieżki print_to_console("Nie można znaleźć ścieżki A*") # Wyświetl komunikat, jeśli nie znaleziono ścieżki
if (Astar2): if (Astar2):
aStarRoot2 = AStar.A_star2({'x': 0, 'y': 0, 'direction': "E"}, pole, goalTreasure) aStarRoot2,cost_list= AStar.A_star2({'x': 0, 'y': 0, 'direction': "E"}, pole, goalTreasure)
if aStarRoot2: if aStarRoot2:
print("Pełna ścieżka agenta:")
aStarRoot2.reverse() aStarRoot2.reverse()
cost_list.reverse()
i=0
for node in aStarRoot2:
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,"- Koszt: ",cost_list[i])
i=i+1
print_to_console("Traktor porusza się obliczoną ścieżką A*") print_to_console("Traktor porusza się obliczoną ścieżką A*")
traktor.move_by_root(aStarRoot2, pole, [traktor.irrigateSlot]) traktor.move_by_root(aStarRoot2, pole, [traktor.irrigateSlot])
print("Koszt:", total_cost)
else: else:
print_to_console("Nie można znaleźć ścieżki A*") # Wyświetl komunikat, jeśli nie znaleziono ścieżki print_to_console("Nie można znaleźć ścieżki A*") # Wyświetl komunikat, jeśli nie znaleziono ścieżki

View File

@ -18,7 +18,8 @@ class Image:
4:"winogrono", 4:"winogrono",
5:"ziemniak", 5:"ziemniak",
6:"dirt", 6:"dirt",
7:"mud"} 7:"mud",
8:"road"}
for index in files_plants: for index in files_plants:
if index >= 6: if index >= 6:
plant_image = pygame.image.load("images/" + files_plants[index] + ".jpg") plant_image = pygame.image.load("images/" + files_plants[index] + ".jpg")

View File

@ -23,7 +23,12 @@ class Slot:
pygame.display.update() pygame.display.update()
def redraw_image(self): def redraw_image(self):
self.set_image() self.mark_visited()
def mark_visited(self):
plant,self.plant_image=self.image_loader.return_plant('road')
self.screen.blit(self.plant_image, (self.x_axis * dCon.CUBE_SIZE, self.y_axis * dCon.CUBE_SIZE))
pygame.draw.rect(self.screen, Colors.BLACK, self.field, BORDER_THICKNESS)
def color_change(self,color): def color_change(self,color):
self.plant=color self.plant=color

1
Ui.py
View File

@ -25,6 +25,7 @@ class Ui:
def render_text_to_console(self,string_to_print): def render_text_to_console(self,string_to_print):
font=pygame.font.Font(self.font,self.font_size) font=pygame.font.Font(self.font,self.font_size)
string_to_print=str(string_to_print)
self.break_string_to_console(string_to_print) self.break_string_to_console(string_to_print)
for string in self.to_print: for string in self.to_print:
text=font.render(string,True,Colors.BLACK,Colors.WHITE) text=font.render(string,True,Colors.BLACK,Colors.WHITE)