"""An example Python strategy for a match on the square grid."""
visits = {}

def play(turn):
    for unit in turn.units:
        if unit.status == 2:
            continue
        targets = [b for b in turn.buildings if b.owner != 1]
        if targets:
            target = min(targets, key=lambda b: abs(b.x-unit.x) + abs(b.y-unit.y))
            if unit.position == target.position:
                unit.capture(target)
            else:
                unit.move(target.x, target.y)
        elif turn.enemies:
            enemy = turn.enemies[0]
            unit.shoot(enemy.x, enemy.y)
        else:
            edge = turn.size - 1
            corners = [(0, 0), (edge, 0), (edge, edge), (0, edge)]
            step = visits.get(unit.id, unit.id) % 4
            if unit.position == corners[step]:
                step = (step + 1) % 4
            visits[unit.id] = step
            x, y = corners[step]
            unit.move(x, y)
