From b62e033801895ad633f702685e50cf367ae0adee Mon Sep 17 00:00:00 2001 From: Peter Ward Date: Sat, 21 Jul 2012 12:45:38 +1000 Subject: Add ZMQ engine and viewer. --- snakegame/engine.py | 18 +----------------- snakegame/zmq.py | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 17 deletions(-) create mode 100644 snakegame/zmq.py diff --git a/snakegame/engine.py b/snakegame/engine.py index 7ba9e0b..6a981a1 100644 --- a/snakegame/engine.py +++ b/snakegame/engine.py @@ -16,7 +16,7 @@ class Engine(object): def __init__( self, rows, columns, n_apples, - wrap=True, results=False, + wrap=True, random=None, *args, **kwargs ): @@ -28,9 +28,6 @@ class Engine(object): self.wrap = wrap self.bots = {} - self.results = None - if results: - self.results = open('results.csv', 'a+') self.new_game(rows, columns, n_apples) @@ -101,19 +98,6 @@ class Engine(object): bot = self.bots[letter] del self.bots[letter] - if not self.results: - return - - try: - name = bot[0].__name__ - except AttributeError: - pass - else: - apple_score = len(bot[2]) - self.results.write('%s,%s,%s,%s\n' % \ - (self.game_id, name, apple_score, time_score)) - self.results.flush() - def update_snakes(self): self.game_ticks += 1 diff --git a/snakegame/zmq.py b/snakegame/zmq.py new file mode 100644 index 0000000..c38c680 --- /dev/null +++ b/snakegame/zmq.py @@ -0,0 +1,35 @@ +from __future__ import absolute_import + +import pickle + +class Viewer(object): + def __init__(self, engine, sock): + self.sock = sock + self.engine = engine + + def run(self): + for board in self.engine: + bots = { + letter: (None, colour, None, team) + for letter, (_, colour, _, team) in self.engine.bots.iteritems() + } + + msg = pickle.dumps({ + 'bots': bots, + 'board': board, + }, protocol=2) + + self.sock.send(msg) + +class Engine(object): + def __init__(self, sock): + self.sock = sock + + def __iter__(self): + while True: + if not self.sock.poll(timeout=2000): + break + msg = self.sock.recv() + obj = pickle.loads(msg) + self.bots = obj['bots'] + yield obj['board'] -- cgit v1.2.3