import ast
import imp
import rgkit.game as game
import rgkit.rg as rg
from rgkit.settings import settings


class MyPlayer(game.Player):
    def __init__(self, code):
        game.Player.__init__(self, code='')

        self._mod = imp.new_module('usercode%d' % id(self))

        def my_import(name, globals={}, locals={}, fromlist=[], level=-1):
            if name == 'rg':
                return rg
            else:
                return real_import(name, globals, locals, fromlist, level)

        builtins = dict(__builtins__)
        real_import, builtins['__import__'] = builtins['__import__'], my_import
        self._mod.__dict__['__builtins__'] = builtins
        exec code in self._mod.__dict__
        self._robots = None
        self._cache = {}


def game_board(game):
    boxes = []
    for y in range(settings.board_size):
        for x in range(settings.board_size):
            robot = game._field[(x, y)]
            if (x, y) in settings.obstacles:
                boxes.append({'type': 'obstacle'})
            elif robot is not None:
                boxes.append({
                    'type': {0: 'red', 1: 'blue'}[robot.player_id],
                    'hp': robot.hp
                })
            else:
                boxes.append({'type': 'normal'})

    return boxes


def run_game(code1, code2):
    def turn():
        return {'scores': g.get_scores(), 'board': game_board(g)}

    with open('rgkit/maps/default.py') as mapfile:
        game.init_settings(ast.literal_eval(mapfile.read()))

    g = game.Game(MyPlayer(code=code1), MyPlayer(code=code2))

    history = [turn()]
    for i in xrange(settings.max_turns):
        g.run_turn()
        history.append(turn())

    return history

@@ -1320,16 +1320,138 @@
 code2):%0A
+    directions = %7B%0A        (-1, 0): 'left',%0A        (1, 0): 'right',%0A        (0, 1): 'down',%0A        (0, -1): 'up'%0A    %7D%0A%0A
     def 
@@ -1656,16 +1656,25 @@
 me.Game(
+%0A        
 MyPlayer
@@ -1686,16 +1686,24 @@
 =code1),
+%0A       
  MyPlaye
@@ -1715,16 +1715,43 @@
 e=code2)
+,%0A        record_turns=True
 )%0A%0A    h
@@ -1830,16 +1830,349 @@
 _turn()%0A
+%0A        for (x, y), action in g.action_at%5Bg.turns-1%5D.iteritems():%0A            box = history%5B-1%5D%5B'board'%5D%5Bx+y*19%5D%0A            box%5B'action'%5D = action%5B'name'%5D%0A%0A            if action%5B'target'%5D is not None:%0A                target_x, target_y = action%5B'target'%5D%0A                box%5B'target'%5D = directions%5B(target_x - x), (target_y - y)%5D%0A%0A
         

add bot action information