Commits

Lars Yencken  committed dfb9ee7

Locations on a torus.

  • Participants
  • Parent commits 895523e
  • Branches scent

Comments (0)

Files changed (2)

File test_torus.py

+# -*- coding: utf-8 -*-
+#
+#  test_torus.py
+#  aichallenge-py
+#
+#  Created by Lars Yencken on 2011-11-13.
+#  Copyright 2011 Lars Yencken. All rights reserved.
+#
+
+"""
+Tests for locations on a torus.
+"""
+
+import unittest
+
+import torus
+
+class TorusTest(unittest.TestCase):
+    def setUp(self):
+        torus.init(15, 20)
+
+    def test_add(self):
+        l1 = torus.Loc(3, 5)
+        l2 = torus.Loc(7, 8)
+        self.assertEqual(l1 + l2, torus.Loc(10, 13))
+
+        l3 = torus.Loc(14, 19)
+        self.assertEqual(l1 + l3, torus.Loc(2, 4))
+
+    def test_sub(self):
+        l1 = torus.Loc(3, 5)
+        l2 = torus.Loc(7, 8)
+        self.assertEqual(l2 - l1, torus.Loc(4, 3))
+
+        l3 = torus.Loc(4, 6)
+        self.assertEqual(l1 - l3, torus.Loc(14, 19))
+
+    def test_dist(self):
+        l1 = torus.Loc(3, 5)
+        l2 = torus.Loc(7, 8)
+        self.assertEqual(l1.dist(l2), 7)
+        self.assertEqual(l2.dist(l1), 7)
+
+        l3 = torus.Loc(14, 19)
+        self.assertEqual(l1.dist(l3), 10)
+        self.assertEqual(l3.dist(l1), 10)
+
+# -*- coding: utf-8 -*-
+#
+#  torus.py
+#  aichallenge-py
+#
+#  Created by Lars Yencken on 2011-11-13.
+#  Copyright 2011 Lars Yencken. All rights reserved.
+#
+
+"""
+Position operations on a torus.
+"""
+
+from collections import namedtuple
+
+ROWS = None
+COLS = None
+
+Loc = namedtuple('Loc', 'y x')
+
+def init(rows, cols):
+    global ROWS, COLS
+    ROWS = rows
+    COLS = cols
+
+    def _loc_add(l1, l2):
+        return Loc((l1.y + l2.y) % ROWS, (l1.x + l2.x) % COLS)
+    Loc.__add__ = _loc_add
+
+    def _loc_sub(l1, l2):
+        return Loc((l1.y - l2.y) % ROWS, (l1.x - l2.x) % COLS)
+    Loc.__sub__ = _loc_sub
+
+    def _loc_dist(l1, l2):
+        'calculate the closest distance between to locations'
+        x_diff = abs(l1.x - l2.x)
+        y_diff = abs(l1.y - l2.y)
+        return min(x_diff, COLS - x_diff) + min(y_diff, ROWS - y_diff)
+    Loc.dist = _loc_dist
+