Source

aichallenge-py / torus.py

Full commit
# -*- 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')

AIM = {'n': Loc(-1, 0),
       'e': Loc(0, 1),
       's': Loc(1, 0),
       'w': Loc(0, -1)}

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

    def _loc_dest(l, aim):
        return l + AIM[aim]
    Loc.dest = _loc_dest