home · contact · privacy
Lots of refactoring.
[plomrogue2-experiments] / server.py
index 6f79e0db69308e67665c090daeb3f17cdfeeced0..14df1f37b5b02be228ad82056813c717720df2e1 100755 (executable)
--- a/server.py
+++ b/server.py
@@ -79,40 +79,57 @@ class IO_Handler(socketserver.BaseRequestHandler):
         self.request.close()
 
 
+class Task:
+
+    def __init__(self, name, args=(), kwargs={}):
+        self.name = name
+        self.args = args
+        self.kwargs = kwargs
+        self.todo = 1
+
+
 class Thing:
 
-    def __init__(self, position):
+    def __init__(self, type_, position):
+        self.type = type_
         self.position = position
-        self.task = 'wait'
-        self.todo = 0
+        self.task = Task('wait')
 
     def task_wait(self):
         pass
 
-    def task_moveup(self):
-        self.position[0] -= 1
-
-    def task_movedown(self):
-        self.position[0] += 1
+    def task_move(self, direction):
+        if direction == 'UP':
+            self.position[0] -= 1
+        elif direction == 'DOWN':
+            self.position[0] += 1
+        elif direction == 'RIGHT':
+            self.position[1] += 1
+        elif direction == 'LEFT':
+            self.position[1] -= 1
 
     def decide_task(self):
-        self.set_task('wait')
+        if self.position[1] > 1:
+            self.set_task('move', 'LEFT')
+        elif self.position[1] < 3:
+            self.set_task('move', 'RIGHT')
+        else:
+            self.set_task('wait')
 
-    def set_task(self, task):
-        self.task = task
-        self.todo = 1
+    def set_task(self, task, *args, **kwargs):
+        self.task = Task(task, args, kwargs)
 
     def proceed(self, is_AI=True):
         """Further the thing in its tasks.
 
-        Decrements self.todo; if it thus falls to <= 0, enacts the method whose
-        name is 'task_' + self.task and sets self.task = None. If is_AI, calls
-        self.decide_task to decide a new self.task.
+        Decrements .task.todo; if it thus falls to <= 0, enacts method whose
+        name is 'task_' + self.task.name and sets .task = None. If is_AI, calls
+        .decide_task to decide a self.task.
         """
-        self.todo -= 1
-        if self.todo <= 0:
-            task= getattr(self, 'task_' + self.task)
-            task()
+        self.task.todo -= 1
+        if self.task.todo <= 0:
+            task = getattr(self, 'task_' + self.task.name)
+            task(*self.task.args, **self.task.kwargs)
             self.task = None
         if is_AI and self.task is None:
             self.decide_task()
@@ -123,12 +140,12 @@ class World:
     def __init__(self):
         self.turn = 0
         self.map_size = (5, 5)
-        self.map_ = 'xxxxx\n'+\
-                    'x...x\n'+\
-                    'x.X.x\n'+\
-                    'x...x\n'+\
+        self.map_ = 'xxxxx\n' +\
+                    'x...x\n' +\
+                    'x.X.x\n' +\
+                    'x...x\n' +\
                     'xxxxx'
-        self.things = [Thing(position=[3, 3]), Thing([1, 1])]
+        self.things = [Thing('human', [3, 3]), Thing('monster', [1, 1])]
         self.player_i = 0
         self.player = self.things[self.player_i]
 
@@ -169,6 +186,17 @@ class CommandHandler:
         """Transform tuple (y,x) into string 'Y:'+str(y)+',X:'+str(x)."""
         return 'Y:' + str(tuple_[0]) + ',X:' + str(tuple_[1])
 
+    def quoted(self, string):
+        """Quote and escape string so client interprets it as single token."""
+        quoted = []
+        quoted += ['"']
+        for c in string:
+            if c in {'"', '\\'}:
+                quoted += ['\\']
+            quoted += [c]
+        quoted += ['"']
+        return ''.join(quoted)
+
     def proceed_to_next_player_turn(self, connection_id):
         """Run game world turns until player can decide their next step.
 
@@ -186,15 +214,17 @@ class CommandHandler:
             for thing in self.world.things[self.world.player_i+1:]:
                 thing.proceed()
             self.world.turn += 1
-            for thing  in self.world.things[:self.world.player_i]:
+            for thing in self.world.things[:self.world.player_i]:
                 thing.proceed()
             self.world.player.proceed(is_AI=False)
             if self.world.player.task is None:
                 break
         self.send_all('NEW_TURN ' + str(self.world.turn))
         self.send_all('MAP_SIZE ' + self.stringify_yx(self.world.map_size))
-        self.send_all('TERRAIN\n' + self.world.map_)
-        self.send_all('POSITION ' + self.stringify_yx(self.world.player.position))
+        self.send_all('TERRAIN\n' + self.quoted(self.world.map_))
+        for thing in self.world.things:
+            self.send_all('THING TYPE:' + thing.type + ' '
+                          + self.stringify_yx(thing.position))
 
     def cmd_fib(self, tokens, connection_id):
         """Reply with n-th Fibonacci numbers, n taken from tokens[1:].
@@ -236,8 +266,10 @@ class CommandHandler:
         self.world.turn += 1
         self.send_all('NEW_TURN ' + str(self.world.turn))
         self.send_all('MAP_SIZE ' + self.stringify_yx(self.world.map_size))
-        self.send_all('TERRAIN\n' + self.world.map_)
-        self.send_all('POSITION ' + self.stringify_yx(self.world.player.position))
+        self.send_all('TERRAIN\n' + self.quoted(self.world.map_))
+        for thing in self.world.things:
+            self.send_all('THING TYPE:' + thing.type + ' '
+                          + self.stringify_yx(thing.position))
         self.pool_result = self.pool.map_async(fib, (35, 35))
 
     def cmd_get_turn(self, connection_id):
@@ -245,13 +277,11 @@ class CommandHandler:
         self.send_to(connection_id, str(self.world.turn))
 
     def cmd_move(self, direction, connection_id):
-        """Set player task to 'moveup' or 'movedown', finish player turn."""
-        if not direction in {'UP', 'DOWN'}:
-            raise ArgumentError('MOVE ARGUMENT MUST BE "UP" or "DOWN"')
-        if direction == 'UP':
-            self.world.player.set_task('moveup')
-        else:
-            self.world.player.set_task('movedown')
+        """Set player task to 'move' with direction arg, finish player turn."""
+        if direction not in {'UP', 'DOWN', 'RIGHT', 'LEFT'}:
+            raise ArgumentError('MOVE ARGUMENT MUST BE ONE OF: '
+                                'UP, DOWN, RIGHT, LEFT')
+        self.world.player.set_task('move', direction=direction)
         self.proceed_to_next_player_turn(connection_id)
 
     def cmd_wait(self, connection_id):