Skip to content
This repository has been archived by the owner on Jun 10, 2021. It is now read-only.

Commit

Permalink
fix final tiled conversion for shared data (with ugly code)
Browse files Browse the repository at this point in the history
  • Loading branch information
buxx committed Oct 9, 2017
1 parent c3a25f1 commit 4c7452a
Show file tree
Hide file tree
Showing 5 changed files with 73 additions and 22 deletions.
5 changes: 4 additions & 1 deletion sandbox/tile/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
synergine2_path = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../'))
sys.path.append(synergine2_path)

from synergine2_xyz.move import MoveToMechanism, MoveToBehaviour
from sandbox.tile.simulation.subject import Man
from sandbox.tile.simulation.base import TileStrategySimulation
from sandbox.tile.simulation.base import TileStrategySubjects
Expand All @@ -24,11 +25,13 @@ def main(map_dir_path: str, seed_value: int=42):

config = Config()
config.load_files(['sandbox/tile/config.yaml'])
logger = get_default_logger(level=logging.DEBUG)
logger = get_default_logger(level=logging.ERROR)

map_file_path = 'sandbox/tile/{}.tmx'.format(os.path.join(map_dir_path, os.path.basename(map_dir_path)))

simulation = TileStrategySimulation(config, map_file_path=map_file_path)
simulation.add_to_index(Man, MoveToBehaviour, MoveToMechanism)

subjects = TileStrategySubjects(simulation=simulation)

for position in ((0, 2),):
Expand Down
49 changes: 31 additions & 18 deletions synergine2/share.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,17 @@ class TrackedDict(dict):

def __init__(self, seq=None, **kwargs):
self.key = kwargs.pop('key')
self.original_key = kwargs.pop('original_key')
self.shared = kwargs.pop('shared')
super().__init__(seq, **kwargs)

def __setitem__(self, key, value):
super().__setitem__(key, value)
self.shared.set(self.key, dict(self))
self.shared.set(self.key, dict(self), original_key=self.original_key)

def setdefault(self, k, d=None):
v = super().setdefault(k, d)
self.shared.set(self.key, dict(self))
self.shared.set(self.key, dict(self), original_key=self.original_key)
return v
# TODO: Cover all methods

Expand All @@ -49,12 +50,13 @@ class TrackedList(list):

def __init__(self, seq=(), **kwargs):
self.key = kwargs.pop('key')
self.original_key = kwargs.pop('original_key')
self.shared = kwargs.pop('shared')
super().__init__(seq)

def append(self, p_object):
super().append(p_object)
self.shared.set(self.key, list(self))
self.shared.set(self.key, list(self), original_key=self.original_key)

# TODO: Cover all methods

Expand Down Expand Up @@ -86,15 +88,20 @@ def reset(self) -> None:
self.commit()
self._data = {}

def set(self, key: str, value: typing.Any) -> None:
def set(self, key: str, value: typing.Any, original_key: str=None) -> None:
try:
special_type = self._special_types[key]
value = special_type(value, key=key, shared=self)
special_type, original_key_ = self._special_types[key]
value = special_type(value, key=key, shared=self, original_key=original_key)
except KeyError:
pass
try:
# TODO: Code degeu pour gerer les {id}_truc
special_type, original_key_ = self._special_types[original_key]
value = special_type(value, key=key, shared=self, original_key=original_key)
except KeyError:
pass

self._data[key] = value
self._modified_keys.add(key)
self._modified_keys.add((key, original_key))

def get(self, *key_args: typing.Union[str, float, int]) -> typing.Any:
key = '_'.join([str(v) for v in key_args])
Expand All @@ -111,25 +118,31 @@ def get(self, *key_args: typing.Union[str, float, int]) -> typing.Any:
special_type = None

try:
special_type = self._special_types[key]
special_type, original_key = self._special_types[key]
except KeyError:
pass

if special_type:
self._data[key] = special_type(value, key=key, shared=self)
self._data[key] = special_type(value, key=key, shared=self, original_key=original_key)
else:
self._data[key] = value

return self._data[key]

