mirror of
https://github.com/illiumst/marl-factory-grid.git
synced 2025-09-15 23:37:14 +02:00
WIP: removing tiles
This commit is contained in:
@@ -40,11 +40,11 @@ class Move(Action, abc.ABC):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
def do(self, entity, env):
|
||||
def do(self, entity, state):
|
||||
new_pos = self._calc_new_pos(entity.pos)
|
||||
if next_tile := env[c.FLOOR].by_pos(new_pos):
|
||||
if state.check_move_validity(entity, new_pos): # next_tile := state[c.FLOOR].by_pos(new_pos):
|
||||
# noinspection PyUnresolvedReferences
|
||||
valid = entity.move(next_tile)
|
||||
valid = entity.move(new_pos, state)
|
||||
else:
|
||||
valid = c.NOT_VALID
|
||||
reward = r.MOVEMENTS_VALID if valid else r.MOVEMENTS_FAIL
|
||||
|
@@ -31,7 +31,7 @@ class Entity(EnvObject, abc.ABC):
|
||||
|
||||
@property
|
||||
def tile(self):
|
||||
return self._tile # wall_n_floors funktionalität
|
||||
return self._tile # wall_n_floors funktionalität
|
||||
|
||||
# @property
|
||||
# def last_tile(self):
|
||||
@@ -48,12 +48,11 @@ class Entity(EnvObject, abc.ABC):
|
||||
curr_x, curr_y = self.pos
|
||||
return last_x - curr_x, last_y - curr_y
|
||||
|
||||
def move(self, next_pos):
|
||||
def move(self, next_pos, state):
|
||||
next_pos = next_pos
|
||||
curr_pos = self._pos
|
||||
if not_same_pos := curr_pos != next_pos:
|
||||
if valid := next_tile.enter(self): # muss abgefragt werden über observer? alle obs? wie sonst posdict
|
||||
# curr_tile.leave(self) kann raus wegen notify change pos
|
||||
if valid := state.check_move_validity(self, next_pos):
|
||||
self._pos = next_pos
|
||||
self._last_pos = curr_pos
|
||||
for observer in self.observers:
|
||||
@@ -66,7 +65,6 @@ class Entity(EnvObject, abc.ABC):
|
||||
self._status = None
|
||||
self._pos = position
|
||||
self._last_pos = c.VALUE_NO_POS
|
||||
# tile.enter(self)
|
||||
|
||||
def summarize_state(self) -> dict: # tile=str(self.tile.name)
|
||||
return dict(name=str(self.name), x=int(self.x), y=int(self.y), can_collide=bool(self.var_can_collide))
|
||||
|
@@ -45,9 +45,9 @@ class Floor(EnvObject):
|
||||
def encoding(self):
|
||||
return c.VALUE_OCCUPIED_CELL
|
||||
|
||||
@property
|
||||
def guests_that_can_collide(self):
|
||||
return [x for x in self.guests if x.var_can_collide]
|
||||
# @property
|
||||
# def guests_that_can_collide(self):
|
||||
# return [x for x in self.guests if x.var_can_collide]
|
||||
|
||||
@property
|
||||
def guests(self):
|
||||
|
@@ -64,7 +64,8 @@ class Factory(gym.Env):
|
||||
self.map: LevelParser
|
||||
self.obs_builder: OBSBuilder
|
||||
|
||||
# TODO: Reset ---> document this
|
||||
# reset env to initial state, preparing env for new episode.
|
||||
# returns tuple where the first dict contains initial observation for each agent in the env
|
||||
self.reset()
|
||||
|
||||
def __getitem__(self, item):
|
||||
@@ -80,22 +81,22 @@ class Factory(gym.Env):
|
||||
|
||||
self.state = None
|
||||
|
||||
# Init entity:
|
||||
entities = self.map.do_init() # done
|
||||
# Init entities
|
||||
entities = self.map.do_init()
|
||||
|
||||
# Grab all )rules:
|
||||
# Init rules
|
||||
rules = self.conf.load_rules()
|
||||
|
||||
# Agents
|
||||
# Init agents
|
||||
# noinspection PyAttributeOutsideInit
|
||||
self.state = Gamestate(entities, rules, self.conf.env_seed) # get_all_tiles_with_collisions
|
||||
agents = self.conf.load_agents(self.map.size, self[c.FLOOR].empty_tiles) # empty_tiles -> entity(tile)
|
||||
agents = self.conf.load_agents(self.map.size, self.state.entities.floorlist)
|
||||
self.state.entities.add_item({c.AGENT: agents})
|
||||
|
||||
# All is set up, trigger additional init (after agent entity spawn etc)
|
||||
self.state.rules.do_all_init(self.state, self.map)
|
||||
|
||||
# Observations
|
||||
# Build initial observations for all agents
|
||||
# noinspection PyAttributeOutsideInit
|
||||
self.obs_builder = OBSBuilder(self.map.level_shape, self.state, self.map.pomdp_r)
|
||||
return self.obs_builder.refresh_and_build_for_all(self.state)
|
||||
@@ -165,7 +166,7 @@ class Factory(gym.Env):
|
||||
if not self._renderer: # lazy init
|
||||
from marl_factory_grid.utils.renderer import Renderer
|
||||
global Renderer
|
||||
self._renderer = Renderer(self.map.level_shape, view_radius=self.conf.pomdp_r, fps=10)
|
||||
self._renderer = Renderer(self.map.level_shape, view_radius=self.conf.pomdp_r, fps=10)
|
||||
|
||||
render_entities = self.state.entities.render()
|
||||
if self.conf.pomdp_r:
|
||||
|
@@ -23,10 +23,33 @@ class Entities(Objects):
|
||||
def names(self):
|
||||
return list(self._data.keys())
|
||||
|
||||
def __init__(self):
|
||||
@property
|
||||
def floorlist(self):
|
||||
return self._floor_positions
|
||||
|
||||
def __init__(self, floor_positions):
|
||||
self._floor_positions = floor_positions
|
||||
self.pos_dict = defaultdict(list)
|
||||
super().__init__()
|
||||
|
||||
# def all_floors(self):
|
||||
# return[key for key, val in self.pos_dict.items() if any('floor' in x.name.lower() for x in val)]
|
||||
|
||||
def guests_that_can_collide(self, pos):
|
||||
return[x for val in self.pos_dict[pos] for x in val if x.var_can_collide]
|
||||
|
||||
def empty_tiles(self):
|
||||
return[key for key in self.floorlist if not any(self.pos_dict[key])]
|
||||
|
||||
def occupied_tiles(self): # positions that are not empty
|
||||
return[key for key in self.floorlist if any(self.pos_dict[key])]
|
||||
|
||||
def is_blocked(self):
|
||||
return[key for key, val in self.pos_dict.items() if any([x.var_is_blocking_pos for x in val])]
|
||||
|
||||
def is_not_blocked(self):
|
||||
return[key for key, val in self.pos_dict.items() if not all([x.var_is_blocking_pos for x in val])]
|
||||
|
||||
def iter_entities(self):
|
||||
return iter((x for sublist in self.values() for x in sublist))
|
||||
|
||||
|
@@ -1,5 +1,7 @@
|
||||
from typing import List, Tuple
|
||||
|
||||
import numpy as np
|
||||
|
||||
from marl_factory_grid.environment import constants as c
|
||||
from marl_factory_grid.environment.entity.entity import Entity
|
||||
from marl_factory_grid.environment.entity.wall_floor import Floor
|
||||
@@ -11,30 +13,31 @@ class PositionMixin:
|
||||
var_can_collide: bool = True
|
||||
var_has_position: bool = True
|
||||
|
||||
def spawn(self, coords: List[Tuple[(int, int)]]): # runde klammern?
|
||||
def spawn(self, coords: List[Tuple[(int, int)]]):
|
||||
self.add_items([self._entity(pos) for pos in coords])
|
||||
|
||||
def render(self):
|
||||
return [y for y in [x.render() for x in self] if y is not None]
|
||||
|
||||
@classmethod
|
||||
def from_tiles(cls, tiles, *args, entity_kwargs=None, **kwargs):
|
||||
collection = cls(*args, **kwargs)
|
||||
entities = [cls._entity(tile, str_ident=i,
|
||||
**entity_kwargs if entity_kwargs is not None else {})
|
||||
for i, tile in enumerate(tiles)]
|
||||
collection.add_items(entities)
|
||||
return collection
|
||||
# @classmethod
|
||||
# def from_tiles(cls, tiles, *args, entity_kwargs=None, **kwargs):
|
||||
# collection = cls(*args, **kwargs)
|
||||
# entities = [cls._entity(tile, str_ident=i,
|
||||
# **entity_kwargs if entity_kwargs is not None else {})
|
||||
# for i, tile in enumerate(tiles)]
|
||||
# collection.add_items(entities)
|
||||
# return collection
|
||||
|
||||
@classmethod
|
||||
def from_coordinates(cls, positions: [(int, int)], tiles, *args, entity_kwargs=None, **kwargs, ):
|
||||
return cls.from_tiles([tiles.by_pos(position) for position in positions], tiles.size, *args,
|
||||
entity_kwargs=entity_kwargs,
|
||||
**kwargs)
|
||||
def from_coordinates(cls, positions: [(int, int)], *args, entity_kwargs=None, **kwargs, ):
|
||||
collection = cls(*args, **kwargs)
|
||||
collection.add_items(
|
||||
[cls._entity(tuple(pos), **entity_kwargs if entity_kwargs is not None else {}) for pos in positions])
|
||||
return collection
|
||||
|
||||
def __delitem__(self, name):
|
||||
idx, obj = next((i, obj) for i, obj in enumerate(self) if obj.name == name)
|
||||
obj.tile.leave(obj)
|
||||
obj.tile.leave(obj) # observer notify?
|
||||
super().__delitem__(name)
|
||||
|
||||
def by_pos(self, pos: (int, int)):
|
||||
|
@@ -126,17 +126,12 @@ class Objects:
|
||||
del self[item]
|
||||
|
||||
def notify_change_pos(self, entity: object):
|
||||
# print("notifychange")
|
||||
try:
|
||||
# print("lastpos")
|
||||
# print(self.pos_dict[entity.last_pos])
|
||||
self.pos_dict[entity.last_pos].remove(entity)
|
||||
except (ValueError, AttributeError):
|
||||
pass
|
||||
if entity.var_has_position:
|
||||
try:
|
||||
# print("pos")
|
||||
# print(self.pos_dict[entity.pos])
|
||||
self.pos_dict[entity.pos].append(entity)
|
||||
except (ValueError, AttributeError):
|
||||
pass
|
||||
|
@@ -1,5 +1,5 @@
|
||||
import random
|
||||
from typing import List
|
||||
from typing import List, Tuple
|
||||
|
||||
from marl_factory_grid.environment import constants as c
|
||||
from marl_factory_grid.environment.groups.env_objects import EnvObjects
|
||||
@@ -15,16 +15,12 @@ class Walls(PositionMixin, EnvObjects):
|
||||
super(Walls, self).__init__(*args, **kwargs)
|
||||
self._value = c.VALUE_OCCUPIED_CELL
|
||||
|
||||
@classmethod
|
||||
def from_coordinates(cls, argwhere_coordinates, *args, **kwargs):
|
||||
tiles = cls(*args, **kwargs)
|
||||
# noinspection PyTypeChecker
|
||||
tiles.add_items([cls._entity(pos) for pos in argwhere_coordinates])
|
||||
return tiles
|
||||
|
||||
@classmethod
|
||||
def from_tiles(cls, tiles, *args, **kwargs):
|
||||
raise RuntimeError()
|
||||
# @classmethod
|
||||
# def from_coordinates(cls, argwhere_coordinates, *args, **kwargs):
|
||||
# tiles = cls(*args, **kwargs)
|
||||
# # noinspection PyTypeChecker
|
||||
# tiles.add_items([cls._entity(pos) for pos in argwhere_coordinates])
|
||||
# return tiles
|
||||
|
||||
def by_pos(self, pos: (int, int)):
|
||||
try:
|
||||
@@ -43,17 +39,4 @@ class Floors(Walls):
|
||||
super(Floors, self).__init__(*args, **kwargs)
|
||||
self._value = c.VALUE_FREE_CELL
|
||||
|
||||
@property
|
||||
def occupied_tiles(self):
|
||||
tiles = [tile for tile in self if tile.is_occupied()]
|
||||
random.shuffle(tiles)
|
||||
return tiles
|
||||
|
||||
@property
|
||||
def empty_tiles(self) -> List[Floor]:
|
||||
# def empty_tiles(self) -> List[Tuple[int, int]]:
|
||||
tiles = [tile for tile in self if tile.is_empty()]
|
||||
# positions = [tile.pos for tile in self if tile.is_empty()]
|
||||
random.shuffle(tiles)
|
||||
return tiles
|
||||
|
||||
|
@@ -74,10 +74,10 @@ class Collision(Rule):
|
||||
|
||||
def tick_post_step(self, state) -> List[TickResult]:
|
||||
self.curr_done = False
|
||||
tiles_with_collisions = state.get_all_tiles_with_collisions()
|
||||
pos_with_collisions = state.get_all_pos_with_collisions()
|
||||
results = list()
|
||||
for tile in tiles_with_collisions:
|
||||
guests = tile.guests_that_can_collide
|
||||
for pos in pos_with_collisions:
|
||||
guests = [x for x in state.entities.pos_dict[pos] if x.var_can_collide]
|
||||
if len(guests) >= 2:
|
||||
for i, guest in enumerate(guests):
|
||||
try:
|
||||
|
Reference in New Issue
Block a user