summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorPeter Ward <peteraward@gmail.com>2012-07-21 12:45:38 +1000
committerPeter Ward <peteraward@gmail.com>2012-07-21 12:45:38 +1000
commitb62e033801895ad633f702685e50cf367ae0adee (patch)
treedaf37575a7de5b6d1d1fd230248a908acc588a0d
parentb99240781b813dd030e18750bb9d2ac62711c249 (diff)
Add ZMQ engine and viewer.
-rw-r--r--snakegame/engine.py18
-rw-r--r--snakegame/zmq.py35
2 files changed, 36 insertions, 17 deletions
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']