def commit(self) -> None:
for key in self._modified_keys:
for key, original_key in self._modified_keys:
try:
special_type = self._special_types[key]
special_type, original_key = self._special_types[key]
value = special_type.base(self.get(key))
self._r.set(key, pickle.dumps(value))
except KeyError:
self._r.set(key, pickle.dumps(self.get(key)))
# Code degeu pour gerer les {id}_truc
try:
special_type, original_key = self._special_types[original_key]
value = special_type.base(self.get(key))
self._r.set(key, pickle.dumps(value))
except KeyError:
self._r.set(key, pickle.dumps(self.get(key)))
self._modified_keys = set()

def refresh(self) -> None:
Expand All @@ -156,11 +169,11 @@ def create(
indexes = indexes or []

if type(value) is dict:
value = TrackedDict(value, key=key, shared=shared)
self._special_types[key] = TrackedDict
value = TrackedDict(value, key=key, shared=shared, original_key=key)
self._special_types[key] = TrackedDict, key
elif type(value) is list:
value = TrackedList(value, key=key, shared=shared)
self._special_types[key] = TrackedList
value = TrackedList(value, key=key, shared=shared, original_key=key)
self._special_types[key] = TrackedList, key

def get_key(obj):
return key
Expand All @@ -186,7 +199,7 @@ def fset(self_, value_):
except UnknownSharedData:
pass # If no shared data, no previous value to remove

self.set(key_formatter(self_), value_)
self.set(key_formatter(self_), value_, original_key=key)

for index in indexes:
index.add(value_)
Expand Down
12 changes: 10 additions & 2 deletions synergine2/simulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,21 @@ class Intention(object):


class IntentionManager(object):
def __init__(self) -> None:
self.intentions = {} # type: typing.Dict[typing.Type[Intention], Intention]
intentions = shared.create(['{id}', 'intentions'], {}) # type: typing.Dict[typing.Type[Intention], Intention]

def __init__(self):
self._id = id(self)
self.intentions = {}

@property
def id(self) -> int:
return self._id

def set(self, intention: Intention) -> None:
self.intentions[type(intention)] = intention

def get(self, intention_type: typing.Type[Intention]) -> Intention:
# TODO: Raise specialised exception if KeyError
return self.intentions[intention_type]


Expand Down
3 changes: 2 additions & 1 deletion synergine2_xyz/move.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ class MoveToBehaviour(SubjectBehaviour):
def run(self, data):
# TODO: on fait vraiment rien ici ? Note: meme si il n'y a pas de new_path, l'action doit s'effectuer
# du moment qu'il y a une intention de move
move_to_data = data[self.move_to_mechanism]
move_to_data = data[self.move_to_mechanism.__name__]
if move_to_data:
return move_to_data
return False
Expand All @@ -151,6 +151,7 @@ def action(self, data) -> [Event]:
new_position = move.path[move.path_progression]
previous_position = self.subject.position
self.subject.position = new_position
self.subject.intentions.set(move)

return [MoveEvent(self.subject.id, previous_position, new_position)]

Expand Down
26 changes: 26 additions & 0 deletions tests/test_share.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,32 @@ class Foo(object):
assert shared.get('data') == ['foo', 'bar', 'bAr']
assert pickle.loads(shared._r.get('data')) == ['foo', 'bar', 'bAr']

def test_update_list_with_pointer__composite_key(self):
shared = share.SharedDataManager()

class Foo(object):
data = shared.create(['{id}', 'data'], [])

def __init__(self):
self.id = id(self)

foo = Foo()
foo.data = ['foo']

assert shared.get(str(id(foo)) + '_data') == ['foo']

foo.data.append('bar')
assert shared.get(str(id(foo)) + '_data') == ['foo', 'bar']

shared.commit()
assert shared.get(str(id(foo)) + '_data') == ['foo', 'bar']
assert pickle.loads(shared._r.get(str(id(foo)) + '_data')) == ['foo', 'bar']

foo.data.append('bAr')
shared.commit()
assert shared.get(str(id(foo)) + '_data') == ['foo', 'bar', 'bAr']
assert pickle.loads(shared._r.get(str(id(foo)) + '_data')) == ['foo', 'bar', 'bAr']

def test_refresh_without_commit(self):
shared = share.SharedDataManager()

Expand Down

0 comments on commit 4c7452a

Please sign in to comment.