From 42aec48676aca13b2a210b3a19e403692e135479 Mon Sep 17 00:00:00 2001 From: kabix09 Date: Mon, 3 May 2021 00:23:18 +0200 Subject: [PATCH] code refactor - change var names & dir structure --- actions.py | 47 --- hero.py | 325 ------------------ othercharacters.py | 86 ----- server.py | 9 +- src/__init__.py | 0 src/__pycache__/__init__.cpython-39.pyc | Bin 0 -> 142 bytes src/__pycache__/direction.cpython-39.pyc | Bin 0 -> 711 bytes src/agent/__init__.py | 4 + src/agent/__pycache__/__init__.cpython-39.pyc | Bin 0 -> 248 bytes src/agent/__pycache__/hero.cpython-39.pyc | Bin 0 -> 4567 bytes src/agent/hero.py | 199 +++++++++++ .../map/__pycache__/gameMap.cpython-39.pyc | Bin 0 -> 1985 bytes model.py => src/agent/map/gameMap.py | 134 ++++---- src/agent/model/__init__.py | 6 + .../model/__pycache__/armor.cpython-39.pyc | Bin 0 -> 1201 bytes .../model/__pycache__/box.cpython-39.pyc | Bin 0 -> 751 bytes .../model/__pycache__/creature.cpython-39.pyc | Bin 0 -> 1871 bytes .../model/__pycache__/wall.cpython-39.pyc | Bin 0 -> 631 bytes .../model/__pycache__/weapon.cpython-39.pyc | Bin 0 -> 885 bytes src/agent/model/armor.py | 21 ++ src/agent/model/box.py | 13 + src/agent/model/creature.py | 47 +++ src/agent/model/dice/__init__.py | 0 .../dice/__pycache__/dice.cpython-39.pyc | Bin 0 -> 310 bytes src/agent/model/dice/dice.py | 5 + src/agent/model/wall.py | 9 + src/agent/model/weapon.py | 14 + state.py => src/agent/state.py | 0 .../__pycache__/actions.cpython-39.pyc | Bin 0 -> 234 bytes src/dictionary/actions.py | 5 + src/dictionary/directions.py | 8 + direction.py => src/direction.py | 9 +- src/items/__pycache__/armory.cpython-39.pyc | Bin 0 -> 1301 bytes armory.py => src/items/armory.py | 7 +- src/tree/__pycache__/node.cpython-39.pyc | Bin 0 -> 1291 bytes node.py => src/tree/node.py | 11 +- src/treesearch/__init__.py | 3 + .../actionsInterpreter.cpython-39.pyc | Bin 0 -> 957 bytes src/treesearch/__pycache__/bfs.cpython-39.pyc | Bin 0 -> 2863 bytes src/treesearch/actionsInterpreter.py | 40 +++ src/treesearch/bfs.py | 140 ++++++++ src/treesearch/heuristic/__init__.py | 1 + src/treesearch/heuristic/manhattan.py | 4 + 43 files changed, 611 insertions(+), 536 deletions(-) delete mode 100644 actions.py delete mode 100644 hero.py delete mode 100644 othercharacters.py create mode 100644 src/__init__.py create mode 100644 src/__pycache__/__init__.cpython-39.pyc create mode 100644 src/__pycache__/direction.cpython-39.pyc create mode 100644 src/agent/__init__.py create mode 100644 src/agent/__pycache__/__init__.cpython-39.pyc create mode 100644 src/agent/__pycache__/hero.cpython-39.pyc create mode 100644 src/agent/hero.py create mode 100644 src/agent/map/__pycache__/gameMap.cpython-39.pyc rename model.py => src/agent/map/gameMap.py (84%) create mode 100644 src/agent/model/__init__.py create mode 100644 src/agent/model/__pycache__/armor.cpython-39.pyc create mode 100644 src/agent/model/__pycache__/box.cpython-39.pyc create mode 100644 src/agent/model/__pycache__/creature.cpython-39.pyc create mode 100644 src/agent/model/__pycache__/wall.cpython-39.pyc create mode 100644 src/agent/model/__pycache__/weapon.cpython-39.pyc create mode 100644 src/agent/model/armor.py create mode 100644 src/agent/model/box.py create mode 100644 src/agent/model/creature.py create mode 100644 src/agent/model/dice/__init__.py create mode 100644 src/agent/model/dice/__pycache__/dice.cpython-39.pyc create mode 100644 src/agent/model/dice/dice.py create mode 100644 src/agent/model/wall.py create mode 100644 src/agent/model/weapon.py rename state.py => src/agent/state.py (100%) create mode 100644 src/dictionary/__pycache__/actions.cpython-39.pyc create mode 100644 src/dictionary/actions.py create mode 100644 src/dictionary/directions.py rename direction.py => src/direction.py (52%) create mode 100644 src/items/__pycache__/armory.cpython-39.pyc rename armory.py => src/items/armory.py (93%) create mode 100644 src/tree/__pycache__/node.cpython-39.pyc rename node.py => src/tree/node.py (64%) create mode 100644 src/treesearch/__init__.py create mode 100644 src/treesearch/__pycache__/actionsInterpreter.cpython-39.pyc create mode 100644 src/treesearch/__pycache__/bfs.cpython-39.pyc create mode 100644 src/treesearch/actionsInterpreter.py create mode 100644 src/treesearch/bfs.py create mode 100644 src/treesearch/heuristic/__init__.py create mode 100644 src/treesearch/heuristic/manhattan.py diff --git a/actions.py b/actions.py deleted file mode 100644 index 389ab12..0000000 --- a/actions.py +++ /dev/null @@ -1,47 +0,0 @@ -# Funkcja konwertujaca wspolrzedne nastepnego pola do odwiedzenia - -# pole to element wziety z kolejki path -from state import AgentState -from direction import Direction - -def actionsInterpreter(actionIndex, defaultState, directions): - - if actionIndex == -1: - return AgentState( - defaultState.get_x(), - defaultState.get_y(), - defaultState.get_direction().counterClockwise() - ) - elif actionIndex == 0: - move_x = 0 - move_y = 0 - - if defaultState.get_direction() == Direction.N: - move_y = 1 - elif defaultState.get_direction() == Direction.E: - move_x = 1 - elif defaultState.get_direction() == Direction.S: - move_y = -1 - elif defaultState.get_direction() == Direction.W: - move_x = -1 - - return AgentState( - defaultState.get_x() + move_x, # directions[defaultState.get_direction()[0]], - is not subscriptable ??? - defaultState.get_y() + move_y, # directions[defaultState.get_direction()][1], - is not subscriptable ??? - defaultState.get_direction() - ) - elif actionIndex == 1: - return AgentState( - defaultState.get_x(), - defaultState.get_y(), - defaultState.get_direction().clockwise() - ) - else: - return defaultState - - -actions = { - "rotateLeft": -1, - "moveForward": 0, - "rotateRight": 1 -} diff --git a/hero.py b/hero.py deleted file mode 100644 index 3d1b6b6..0000000 --- a/hero.py +++ /dev/null @@ -1,325 +0,0 @@ -import random -import heapq - -from mesa import Agent - -from othercharacters import dice, Box, Creature, Armor, Weapon -from actions import actions, actionsInterpreter -from state import AgentState -from direction import Direction -from node import Node - - -class Player(Creature): - def __init__(self, unique_id, model, n, s, a, w, maxhp, hp, weap, arm, g, w2, w3, listOfChests): - super().__init__(unique_id, model, n, s, a, w, maxhp, hp, weap, arm, g) - self.name = n - self.strength = s - self.agility = a - self.wisdom = w - self.maxHealth = maxhp - self.health = hp - self.gold = g - self.weapon1 = weap - self.weapon2 = w2 - self.weapon3 = w3 - self.armor = arm - self.isBox = False - self.isCreature = False - self.directions = { - Direction.N : [0, 1], - Direction.E : [1, 0], - Direction.S : [0, -1], - Direction.W : [-1, 0] - } - self.direction = Direction.N - self.queue = [] - self.hasgoalchest = False - self.openedchests = 0 - self.__listOfChests = listOfChests - self.__actionsCollection = [] - - def meleeAttack(self, opponent): - attackValue = self.strength + dice(6) - defenseValue = opponent.strength + opponent.armor.defence - damage = attackValue - defenseValue - if damage > 0: - opponent.health = opponent.health - (damage + self.weapon1.damage) - - def rangeAttack(self, opponent): - attackValue = self.agility + dice(6) - defenseValue = opponent.agility - damage = attackValue - defenseValue - if (damage > 0) and (damage + self.weapon2.damage - opponent.armor.defence > 0): - opponent.health = opponent.health - (damage + self.weapon2.damage - opponent.armor.defence) - - def magicAttack(self, opponent): - attackValue = self.wisdom + dice(6) - defenseValue = opponent.wisdom - damage = attackValue - defenseValue - if (damage > 0) and (damage + self.weapon3.damage - opponent.armor.mag_protection > 0): - opponent.health = opponent.health - (damage + self.weapon3.damage - opponent.armor.mag_protection) - - def fightOrFlight(self, opponent): - combat = True - while combat: - choice = dice(4) - print("dice rolled:", choice) - if choice == 1: - running_speed = self.agility + dice(6) - opponent_speed = opponent.agility + dice(6) - if running_speed > opponent_speed: - combat = False - print("Player ran away") - self.step() - else: - opponent.defaultAttack(self) - if self.health <= 0: - combat = False - print("Player died :/") - elif choice == 2: - self.meleeAttack(opponent) - if opponent.health > 0: - opponent.defaultAttack(self) - if self.health <= 0: - combat = False - print("Player died :/") - else: - combat = False - self.gold = self.gold + opponent.gold - opponent.gold = 0 - opponent.model.grid.remove_agent(opponent) - print("Fight won") - elif choice == 3: - self.rangeAttack(opponent) - if opponent.health > 0: - opponent.defaultAttack(self) - if self.health <= 0: - combat = False - print("Player died :/") - else: - combat = False - self.gold = self.gold + opponent.gold - opponent.gold = 0 - opponent.model.grid.remove_agent(opponent) - print("Fight won") - else: - self.magicAttack(opponent) - if opponent.health > 0: - opponent.defaultAttack(self) - if self.health <= 0: - combat = False - print("Player died :/") - else: - combat = False - self.gold = self.gold + opponent.gold - opponent.gold = 0 - opponent.model.grid.remove_agent(opponent) - print("Fight won") - - def openChest(self, chest): - self.gold = self.gold + chest.gold - print("------Chest opened. Gold inside:", chest.gold,"-----") - chest.gold = 0 - self.openedchests += 1 - self.hasgoalchest = False - chest.model.grid.remove_agent(chest) - #self.direction = 0 # po osiągnięciu jednego celu 'restartuje sie' na szukanie ścieżki do kolejnego -- NIE ZEROWAĆ OBROTU - to psuje goldState w bfs!!! - # if isinstance(chest.loot,Armor): - # buffer = self.armor - # self.armor = chest.loot - # chest.loot = buffer - # if isinstance(chest.loot,Weapon): - # if chest.loot.type == "Melee": - # buffer = self.weapon1 - # self.weapon1 = chest.loot - # chest.loot = buffer - # elif chest.loot.type == "Range": - # buffer = self.weapon2 - # self.weapon2 = chest.loot - # chest.loot = buffer - # elif chest.loot.type == "Magic": - # buffer = self.weapon3 - # self.weapon3 = chest.loot - # chest.loot = buffer - - #- - - - bfs & successor - - - -# - def successor(self, append): - - rotateLeft = AgentState( - append.get_x(), - append.get_y(), - append.get_direction().counterClockwise() - ) - - rotateRight = AgentState( - append.get_x(), - append.get_y(), - append.get_direction().clockwise() - ) - - move_x = 0 - move_y = 0 - - if append.get_direction() == Direction.N: - move_y = 1 - elif append.get_direction() == Direction.E: - move_x = 1 - elif append.get_direction() == Direction.S: - move_y = -1 - elif append.get_direction() == Direction.W: - move_x = -1 - - if append.get_x() + move_x >= 0 and append.get_x() + move_x < 10 and append.get_y() + move_y >=0 and append.get_y() + move_y < 10: - moveForward = AgentState( - append.get_x() + move_x, - append.get_y() + move_y, - append.get_direction() - ) - else: - moveForward = None - - return [ - [actions["rotateLeft"], rotateLeft], - [actions["moveForward"], moveForward], - [actions["rotateRight"], rotateRight] - ] - - def heuristics(self, state, target_state): - # cost is initially step distance in manhattan metric - return abs(state.get_x() - target_state.get_x()) + abs(state.get_y() - target_state.get_y()) - - def graphsearch(self, fringe, explored, istate, succesorFunction, goalState): - finalActionList = [] - init_state = [None, istate] - root = Node(None, init_state, 0) - heapq.heappush(fringe, (0, root)) # at beginning do nothing - - while len(fringe) != 0: - _flag = True - - if len(fringe) == 0: - return False - - tmpNode = (heapq.heappop(fringe))[1] # node - - # build dictionary - # parent = tmpNode.get_predecessor() # fetch parent state - # tmpNode.set_predecessor(None) # clear predecessor - don't build a tree chain - # if parent is None: - # finalActionList.append([parent, tmpNode]) - # else: - # finalActionList.append( - # [parent[1], tmpNode]) # pair(key, value) - key: parent state, value: current state + action - - if tmpNode._state.get_x() == goalState.get_x() and tmpNode._state.get_y() == goalState.get_y(): - while tmpNode._parent is not None: - finalActionList.append(tmpNode._action) - tmpNode = tmpNode._parent - finalActionList = list(reversed(finalActionList)) - return finalActionList # TODO change step! - - explored.append(tmpNode) - - tmpList = succesorFunction(tmpNode._state) - for newState in tmpList: - _flag = True - _flagFringe = True - _flagExplored = True - - if newState[1] is None: - continue - - # calculating priority - monster = 0 - if any([thing.isCreature for thing in self.model.grid.get_cell_list_contents([(newState[1].get_x(), newState[1].get_y())])]): - if newState[0] == 0: - monster = 10 - p = self.heuristics(newState[1], goalState) + tmpNode._cost + monster + 1 - - r = 0 - counter = 0 - pos = 0 - for fringeNode in fringe: - if fringeNode[1]._state.get_x() == newState[1].get_x() and fringeNode[1]._state.get_y() == newState[1].get_y() and fringeNode[1]._state.get_direction() == newState[1].get_direction(): - _flagFringe = False - _flag = False - r = fringeNode[0] - pos = counter - counter = counter + 1 - - for exploredNode in explored: - if exploredNode._state.get_x() == newState[1].get_x() and exploredNode._state.get_y() == newState[1].get_y() and exploredNode._state.get_direction() == newState[1].get_direction(): - _flagExplored = False - _flag = False - - # if _flag: - # newState[1].set_predecessor(tmpNode) - - if _flagFringe and _flagExplored: - newNode = Node(tmpNode, newState, tmpNode._cost + 1 + monster) - heapq.heappush(fringe, (p, newNode)) - elif not _flagFringe and (p < r): - newNode = Node(tmpNode, newState, tmpNode._cost + 1 + monster) - fringe[pos][0] = p - fringe[pos][1] = newNode - - return None - - def step(self): - if self.health > 0: - print("position: ", self.pos) - # print("direction: ", self.direction) - if not self.hasgoalchest: # jeśli nie ma wyznaczonej skrzynki do której idzie to robi bfs żeby ją wyznaczyć - # self.path=self.findShortestPathToTarget() - if len(self.__listOfChests) != 0: - # select and remove element from list - randomChest = random.choice(self.__listOfChests) - self.__listOfChests.remove(randomChest) - self.hasgoalchest = True - - currentState = AgentState(self.pos[0], self.pos[1], self.direction) - - goalState = AgentState(randomChest[1][0], randomChest[1][1], self.direction) - # find way to goal state - self.__actionsCollection = self.graphsearch([], - [], - currentState, - self.successor, - goalState) - - if self.__actionsCollection is None: - raise Exception("CRITICAL ERROR - Algorithm error - Path doesn't exist!!! ://") - - else: - self.__actionsCollection = [action for action in self.__actionsCollection if action is not None] # remove first None action - else: - raise Exception("WIN!!! :D") - - elif len(self.__actionsCollection) == 0: # jeśli jest wyznaczona skrzynka - cel & nie ma akcji do wykonania - cel osiągnięty - self.hasgoalchest = False - - elif len(self.__actionsCollection) != 0: # jeśli jest wyznaczona skrzynka - cel & są akcje do wykoannia to je realizuje - - actionIndex = self.__actionsCollection[0] # ignore -1 because it's None - self.__actionsCollection.remove(actionIndex) - - newState = actionsInterpreter(actionIndex, AgentState(self.pos[0], self.pos[1], self.direction), self.directions) - - self.model.grid.move_agent(self, (newState.get_x(), newState.get_y())) - self.direction = newState.get_direction() - - print("moved to - ", [newState.get_x(), newState.get_y()]) - - cellmates = self.model.grid.get_cell_list_contents([self.pos]) - if len(cellmates) > 1: - if isinstance(cellmates[0], Box): - self.openChest(cellmates[0]) - else: - opponent = cellmates[0] - print("Fighting") - self.fightOrFlight(opponent) - # print("HP: " + str(self.health) + " / " + str(self.maxHealth)) - print("Gold: " + str(self.gold)) - else: - print("HP: 0 / " + str(self.maxHealth)) diff --git a/othercharacters.py b/othercharacters.py deleted file mode 100644 index b558ec1..0000000 --- a/othercharacters.py +++ /dev/null @@ -1,86 +0,0 @@ -from mesa import Agent -import random - - -def dice(number): - return random.randint(1, number) - - - -class Wall(Agent): - def __init__(self, unique_id, model): - super().__init__(unique_id, model) - - def step(self): - pass - - -class Box(Agent): - def __init__(self, unique_id, model): - super().__init__(unique_id, model) - self.gold = 3 * dice(6) - self.isBox = True - self.isCreature = False - - def step(self): - pass - - -class Weapon(): - def __init__(self, name, type, damage): - self.name = name - self.type = type - self.damage = damage - - -class Armor(): - def __init__(self, name, defence, mp): - self.name = name - self.defence = defence - self.mag_protection = mp - - -class Creature(Agent): - def __init__(self, unique_id, model, n, s, a, w, maxhp, hp, weap, arm, g): - super().__init__(unique_id, model) - self.name = n - self.strength = s - self.agility = a - self.wisdom = w - self.maxHealth = maxhp - self.health = hp - self.gold = g - self.weapon1 = weap - self.armor = arm - self.isBox = False - self.isCreature = True - - def meleeAttack(self, opponent): - attackValue = self.strength + dice(6) - defenseValue = opponent.strength + opponent.armor.defence - damage = attackValue - defenseValue - if damage > 0: - opponent.health = opponent.health - (damage + self.weapon1.damage) - - def rangeAttack(self, opponent): - attackValue = self.agility + dice(6) - defenseValue = opponent.agility - damage = attackValue - defenseValue - if (damage > 0) and (damage + self.weapon1.damage - opponent.armor.defence > 0): - opponent.health = opponent.health - (damage + self.weapon1.damage - opponent.armor.defence) - - def magicAttack(self, opponent): - attackValue = self.wisdom + dice(6) - defenseValue = opponent.wisdom - damage = attackValue - defenseValue - if (damage > 0) and (damage + self.weapon1.damage - opponent.armor.mag_protection > 0): - opponent.health = opponent.health - (damage + self.weapon1.damage - opponent.armor.mag_protection) - - def defaultAttack(self, opponent): - if self.weapon1.type == "Meele": - self.meleeAttack(opponent) - elif self.weapon1.type == "Range": - self.rangeAttack(opponent) - else: - self.magicAttack(opponent) - diff --git a/server.py b/server.py index 1d0b90d..ae17886 100644 --- a/server.py +++ b/server.py @@ -1,4 +1,4 @@ -from model import GameMap +from src.agent.map.gameMap import GameMap from mesa.visualization.modules import CanvasGrid from mesa.visualization.ModularVisualization import ModularServer @@ -10,13 +10,14 @@ def player_representation(agent): portrayal["Shape"] = "sprites/box.png" portrayal["Layer"] = 0 elif agent.isCreature: - portrayal["Shape"]='sprites/goblin.png' + portrayal["Shape"] = 'sprites/goblin.png' return portrayal + grid = CanvasGrid(player_representation, 10, 10, 500, 500) server = ModularServer(GameMap, [grid], "Map", - {"x":10, "y":10}) + {"x": 10, "y": 10}) server.port = 8081 -server.launch() \ No newline at end of file +server.launch() diff --git a/src/__init__.py b/src/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/__pycache__/__init__.cpython-39.pyc b/src/__pycache__/__init__.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ab9b423735549199380da5ee1c394003ab39e3f GIT binary patch literal 142 zcmYe~<>g`kf@YQe1Q7igL?8o3AjbiSi&=m~3PUi1CZpdI z6P}rul3!k|U}zBIl3JWyl3x&0RFJM)T$LG9T$CIWAD@|*SrQ+wS5SG2!zMRBr8Fni L4rJJ8AZ7pn+wCAj literal 0 HcmV?d00001 diff --git a/src/__pycache__/direction.cpython-39.pyc b/src/__pycache__/direction.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..923230ddd275e7bc82b763129a03f6ebcc75d4c9 GIT binary patch literal 711 zcma)4!D`z;5S`JkW65>WghE;{y2)0JEEox-R-L(=Ll2g)i zzr(+@*Pi?fJ#|KITsNnVn5UiD(d>J(8gFj)fbIMCkB=`9;HL!Zra3rb_j?Qkge6Qc zMTGZ25ve;MW${*}5$O>OIt#9X0S0|qHIrO|b&EJSV)ri@ETl-lA7ZK~N;RppLpt4{ z4sF~)+NCbV{EjK%#=Vf76wcYZMm*E<|F!QI(co%MP zhSzwDBbck96L|}Pc@#Pq-_w(@K(m`vH$=8 literal 0 HcmV?d00001 diff --git a/src/agent/__init__.py b/src/agent/__init__.py new file mode 100644 index 0000000..dbf109d --- /dev/null +++ b/src/agent/__init__.py @@ -0,0 +1,4 @@ +from .hero import Player +from .map.gameMap import GameMap +from .model import * +from .state import AgentState diff --git a/src/agent/__pycache__/__init__.cpython-39.pyc b/src/agent/__pycache__/__init__.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b489ef82e10a49df341deda85072bd65621dd3c7 GIT binary patch literal 248 zcmYe~<>g`kf_*Ce2|+;mF^GcG@s%+i@JH4H01iUjIZ8vRGE^bvCgSZ6ez!QEQ>yo~oUn?dcv@ z_hju+FG8%PNL+v$LL7Dv94v9k_QsJA2YS@6>%IDY zuU>ui-h|C&jp6zHwV&U;{&mLwO3eIYfq4gSdIv->!6W9=*NFHX`kIk3G<}m(*@~>8 z?c2I+N6xU~S9IBl++o$Pa`qk*72!T&!j-jc)2|DDo3*P?FfvnAao!`F1_W}HbiQW6wG^ZLr|4vjGXm{TVG00qf>E|_n8#@4yu!g%ER zrZ9!|i20VVg@dnMuFH2sRn)*&L|ruSbwyLO@U4EvEaum++J(aTC<-4+)mfOEkjhQG zG;jJVkc@4!9iH>t$j#i!?cB*Lxtmw>T3+9+a|S634Aii|L@f&}v|xdaRxEJPk_DB# z4oZDkP|X{lwY&*h#~3VV2oBoRw3RIk4uLz|WuQm2?5HqMK9;vYk8Ak}!LWXFbwzP3 zuzj+y)A2~E!VQ9c+|Pobu;Oqi3pdS_jJsK{sD#~q)XyFk&SpOq$*`yn!w2unFhZTv zE5BAZi9}J^l;J3eFU<;V;|0O~NSX^kkY9&158FDM~IajtAuy1VPkKvk%vosZm;--V=w~PtxTiil)x9 zP*|yq*8S=@?qiOiFA95@2pJVTE_hn-u;81%1O0;D$T#phrAoeu^%uPB8=IH$zUjAU z&LCNzF6J?OGzdCTn5IGSnEmTJ%S&rNNTo{GKJLdN*-X7l7uRmcbR$bfYiiUzpHBK~ zsp_nS8hF!hf-vrJ=Y>CauV%7P+F^0FgB^oK)Xej2`yDImu3;Wnhv2JT_OKI2fz+ zp^B=bTr?F79b`Qjh<-<^V>1iukxS=iYK zJ`JO>^qab8Doa*uZnm7dpD zg>iSLZ5s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l-`S-R#J7?e49o lrL($wIWnztP63@6kOGB!rQGPNbeZT|$AwvGn;J&L{14@+I=}z` literal 0 HcmV?d00001 diff --git a/src/agent/hero.py b/src/agent/hero.py new file mode 100644 index 0000000..06f052d --- /dev/null +++ b/src/agent/hero.py @@ -0,0 +1,199 @@ +import random + +from src.agent.model import * +from src.agent.state import AgentState +from src.direction import Direction +from src.treesearch.actionsInterpreter import ActionInterpreter + +from src.treesearch.bfs import BFS + + +class Player(Creature): + def __init__(self, unique_id, model, n, s, a, w, max_hp, hp, weapon, arm, g, w2, w3, list_of_chests): + super().__init__(unique_id, model, n, s, a, w, max_hp, hp, weapon, arm, g) + self.name = n + self.strength = s + self.agility = a + self.wisdom = w + self.maxHealth = max_hp + self.health = hp + self.gold = g + self.weapon1 = weapon + self.weapon2 = w2 + self.weapon3 = w3 + self.armor = arm + self.isBox = False + self.isCreature = False + self.direction = Direction.N + self.queue = [] + self.has_goal_chest = False + self.opened_chests = 0 + self.__listOfChests = list_of_chests + self.__actionsCollection = [] + + def melee_attack(self, opponent): + attack_value = self.strength + roll_the_dice(6) + defense_value = opponent.strength + opponent.armor.defence + damage = attack_value - defense_value + if damage > 0: + opponent.health = opponent.health - (damage + self.weapon1.damage) + + def range_attack(self, opponent): + attack_value = self.agility + roll_the_dice(6) + defense_value = opponent.agility + damage = attack_value - defense_value + if (damage > 0) and (damage + self.weapon2.damage - opponent.armor.defence > 0): + opponent.health = opponent.health - (damage + self.weapon2.damage - opponent.armor.defence) + + def magic_attack(self, opponent): + attack_value = self.wisdom + roll_the_dice(6) + defense_value = opponent.wisdom + damage = attack_value - defense_value + if (damage > 0) and (damage + self.weapon3.damage - opponent.armor.mag_protection > 0): + opponent.health = opponent.health - (damage + self.weapon3.damage - opponent.armor.mag_protection) + + def fight_or_flight(self, opponent): + combat = True + while combat: + choice = roll_the_dice(4) + print("roll_the_dice rolled:", choice) + if choice == 1: + running_speed = self.agility + roll_the_dice(6) + opponent_speed = opponent.agility + roll_the_dice(6) + if running_speed > opponent_speed: + combat = False + print("Player ran away") + self.step() + else: + opponent.default_attack(self) + if self.health <= 0: + combat = False + print("Player died :/") + elif choice == 2: + self.melee_attack(opponent) + if opponent.health > 0: + opponent.default_attack(self) + if self.health <= 0: + combat = False + print("Player died :/") + else: + combat = False + self.gold = self.gold + opponent.gold + opponent.gold = 0 + opponent.model.grid.remove_agent(opponent) + print("Fight won") + elif choice == 3: + self.range_attack(opponent) + if opponent.health > 0: + opponent.default_attack(self) + if self.health <= 0: + combat = False + print("Player died :/") + else: + combat = False + self.gold = self.gold + opponent.gold + opponent.gold = 0 + opponent.model.grid.remove_agent(opponent) + print("Fight won") + else: + self.magic_attack(opponent) + if opponent.health > 0: + opponent.default_attack(self) + if self.health <= 0: + combat = False + print("Player died :/") + else: + combat = False + self.gold = self.gold + opponent.gold + opponent.gold = 0 + opponent.model.grid.remove_agent(opponent) + print("Fight won") + + def open_chest(self, chest): + self.gold = self.gold + chest.gold + print("------Chest opened. Gold inside:", chest.gold, "-----") + chest.gold = 0 + self.opened_chests += 1 + self.has_goal_chest = False + chest.model.grid.remove_agent(chest) + # self.direction = 0 # po osiągnięciu jednego celu 'restartuje sie' na szukanie ścieżki do kolejnego -- NIE ZEROWAĆ OBROTU - to psuje goldState w bfs!!! + # if isinstance(chest.loot,Armor): + # buffer = self.armor + # self.armor = chest.loot + # chest.loot = buffer + # if isinstance(chest.loot,Weapon): + # if chest.loot.weapon_type == "Melee": + # buffer = self.weapon1 + # self.weapon1 = chest.loot + # chest.loot = buffer + # elif chest.loot.weapon_type == "Range": + # buffer = self.weapon2 + # self.weapon2 = chest.loot + # chest.loot = buffer + # elif chest.loot.weapon_type == "Magic": + # buffer = self.weapon3 + # self.weapon3 = chest.loot + # chest.loot = buffer + + def step(self): + if self.health > 0: + print("position: ", self.pos) + # print("direction: ", self.direction) + if not self.has_goal_chest: # jeśli nie ma wyznaczonej skrzynki do której idzie to robi bfs żeby ją wyznaczyć + # self.path=self.findShortestPathToTarget() + if len(self.__listOfChests) != 0: + # select and remove element from list + random_chest = random.choice(self.__listOfChests) + self.__listOfChests.remove(random_chest) + self.has_goal_chest = True + + current_state = AgentState(self.pos[0], self.pos[1], self.direction) + + goal_state = AgentState(random_chest[1][0], random_chest[1][1], self.direction) + # find way to goal state + treesearch_module = BFS(self) + self.__actionsCollection = treesearch_module.graphsearch([], + [], + current_state, + BFS.successor, + goal_state) + + if self.__actionsCollection is None: + raise Exception("CRITICAL ERROR - Algorithm error - Path doesn't exist!!! ://") + + else: + self.__actionsCollection = [action for action in self.__actionsCollection if + action is not None] # remove first None action + else: + raise Exception("WIN!!! :D") + + elif len( + self.__actionsCollection) == 0: # jeśli jest wyznaczona skrzynka - cel & nie ma akcji do wykonania - cel osiągnięty + self.has_goal_chest = False + + elif len( + self.__actionsCollection) != 0: # jeśli jest wyznaczona skrzynka - cel & są akcje do wykoannia to je realizuje + + action_index = self.__actionsCollection[0] # ignore -1 because it's None + self.__actionsCollection.remove(action_index) + + new_state = ActionInterpreter.interpret(action_index, + AgentState(self.pos[0], self.pos[1], self.direction)) + + self.model.grid.move_agent(self, (new_state.get_x(), new_state.get_y())) + self.direction = new_state.get_direction() + + print("moved to - ", [new_state.get_x(), new_state.get_y()]) + + cellmates = self.model.grid.get_cell_list_contents([self.pos]) + if len(cellmates) > 1: + if isinstance(cellmates[0], Box): + self.open_chest(cellmates[0]) + else: + opponent = cellmates[0] + print("Fighting") + self.fight_or_flight(opponent) + # print("HP: " + str(self.health) + " / " + str(self.maxHealth)) + print("Gold: " + str(self.gold)) + else: + print("HP: 0 / " + str(self.maxHealth)) diff --git a/src/agent/map/__pycache__/gameMap.cpython-39.pyc b/src/agent/map/__pycache__/gameMap.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b3c5160616a82e82f1f04e2cf3356f209af5bd7c GIT binary patch literal 1985 zcmb7E&2Aev5MJ(|R?Se`GGz z*oJ&k?#%=EVE2}n=!5LFm+BRIX}?)ZN$RABE-}N8Lvm&~K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@A5@w6Y0p4e<;BbVfk*jOtnAb5a$C?=4a$u+A zaCQ6`^vi_UvMe){Hcp2Y0XF@yV))5A1MpOQ02Mfc_5c6? literal 0 HcmV?d00001 diff --git a/src/agent/model/__pycache__/weapon.cpython-39.pyc b/src/agent/model/__pycache__/weapon.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb4e9e852dbbbd9e7d631820b7c835252bd3665b GIT binary patch literal 885 zcmb7C!A{#i5S_IhXA^J{AaU;1Qj6e<+A0#2xaEQn!m_kjnQfFdam=m}3i1u49{G;^ z(q8!lZk(902}x0UV61sNvokwycg9&1b%EsX?!)DU0C;3)ReW-Kq;`kk1Q1Z%liqm= zpmz$fKcM}8#3QdqYQGR@NCZOSp+N5*5+8jGXbrH1A+0TJqog&&4%OSF zW{^_#yi6xk)Z?_Nv|r4eRBDuuN~QQgHY5NM(s#SnTzh{JAJ8n`gl*Qk1AM50-}GX` zMPgxiL~~&{P+ziv4!KSaby;_!O`hd^SaL05AK~I*m<DRk`ngU1H9dq(q!~26Xo=D*ZPi(YE literal 0 HcmV?d00001 diff --git a/src/agent/model/armor.py b/src/agent/model/armor.py new file mode 100644 index 0000000..09d8995 --- /dev/null +++ b/src/agent/model/armor.py @@ -0,0 +1,21 @@ +class Armor: + def __init__(self, name, defence, mp): + self.__name = name + self.__defence = defence + self.__mag_protection = mp + + def get_name(self): + return self.__name + + def get_defence(self): + return self.__defence + + def set_defence(self, new_defence): + self.__defence = new_defence + + def get_mag_protection(self): + return self.__mag_protection + + def set_mag_protection(self, new_mag_protection): + self.__mag_protection = new_mag_protection + diff --git a/src/agent/model/box.py b/src/agent/model/box.py new file mode 100644 index 0000000..d8709f9 --- /dev/null +++ b/src/agent/model/box.py @@ -0,0 +1,13 @@ +from mesa import Agent +from .dice.dice import roll_the_dice + + +class Box(Agent): + def __init__(self, unique_id, model): + super().__init__(unique_id, model) + self.gold = 3 * roll_the_dice(6) + self.isBox = True + self.isCreature = False + + def step(self): + pass diff --git a/src/agent/model/creature.py b/src/agent/model/creature.py new file mode 100644 index 0000000..0c1309b --- /dev/null +++ b/src/agent/model/creature.py @@ -0,0 +1,47 @@ +from mesa import Agent +from .dice.dice import roll_the_dice + + +class Creature(Agent): + def __init__(self, unique_id, model, name, strength, agility, wisdom, max_hp, hp, weapon, armor, gold): + super().__init__(unique_id, model) + self.name = name + self.strength = strength + self.agility = agility + self.wisdom = wisdom + self.maxHealth = max_hp + self.health = hp + self.gold = gold + self.weapon1 = weapon + self.armor = armor + self.isBox = False + self.isCreature = True + + def melee_attack(self, opponent): + attack_value = self.strength + roll_the_dice(6) + defense_value = opponent.strength + opponent.armor.defence + damage = attack_value - defense_value + if damage > 0: + opponent.health = opponent.health - (damage + self.weapon1.damage) + + def range_attack(self, opponent): + attack_value = self.agility + roll_the_dice(6) + defense_value = opponent.agility + damage = attack_value - defense_value + if (damage > 0) and (damage + self.weapon1.damage - opponent.armor.defence > 0): + opponent.health = opponent.health - (damage + self.weapon1.damage - opponent.armor.defence) + + def magic_attack(self, opponent): + attack_value = self.wisdom + roll_the_dice(6) + defense_value = opponent.wisdom + damage = attack_value - defense_value + if (damage > 0) and (damage + self.weapon1.damage - opponent.armor.mag_protection > 0): + opponent.health = opponent.health - (damage + self.weapon1.damage - opponent.armor.mag_protection) + + def default_attack(self, opponent): + if self.weapon1.type == "Meele": + self.melee_attack(opponent) + elif self.weapon1.type == "Range": + self.range_attack(opponent) + else: + self.magic_attack(opponent) diff --git a/src/agent/model/dice/__init__.py b/src/agent/model/dice/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/agent/model/dice/__pycache__/dice.cpython-39.pyc b/src/agent/model/dice/__pycache__/dice.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c27cfddef83043345a926285dcb4c06f9eed86aa GIT binary patch literal 310 zcmYjMJxc>Y5S`tNmmppv{s7x6610^N0g`kf-}nf3F$!kF^GcWHa^HWN5Qtg<4CKj^+2_{A${0jgB5ky@8 literal 0 HcmV?d00001 diff --git a/src/dictionary/actions.py b/src/dictionary/actions.py new file mode 100644 index 0000000..5fc1ee4 --- /dev/null +++ b/src/dictionary/actions.py @@ -0,0 +1,5 @@ +actions = { + "rotate_left": -1, + "move_forward": 0, + "rotate_right": 1 + } diff --git a/src/dictionary/directions.py b/src/dictionary/directions.py new file mode 100644 index 0000000..1483cbd --- /dev/null +++ b/src/dictionary/directions.py @@ -0,0 +1,8 @@ +from src.direction import Direction + +directions = { + Direction.N: [0, 1], + Direction.E: [1, 0], + Direction.S: [0, -1], + Direction.W: [-1, 0] + } diff --git a/direction.py b/src/direction.py similarity index 52% rename from direction.py rename to src/direction.py index 67d353e..69bf510 100644 --- a/direction.py +++ b/src/direction.py @@ -1,5 +1,6 @@ from enum import Enum + class Direction(Enum): N = 0 E = 1 @@ -7,9 +8,9 @@ class Direction(Enum): W = 3 def clockwise(self): - v = (self.value+1)%4 + v = (self.value + 1) % 4 return Direction(v) - def counterClockwise(self): - v = (self.value-1)%4 - return Direction(v) \ No newline at end of file + def counter_clockwise(self): + v = (self.value - 1) % 4 + return Direction(v) diff --git a/src/items/__pycache__/armory.cpython-39.pyc b/src/items/__pycache__/armory.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed818b76679ae8dccde49d869074e681390f61b9 GIT binary patch literal 1301 zcmZvb%Wl&^6o&0MPLnk0{eBHlE`c`0y`(Kd2)7lhwyGSVNTV#6c1DhcV@I~D(rkGE zo`aX*LA+&^CqQDwe+-Kes-yGk^FQazv5zObS}kk1er$dF^sA(4Kj}uj^0;}Ah_`c^ zCN!b@T3=_nPMq^|eS;agCUs$myfD8SEU&PsZ~A+1Bc{5uKyDo)$Wi55fRs z+EG7@m~kGu%)F4klp`HEtZ>F%S4PZi--VGF;iPHIu)oNW0UDN1c#`LO^+2nc#*v3zCS9^MkTt9 zlQ8O!=wFcLFT+3%tLKs@JsH)qryZ70d)y0Z7u@rQ<5xaUFOO`ls>X{oCm|1t*G!&_hNi?L(|+Q z@d^-7oYMU4C4k;OjQyPcUl|^)c4(SC5(*N5ka#H2JB7qY9|O_>b}%H}!7fImL+oKp zx{G}rkdAPO8>D+UB8<%@n3SmUfDUwnZARLqX&#ZN{Td|HgmfRs5@dPS@@heAAA#9U z&L|YlC{q{*O-JUXshY0L@@iTZO(;#3Rf>MhGp&k>LIR^^@0ze(Cw=Re)nYzVNx++z zpt*p*p6xzQUmK-O`es^S`O!Rl`Xt>`=CCT~sh%G^HYd~6=sc~oQfWcyY|lS6k(AS7 zT1m;Nn1}?3P{j0|3_0a(=g*n38*KBmxrb!b@PV>hipf}LF3eJBKFcy|MW2>Ubf7Am zF*^-Ig2Qp1o8agnZ6u@)DZRmhE3kqS^J#5K8P_3=Y(|&9|H0xcuf^)|dG=PAiG$j> zfU>R|BT?bH|3Vru(p)QQL}g5=Z>`{MUEr+*J2F>kY|%cKc1vR|;4d1!qrny9)~Ur;@eK|g6=K0nq(>yq88w}GfkV@qY;j@r9TuFM pzRTjW!>q+^rQI_yoJS<0F!J4Jef%0Y=DN*I^r9v6k|Tc7gg=$v_o@H@ literal 0 HcmV?d00001 diff --git a/node.py b/src/tree/node.py similarity index 64% rename from node.py rename to src/tree/node.py index 77f60ab..a4a4e49 100644 --- a/node.py +++ b/src/tree/node.py @@ -5,6 +5,15 @@ class Node: self._state = state_tuple[1] self._parent = parent + def get_cost(self): + return self._cost + + def get_action(self): + return self._action + + def get_state(self): + return self._state + def get_predecessor(self): return self._parent @@ -12,4 +21,4 @@ class Node: self._parent = predecessor def __lt__(self, other): - return self._cost < other._cost + return self._cost < other.get_cost() diff --git a/src/treesearch/__init__.py b/src/treesearch/__init__.py new file mode 100644 index 0000000..a58caa9 --- /dev/null +++ b/src/treesearch/__init__.py @@ -0,0 +1,3 @@ +from .bfs import BFS +from .actionsInterpreter import ActionInterpreter +from .heuristic import * diff --git a/src/treesearch/__pycache__/actionsInterpreter.cpython-39.pyc b/src/treesearch/__pycache__/actionsInterpreter.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e087dbd3ac1d56db0fb5fd641b977e5e2b8035e0 GIT binary patch literal 957 zcmZWn&2G~`5Z)i#bxeYkawrlK;((BXLGW@(M@@W}U=XVyzv|d^7&$&vB;{AUJRLzP!KhBJ|T5%|pR>30FM^ z!4bz9%5jLX)k#Kj8d8j2BTl(Uk@OM?GwU{jn(YNXJ@$)jCY2NOW2j ziS;*6o#`&10)?2PkO;~#C)a3!ftLcWW4im*_iqX<+phF|*0IvE0;u4BJ zCGw$0m-q%Rtt6GCOLXHb(E?~8hCs|$POb=C3Nhf-?ne*MBTlbqF{rT}z#_m%@u9k%Hv<5NOpnj*U`ZsdI!uZI)=~6bM@fa)96sBQ(aCXIT=4u z7ipwq5@{)f60uB9qIDY8*k*q+H?4HL-5nrS0}zP#m|zc{;J4%Y*uf6D4c5Qw5P}1E zyvkq4dKdTp`(yew|FGv8pRpp&1!E>)EHC*qvwEAcvuT`dJZ;-~n&d*Clw96{da9lq zV%K8ZzfW1khk`1^CTT(A{c3#cb#<&=FR0o^729C6LzR}+_|Mm6y|4?fxZAi*{{oEF B^KAeC literal 0 HcmV?d00001 diff --git a/src/treesearch/__pycache__/bfs.cpython-39.pyc b/src/treesearch/__pycache__/bfs.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b25d81929b7250fda6149bbc24d42657a5a53116 GIT binary patch literal 2863 zcmZ`*OOM;g5$&N%4GhHCSceQYmjE^f#wPYUKn`=6O$-oYFbtb|%uuA% zq-@WC3IdD|IVIkIFaq|Hd#=f0f57~JzUE{ff&jS%Fr2TNl031!6slFPuBz^?uIjkk z^%=gO-1*Dz{(haYe-d%^vp{?WD1VDVGRZR*(!a>~ScHNTZe`Zk4sCT`iO02A#lBo(XK1z*r8%xEpxg}q?s)|`J*<`@~a zYHk5+%)^YzJ#L){^^FvBJHNl?dEgDfv+^(2yf%2Xw4k@M=K0|L89WOdip9E#JUVgI zzpv2t2{SZBX$rUI-lX31_GE1%rRICm>7tGMF)ML zXxmKNV>KE#HtfUT>A~hNet6rce!L&0-tLR1ZcdENY z$yJ`}?WCCHRjQ&SE0UAvqcYX)HL7fy&kr>JTJuBApC~%po~zw>GD&l(wn3_Eq~w}7 zUM&Al)ecE0ubP1pL$}LWlB8u>s7;XN0}RX(+{Mp-YrF3;o7-Xo-1lIMuejhoe(qb> zwJpN@w`X0-v9;BN5^MF{1mXcql6{Z32W;+29P2>LTNSQG-I5%~;Z^)X)Lin~>x%_S zMP=3e9Q29xN~nJzaoTH+P`{Qq7|gJ1zTndSjLrSpzd$-(xJU_yMx@c-mb{kXVO;XO z1^mvq`mS~_+R*VAY{5AL2Fcu?{;}#*LG7Ny|J<$JL!<)f86CT^2}!5!JYui-(>L>g zq62gR8+AbOz&=y|nqJ~sY*yW-Zq)2}<9PFU>tegnF|iu$3&hqJ1FYo{>dZNR#npZ2 zaMyC+J=M|q0Yk>%k<~QmaKj8h%Qu49q zmE>cuZ{Tr*yu!nqx{JK{L%l&GuDV|b&7M#Uv@6J|-6p5%t$Me~sp)0iEiXZDqkvrg z&@9M#eU0{hpVhld+}>x?%jsQH%9jPDDyyUzPagDP@IL@{_G7wn0~Jq( zO$*rDN8O0C@&S;Qw%USb?}nlpubp8UPo~rd+7ciR%-$X}#JeXWCQgGc>GJYAeo96RpwDa`&(p1N2J#GT& z8sh6!G_5gS9@s6-Cz`9UwXEOTniOT|H^I}(BMepxFqB8u$>WEo+_`d?_pkxwpD-{K zV2=l43uV|A0hQy702(x7#Q$UxTKPhK5Ivr#*8HbUVVEq&G}w3OP1P_SR2D blcC1_r=r!~ezWce^fV}G0Ul0d`Lq59)*IjU literal 0 HcmV?d00001 diff --git a/src/treesearch/actionsInterpreter.py b/src/treesearch/actionsInterpreter.py new file mode 100644 index 0000000..20b1af9 --- /dev/null +++ b/src/treesearch/actionsInterpreter.py @@ -0,0 +1,40 @@ +from src.agent.state import AgentState +from src.direction import Direction + + +class ActionInterpreter: + + @staticmethod + def interpret(action_index, default_state): + if action_index == -1: + return AgentState( + default_state.get_x(), + default_state.get_y(), + default_state.get_direction().counter_clockwise() + ) + elif action_index == 0: + move_x = 0 + move_y = 0 + + if default_state.get_direction() == Direction.N: + move_y = 1 + elif default_state.get_direction() == Direction.E: + move_x = 1 + elif default_state.get_direction() == Direction.S: + move_y = -1 + elif default_state.get_direction() == Direction.W: + move_x = -1 + + return AgentState( + default_state.get_x() + move_x, + default_state.get_y() + move_y, + default_state.get_direction() + ) + elif action_index == 1: + return AgentState( + default_state.get_x(), + default_state.get_y(), + default_state.get_direction().clockwise() + ) + else: + return default_state diff --git a/src/treesearch/bfs.py b/src/treesearch/bfs.py new file mode 100644 index 0000000..fdf930b --- /dev/null +++ b/src/treesearch/bfs.py @@ -0,0 +1,140 @@ +import heapq + +from src.dictionary.actions import actions +from src.agent.state import AgentState +from src.direction import Direction +from src.tree.node import Node +from src.treesearch.heuristic.manhattan import manhattan + + +class BFS: + + def __init__(self, agent): + self.__agent = agent + + @staticmethod + def successor(append): + + rotate_left = AgentState( + append.get_x(), + append.get_y(), + append.get_direction().counter_clockwise() + ) + + rotate_right = AgentState( + append.get_x(), + append.get_y(), + append.get_direction().clockwise() + ) + + move_x = 0 + move_y = 0 + + if append.get_direction() == Direction.N: + move_y = 1 + elif append.get_direction() == Direction.E: + move_x = 1 + elif append.get_direction() == Direction.S: + move_y = -1 + elif append.get_direction() == Direction.W: + move_x = -1 + + if append.get_x() + move_x >= 0 and append.get_x() + move_x < 10 and append.get_y() + move_y >= 0 and append.get_y() + move_y < 10: + move_forward = AgentState( + append.get_x() + move_x, + append.get_y() + move_y, + append.get_direction() + ) + else: + move_forward = None + + return [ + [actions["rotate_left"], rotate_left], + [actions["move_forward"], move_forward], + [actions["rotate_right"], rotate_right] + ] + + def graphsearch(self, fringe, explored, istate, succesor_function, goal_state): + final_action_list = [] + + init_state = [None, istate] + root = Node(None, init_state, 0) + + heapq.heappush(fringe, (0, root)) # at beginning do nothing + + while len(fringe) != 0: + _flag = True + + if len(fringe) == 0: + return False + + tmp_node = (heapq.heappop(fringe))[1] # node + + # build dictionary + # parent = tmp_node.get_predecessor() # fetch parent state + # tmp_node.set_predecessor(None) # clear predecessor - don't build a tree chain + # if parent is None: + # final_action_list.append([parent, tmp_node]) + # else: + # final_action_list.append( + # [parent[1], tmp_node]) # pair(key, value) - key: parent state, value: current state + action + + if tmp_node.get_state().get_x() == goal_state.get_x() and tmp_node.get_state().get_y() == goal_state.get_y(): + while tmp_node.get_predecessor() is not None: + final_action_list.append(tmp_node.get_action()) + tmp_node = tmp_node.get_predecessor() + final_action_list = list(reversed(final_action_list)) + return final_action_list # TODO change step! + + explored.append(tmp_node) + + tmp_list = succesor_function(tmp_node.get_state()) + for new_state in tmp_list: + _flag = True + _flagFringe = True + _flagExplored = True + + if new_state[1] is None: + continue + + # calculating priority + monster = 0 + if any([thing.isCreature for thing in + self.__agent.model.grid.get_cell_list_contents( + [(new_state[1].get_x(), new_state[1].get_y())])]): + if new_state[0] == 0: + monster = 10 + p = manhattan(new_state[1], goal_state) + tmp_node.get_cost() + monster + 1 + + r = 0 + counter = 0 + pos = 0 + for fringeNode in fringe: + if fringeNode[1].get_state().get_x() == new_state[1].get_x() and fringeNode[ + 1].get_state().get_y() == new_state[1].get_y() and fringeNode[1].get_state().get_direction() == \ + new_state[1].get_direction(): + _flagFringe = False + _flag = False + r = fringeNode[0] + pos = counter + counter = counter + 1 + + for exploredNode in explored: + if exploredNode.get_state().get_x() == new_state[1].get_x() and exploredNode.get_state().get_y() == \ + new_state[1].get_y() and exploredNode.get_state().get_direction() == new_state[ + 1].get_direction(): + _flagExplored = False + _flag = False + + # if _flag: + # new_state[1].set_predecessor(tmp_node) + + if _flagFringe and _flagExplored: + new_node = Node(tmp_node, new_state, tmp_node.get_cost() + 1 + monster) + heapq.heappush(fringe, (p, new_node)) + elif not _flagFringe and (p < r): + new_node = Node(tmp_node, new_state, tmp_node.get_cost() + 1 + monster) + fringe[pos][0] = p + fringe[pos][1] = new_node + + return None diff --git a/src/treesearch/heuristic/__init__.py b/src/treesearch/heuristic/__init__.py new file mode 100644 index 0000000..1e52a18 --- /dev/null +++ b/src/treesearch/heuristic/__init__.py @@ -0,0 +1 @@ +from .manhattan import manhattan \ No newline at end of file diff --git a/src/treesearch/heuristic/manhattan.py b/src/treesearch/heuristic/manhattan.py new file mode 100644 index 0000000..a3944ba --- /dev/null +++ b/src/treesearch/heuristic/manhattan.py @@ -0,0 +1,4 @@ +# cost is initially step distance in manhattan metric + +def manhattan(state, target_state): + return abs(state.get_x() - target_state.get_x()) + abs(state.get_y() - target_state.get_y())