예제 #1
0
    def __init__(self, player1_path, player2_path):
        self.match_id = None

        self.player = Player(player1_path) if player1_path else None
        if self.player:
            self.player1_path = player1_path
            self.player.set_player_id(1)

        self.player2 = Player(player2_path) if player2_path else None
        if self.player2:
            self.player2_path = player2_path
            self.player2.set_player_id(0)

        self.turn_repeat = False

        self.UI = SimulatorUI(settings)
        self.UI.setTitle("Robot Game Simulator")

        self.state = GameState(settings, turn=1)
        self.cached_actions = None
        self.human_actions = {}

        self.UI.setTurn(self.state.turn)

        self.UI.bind("w", lambda ev: self.UI.moveSelection((0, -1)))
        self.UI.bind("a", lambda ev: self.UI.moveSelection((-1, 0)))
        self.UI.bind("s", lambda ev: self.UI.moveSelection((0, 1)))
        self.UI.bind("d", lambda ev: self.UI.moveSelection((1, 0)))
        self.UI.bind("<Up>", lambda ev: self.UI.moveSelection((0, -1)))
        self.UI.bind("<Left>", lambda ev: self.UI.moveSelection((-1, 0)))
        self.UI.bind("<Down>", lambda ev: self.UI.moveSelection((0, 1)))
        self.UI.bind("<Right>", lambda ev: self.UI.moveSelection((1, 0)))
        self.UI.bind("<ButtonPress-1>", lambda ev: self.UI.onMouseClick(ev))

        self.UI.bind("l", self.onLoadMatch)
        self.UI.bind("k", self.onLoadTurn)
        self.UI.bind("o", self.onReloadPlayer)
        self.UI.bind("p", self.onSwapPlayer)

        self.UI.bind("t", self.onEditTurn)
        self.UI.bind("f", self.onAddTeammate)
        self.UI.bind("e", self.onAddEnemy)
        self.UI.bind("r", self.onRemove)
        self.UI.bind("c", self.onClear)
        self.UI.bind("<Delete>", self.onRemove)
        self.UI.bind("<BackSpace>", self.onRemove)
        self.UI.bind("h", self.onEditHP)
        self.UI.bind("<space>", self.onShowActions)
        self.UI.bind("<Return>", self.onSimulate)
        self.UI.bind("n", self.onNextAction)
        self.UI.bind("g", self.onSpawnRobots)

        self.UI.run()
예제 #2
0
    def __init__(self, player1_path, player2_path):
        self.match_id = None

        self.player = Player(player1_path) if player1_path else None
        if self.player:
            self.player1_path = player1_path
            self.player.set_player_id(1)

        self.player2 = Player(player2_path) if player2_path else None
        if self.player2:
            self.player2_path = player2_path
            self.player2.set_player_id(0)

        self.turn_repeat = False

        self.UI = SimulatorUI(settings)
        self.UI.setTitle("Robot Game Simulator")

        self.state = GameState(settings, turn=1)
        self.cached_actions = None
        self.human_actions = {}

        self.UI.setTurn(self.state.turn)

        self.UI.bind("w", lambda ev: self.UI.moveSelection((0, -1)))
        self.UI.bind("a", lambda ev: self.UI.moveSelection((-1, 0)))
        self.UI.bind("s", lambda ev: self.UI.moveSelection((0, 1)))
        self.UI.bind("d", lambda ev: self.UI.moveSelection((1, 0)))
        self.UI.bind("<Up>", lambda ev: self.UI.moveSelection((0, -1)))
        self.UI.bind("<Left>", lambda ev: self.UI.moveSelection((-1, 0)))
        self.UI.bind("<Down>", lambda ev: self.UI.moveSelection((0, 1)))
        self.UI.bind("<Right>", lambda ev: self.UI.moveSelection((1, 0)))
        self.UI.bind("<ButtonPress-1>", lambda ev: self.UI.onMouseClick(ev))

        self.UI.bind("l", self.onLoadMatch)
        self.UI.bind("k", self.onLoadTurn)
        self.UI.bind("o", self.onReloadPlayer)
        self.UI.bind("p", self.onSwapPlayer)

        self.UI.bind("t", self.onEditTurn)
        self.UI.bind("f", self.onAddTeammate)
        self.UI.bind("e", self.onAddEnemy)
        self.UI.bind("r", self.onRemove)
        self.UI.bind("c", self.onClear)
        self.UI.bind("<Delete>", self.onRemove)
        self.UI.bind("<BackSpace>", self.onRemove)
        self.UI.bind("h", self.onEditHP)
        self.UI.bind("<space>", self.onShowActions)
        self.UI.bind("<Return>", self.onSimulate)
        self.UI.bind("n", self.onNextAction)
        self.UI.bind("g", self.onSpawnRobots)

        self.UI.run()
예제 #3
0
    def __init__(self, settings, p1_path, p2_path):
        self.settings = settings
        self.match_id = None
        self.p1_path = p1_path
        self.p2_path = p2_path
        self.code = open(p1_path).read()
        if p2_path is None:
            self.p2_path = map_data = open(pkg_resources.resource_filename('rgkit', 'bots/guardbot.py')).read()
        self.code2 = open(p2_path).read()

        self.player = Player(self.code)
        self.player.set_player_id(1)
        self.player2 = Player(self.code2)
        self.player2.set_player_id(0)
        self.UI = SimulatorUI(settings)
        self.UI.setTitle("Robot Game Simulator")

        self.state = GameState(settings, turn=1)
        self.cached_actions = None

        self.UI.setTurn(self.state.turn)

        self.UI.bind("w", lambda ev: self.UI.moveSelection((0, -1)))
        self.UI.bind("a", lambda ev: self.UI.moveSelection((-1, 0)))
        self.UI.bind("s", lambda ev: self.UI.moveSelection((0, 1)))
        self.UI.bind("d", lambda ev: self.UI.moveSelection((1, 0)))
        self.UI.bind("<Up>", lambda ev: self.UI.moveSelection((0, -1)))
        self.UI.bind("<Left>", lambda ev: self.UI.moveSelection((-1, 0)))
        self.UI.bind("<Down>", lambda ev: self.UI.moveSelection((0, 1)))
        self.UI.bind("<Right>", lambda ev: self.UI.moveSelection((1, 0)))
        self.UI.bind("<ButtonPress-1>", lambda ev: self.UI.onMouseClick(ev))

        self.UI.bind("l", self.onLoadMatch)
        self.UI.bind("k", self.onLoadTurn)
        self.UI.bind("o", self.onReloadPlayer)
        self.UI.bind("p", self.onSwapPlayer)
        
        self.UI.bind("t", self.onEditTurn)
        self.UI.bind("f", self.onAddTeammate)
        self.UI.bind("e", self.onAddEnemy)
        self.UI.bind("r", self.onRemove)
        self.UI.bind("c", self.onClear)
        self.UI.bind("<Delete>", self.onRemove)
        self.UI.bind("<BackSpace>", self.onRemove)
        self.UI.bind("h", self.onEditHP)
        self.UI.bind("<space>", self.onShowActions)
        self.UI.bind("<Return>", self.onSimulate)

        self.UI.run()
예제 #4
0
    def __init__(self, settings, player, player2):
        self.settings = settings
        self.player = player
        self.player2 = player2
        self.UI = SimulatorUI(settings)
        self.UI.setTitle("Robot Game Simulator")

        self.robots = []
        self.cached_actions = None
        self.field = game.Field(settings.board_size)
        self.robot_id = 0

        self.turn = 1
        self.last_recipe_id = -1
        self.UI.setTurn(self.turn)

        self.UI.bind("w", lambda ev: self.UI.moveSelection((0, -1)))
        self.UI.bind("a", lambda ev: self.UI.moveSelection((-1, 0)))
        self.UI.bind("s", lambda ev: self.UI.moveSelection((0, 1)))
        self.UI.bind("d", lambda ev: self.UI.moveSelection((1, 0)))
        self.UI.bind("<Up>", lambda ev: self.UI.moveSelection((0, -1)))
        self.UI.bind("<Left>", lambda ev: self.UI.moveSelection((-1, 0)))
        self.UI.bind("<Down>", lambda ev: self.UI.moveSelection((0, 1)))
        self.UI.bind("<Right>", lambda ev: self.UI.moveSelection((1, 0)))
        self.UI.bind("<ButtonPress-1>", lambda ev: self.UI.onMouseClick(ev))

        self.UI.bind("t", self.onEditTurn)
        self.UI.bind("f", self.onAddTeammate)
        self.UI.bind("e", self.onAddEnemy)
        self.UI.bind("r", self.onRemove)
        self.UI.bind("c", self.onClear)
        self.UI.bind("<Delete>", self.onRemove)
        self.UI.bind("<BackSpace>", self.onRemove)
        self.UI.bind("h", self.onEditHP)
        self.UI.bind("<space>", self.onShowActions)
        self.UI.bind("<Return>", self.onSimulate)
        self.UI.bind("v", self.onSave)
        self.UI.bind("l", self.onLoad)

        self.UI.run()
예제 #5
0
class Simulator:
    def __init__(self, player1_path, player2_path):
        self.match_id = None

        self.player = Player(player1_path) if player1_path else None
        if self.player:
            self.player1_path = player1_path
            self.player.set_player_id(1)

        self.player2 = Player(player2_path) if player2_path else None
        if self.player2:
            self.player2_path = player2_path
            self.player2.set_player_id(0)

        self.turn_repeat = False

        self.UI = SimulatorUI(settings)
        self.UI.setTitle("Robot Game Simulator")

        self.state = GameState(settings, turn=1)
        self.cached_actions = None
        self.human_actions = {}

        self.UI.setTurn(self.state.turn)

        self.UI.bind("w", lambda ev: self.UI.moveSelection((0, -1)))
        self.UI.bind("a", lambda ev: self.UI.moveSelection((-1, 0)))
        self.UI.bind("s", lambda ev: self.UI.moveSelection((0, 1)))
        self.UI.bind("d", lambda ev: self.UI.moveSelection((1, 0)))
        self.UI.bind("<Up>", lambda ev: self.UI.moveSelection((0, -1)))
        self.UI.bind("<Left>", lambda ev: self.UI.moveSelection((-1, 0)))
        self.UI.bind("<Down>", lambda ev: self.UI.moveSelection((0, 1)))
        self.UI.bind("<Right>", lambda ev: self.UI.moveSelection((1, 0)))
        self.UI.bind("<ButtonPress-1>", lambda ev: self.UI.onMouseClick(ev))

        self.UI.bind("l", self.onLoadMatch)
        self.UI.bind("k", self.onLoadTurn)
        self.UI.bind("o", self.onReloadPlayer)
        self.UI.bind("p", self.onSwapPlayer)

        self.UI.bind("t", self.onEditTurn)
        self.UI.bind("f", self.onAddTeammate)
        self.UI.bind("e", self.onAddEnemy)
        self.UI.bind("r", self.onRemove)
        self.UI.bind("c", self.onClear)
        self.UI.bind("<Delete>", self.onRemove)
        self.UI.bind("<BackSpace>", self.onRemove)
        self.UI.bind("h", self.onEditHP)
        self.UI.bind("<space>", self.onShowActions)
        self.UI.bind("<Return>", self.onSimulate)
        self.UI.bind("n", self.onNextAction)
        self.UI.bind("g", self.onSpawnRobots)

        self.UI.run()

    def onReloadPlayer(self, event):
        self.UI.fadeActions()
        self.cached_actions = None
        self.human_actions = {}
        if self.player:
            self.player = Player(self.player1_path)
            self.player.set_player_id(1)
        if self.player2:
            self.player2 = Player(self.player2_path)
            self.player2.set_player_id(0)

    def onSwapPlayer(self, event):
        self.UI.clearActions()
        self.UI.clearBots()
        self.onReloadPlayer(None)
        for loc, robot in self.state.robots.iteritems():
            self.state.robots[loc][
                "player_id"] = 1 - self.state.robots[loc]["player_id"]
            self.UI.renderBot(loc, robot.hp, robot.player_id)

    def onLoadMatch(self, event):
        self.match_id = tkSimpleDialog.askinteger("Load match",
                                                  "Enter match number",
                                                  parent=self.UI.root,
                                                  initialvalue=2588548,
                                                  minvalue=1,
                                                  maxvalue=99999999)
        if self.match_id is not None:
            self.moves = getrgmatch.get_match_result(self.match_id)
            self.loadBotsfromTurn(1)

    def onLoadTurn(self, event):
        if self.match_id is not None:
            new_turn = tkSimpleDialog.askinteger("Edit turn",
                                                 "Enter new turn",
                                                 parent=self.UI.root,
                                                 initialvalue=self.state.turn,
                                                 minvalue=1,
                                                 maxvalue=100)
            if new_turn is not None:
                self.loadBotsfromTurn(new_turn)

    def loadBotsfromTurn(self, new_turn):
        if self.match_id is not None:
            self.UI.clearActions()
            self.UI.clearBots()
            self.cached_actions = None
            self.human_actions = {}
            self.state = GameState()
            for bot in self.moves[new_turn]:
                loc = tuple(bot['location'])
                # print bot
                self.state.add_robot(loc, bot['player_id'])
                self.state.robots[loc].hp = bot['hp']
                self.UI.renderBot(loc, bot['hp'], bot['player_id'])

            self.UI.setTurn(new_turn)
            self.state.turn = new_turn

    def onEditTurn(self, event):
        new_turn = tkSimpleDialog.askinteger("Edit turn",
                                             "Enter new turn",
                                             parent=self.UI.root,
                                             initialvalue=self.state.turn,
                                             minvalue=1,
                                             maxvalue=100)
        if new_turn is not None:
            self.UI.fadeActions()
            self.cached_actions = None
            self.human_actions = {}
            self.UI.setTurn(new_turn)
            self.state.turn = new_turn

    def onRemove(self, event):
        self._removeRobot(self.UI.selection)

    def _removeRobot(self, loc):
        if self.state.is_robot(loc):
            self.UI.fadeActions()
            self.cached_actions = None
            if loc in self.human_actions:
                del self.human_actions[loc]
            self.state.remove_robot(loc)
            self.UI.renderEmpty(loc)

    def onAddTeammate(self, event):
        self._addRobot(1, self.UI.selection)

    def onAddEnemy(self, event):
        self._addRobot(0, self.UI.selection)

    def _addRobot(self, player_id, loc):
        self.UI.fadeActions()
        self.cached_actions = None
        if self.state.is_robot(loc):
            self.state.remove_robot(loc)
            if loc in self.human_actions:
                del self.human_actions[loc]

        self.state.add_robot(loc, player_id)
        self.UI.renderBot(loc, 50, player_id)

    def onEditHP(self, event):
        if self.state.is_robot(self.UI.selection):
            robot = self.state.robots[self.UI.selection]
            self.UI.fadeActions()
            self.cached_actions = None
            new_hp = tkSimpleDialog.askinteger("Edit hp",
                                               "Enter new hp",
                                               parent=self.UI.root,
                                               initialvalue=robot.hp,
                                               minvalue=1,
                                               maxvalue=50)
            if new_hp is not None:
                robot.hp = new_hp
                self.UI.renderBot(self.UI.selection, new_hp, robot.player_id)

    def getActions(self):
        def getPlayerActions(player, player_id):
            if player:
                actions, _ = player.get_responses(self.state, player_id)
            else:
                actions = {}
            for loc, robot in self.state.robots.iteritems():
                if robot.player_id == player_id:
                    action = self.human_actions.get(loc)
                    if action or loc not in actions:
                        actions[loc] = action if action else ('guard', )
            return actions

        actions = getPlayerActions(self.player, 1)
        actions.update(getPlayerActions(self.player2, 0))
        return actions

    def onClear(self, event):
        self.UI.clearActions()
        self.UI.clearBots()
        self.cached_actions = None
        self.human_actions = {}
        self.state = GameState(turn=self.state.turn)

    def onShowActions(self, event):
        if self.state.turn < 100:
            # the following is needed since if the turn does not change,
            # non-stateless bots behave differently
            if self.player and self.turn_repeat:
                self.player = Player(self.player1_path)
                self.player.set_player_id(1)
            if self.player2 and self.turn_repeat:
                self.player2 = Player(self.player2_path)
                self.player2.set_player_id(0)
            self.UI.clearActions()
            actions = self.getActions()
            self.cached_actions = actions

            for loc, action in actions.iteritems():
                self.UI.renderAction(loc, action)

            self.turn_repeat = True

            try:
                rgsim_text = self.player._module.rgsim_text
                for loc, text in rgsim_text.iteritems():
                    self.UI.renderText(loc, text)

            except AttributeError:
                print "No rgsim_text dict found for player 1, skipping..."
            except:
                print("Error in rgsim_text dict, please ensure keys are " +
                      "valid locations and values are strings")

    def onSimulate(self, event):
        if self.state.turn < 100:
            self.UI.clearActions()
            self.UI.clearBots()
            if self.cached_actions is None:
                actions = self.getActions()
            else:
                actions = self.cached_actions

            self.state = self.state.apply_actions(actions, spawn=False)

            for loc, robot in self.state.robots.iteritems():
                self.UI.renderBot(loc, robot.hp, robot.player_id)

            self.cached_actions = None
            self.human_actions = {}
            self.UI.setTurn(self.state.turn)
            self.turn_repeat = False

    def onNextAction(self, event):
        if not self.state.is_robot(self.UI.selection):
            return
        robot = self.state.robots[self.UI.selection]
        action = self.human_actions.get(self.UI.selection)
        if action is None and self.cached_actions is not None:
            action = self.cached_actions.get(self.UI.selection)
        if action is None:
            action = ('guard', )
        x, y = self.UI.selection
        adjacent_locs = ((x, y - 1), (x + 1, y), (x, y + 1), (x - 1, y))
        move_locs = [l for l in adjacent_locs if l not in settings.obstacles]
        all_actions = [('guard', )]
        all_actions += [('move', loc) for loc in move_locs]
        all_actions += [('attack', loc) for loc in adjacent_locs]
        all_actions += [('suicide', )]
        i = (all_actions.index(action) + 1) % len(all_actions)
        action = all_actions[i]
        if self.cached_actions is not None:
            self.cached_actions[self.UI.selection] = action
        self.human_actions[self.UI.selection] = action
        self.UI.clearAction(self.UI.selection)
        self.UI.renderAction(self.UI.selection, action)

    def onSpawnRobots(self, event):
        all_locs = self.state._get_spawn_locations()
        for loc in settings.spawn_coords:
            self._removeRobot(loc)
        for i, loc in enumerate(all_locs):
            player_id = i // settings.spawn_per_player
            self._addRobot(player_id, loc)
예제 #6
0
class Simulator:
    SAVE_FILE = "rgsimulator.csv"

    def __init__(self, settings, player, player2):
        self.settings = settings
        self.player = player
        self.player2 = player2
        self.UI = SimulatorUI(settings)
        self.UI.setTitle("Robot Game Simulator")

        self.robots = []
        self.cached_actions = None
        self.field = game.Field(settings.board_size)
        self.robot_id = 0

        self.turn = 1
        self.last_recipe_id = -1
        self.UI.setTurn(self.turn)

        self.UI.bind("w", lambda ev: self.UI.moveSelection((0, -1)))
        self.UI.bind("a", lambda ev: self.UI.moveSelection((-1, 0)))
        self.UI.bind("s", lambda ev: self.UI.moveSelection((0, 1)))
        self.UI.bind("d", lambda ev: self.UI.moveSelection((1, 0)))
        self.UI.bind("<Up>", lambda ev: self.UI.moveSelection((0, -1)))
        self.UI.bind("<Left>", lambda ev: self.UI.moveSelection((-1, 0)))
        self.UI.bind("<Down>", lambda ev: self.UI.moveSelection((0, 1)))
        self.UI.bind("<Right>", lambda ev: self.UI.moveSelection((1, 0)))
        self.UI.bind("<ButtonPress-1>", lambda ev: self.UI.onMouseClick(ev))

        self.UI.bind("t", self.onEditTurn)
        self.UI.bind("f", self.onAddTeammate)
        self.UI.bind("e", self.onAddEnemy)
        self.UI.bind("r", self.onRemove)
        self.UI.bind("c", self.onClear)
        self.UI.bind("<Delete>", self.onRemove)
        self.UI.bind("<BackSpace>", self.onRemove)
        self.UI.bind("h", self.onEditHP)
        self.UI.bind("<space>", self.onShowActions)
        self.UI.bind("<Return>", self.onSimulate)
        self.UI.bind("v", self.onSave)
        self.UI.bind("l", self.onLoad)

        self.UI.run()

    def onEditTurn(self, event):
        new_turn = tkSimpleDialog.askinteger(
            "Edit turn", "Enter new turn", parent=self.UI.root, initialvalue=self.turn, minvalue=1, maxvalue=100
        )
        if new_turn is not None:
            self.UI.fadeActions()
            self.cached_actions = None
            self.UI.setTurn(new_turn)
            self.turn = new_turn

    def onRemove(self, event):
        if self.getRobot(self.UI.selection) is not None:
            self.UI.fadeActions()
            self.cached_actions = None
            self.removeRobot(self.UI.selection)
            self.UI.renderEmpty(self.UI.selection)

    def onAddTeammate(self, event):
        self.UI.fadeActions()
        self.cached_actions = None
        if self.getRobot(self.UI.selection) is not None:
            self.removeRobot(self.UI.selection)

        self.addRobot(self.UI.selection, 1)
        self.UI.renderBot(self.UI.selection, 50, 1)

    def onSave(self, event):
        def serialize(robot):
            return ":".join((robot.player_id, robot.hp, robot.location[0], robot.location[1]))

        with open(self.SAVE_FILE, "a") as fd:
            csv.writer(fd).writerow([serialize(robot) for robot in self.robots])
            print ("added a recipe")

    def onLoad(self, event):
        def deserialize(entry):
            id_, hp, x, y = map(int, entry.split(":"))
            return id_, hp, (x, y)

        with open(self.SAVE_FILE, "r") as fd:
            recipes = [row for row in csv.reader(fd)]
            if len(recipes) <= self.last_recipe_id + 1:
                return
            robots = recipes[self.last_recipe_id + 1]
            if robots is not None:
                self.last_recipe_id += 1
                self.onClear()
                print ("loaded recipe %s" % (self.last_recipe_id,))
                print robots
        for robot in robots:
            id_, hp, location = deserialize(robot)
            self.addRobot(location, id_, hp)
            self.UI.renderBot(self.UI.selection, hp, id_)

    def onAddEnemy(self, event):
        self.UI.fadeActions()
        self.cached_actions = None
        if self.getRobot(self.UI.selection) is not None:
            self.removeRobot(self.UI.selection)

        self.addRobot(self.UI.selection, 0)
        self.UI.renderBot(self.UI.selection, 50, 0)

    def onEditHP(self, event):
        robot = self.getRobot(self.UI.selection)
        if robot is not None:
            self.UI.fadeActions()
            self.cached_actions = None
            new_hp = tkSimpleDialog.askinteger(
                "Edit hp", "Enter new hp", parent=self.UI.root, initialvalue=robot.hp, minvalue=1, maxvalue=50
            )
            if new_hp is not None:
                robot.hp = new_hp
                self.UI.renderBot(self.UI.selection, new_hp, robot.player_id)

    def getRobotID(self):
        ret = self.robot_id
        self.robot_id += 1
        return ret

    def removeRobot(self, loc):
        self.robots.remove(self.field[loc])
        self.field[loc] = None

    def getRobot(self, loc):
        return self.field[loc]

    def addRobot(self, loc, player_id, hp=None):
        if hp is None:
            hp = self.settings.robot_hp
        robot_id = self.getRobotID()
        robot = game.InternalRobot(loc, hp, player_id, robot_id, self.field, 0)
        self.robots.append(robot)
        self.field[loc] = robot

    def buildGameInfo(self):
        return AttrDict(
            {
                "robots": dict(
                    (
                        y.location,
                        AttrDict(
                            dict(
                                (x, getattr(y, x))
                                for x in (self.settings.exposed_properties + self.settings.player_only_properties)
                            )
                        ),
                    )
                    for y in self.robots
                ),
                "turn": self.turn,
            }
        )

    def getActions(self):
        self.player._robot = None
        if self.player2 is not None:
            self.player2._robot = None
        game_info = self.buildGameInfo()
        actions = {}

        for robot in self.robots:
            if robot.player_id == 1:
                robot_player = self.player
            else:
                if self.player2 is not None:
                    robot_player = self.player2
                else:
                    # Don't act
                    actions[robot] = ["guard"]
                    continue

            user_robot = robot_player.get_robot()
            for prop in self.settings.exposed_properties + self.settings.player_only_properties:
                setattr(user_robot, prop, getattr(robot, prop))
            try:
                next_action = user_robot.act(game_info)
                if not robot.is_valid_action(next_action):
                    raise Exception(
                        "Bot %d: %s is not a valid action from %s"
                        % (robot.player_id + 1, str(next_action), robot.location)
                    )
            except Exception:
                traceback.print_exc(file=sys.stdout)
                next_action = ["guard"]
            actions[robot] = next_action

        return actions

    def remove_dead(self):
        to_remove = [x for x in self.robots if x.hp <= 0]
        for robot in to_remove:
            self.robots.remove(robot)
            if self.field[robot.location] == robot:
                self.field[robot.location] = None
                self.UI.renderEmpty(robot.location)

    def onClear(self, event=None):
        self.UI.clearActions()
        self.cached_actions = None
        locations = [robot.location for robot in self.robots]
        self.robots = []
        for loc in locations:
            self.field[loc] = None
            self.UI.renderEmpty(loc)

    def onShowActions(self, event):
        self.UI.clearActions()
        actions = self.getActions()
        self.cached_actions = actions

        for robot, action in actions.items():
            self.UI.renderAction(robot.location, action)

    def applyActions(self, actions):
        action_priority = ["move", "attack", "suicide"]

        for cmd in action_priority:
            for robot, action in actions.iteritems():
                if action[0] != cmd:
                    continue

                old_loc = robot.location
                try:
                    robot.issue_command(action, actions)
                except Exception:
                    traceback.print_exc(file=sys.stdout)
                    actions[robot] = ["guard"]
                if robot.location != old_loc:
                    if self.field[old_loc] is robot:
                        self.field[old_loc] = None
                        self.UI.renderEmpty(old_loc)
                    self.field[robot.location] = robot

    def onSimulate(self, event):
        self.UI.clearActions()
        if self.cached_actions is None:
            actions = self.getActions()
        else:
            actions = self.cached_actions

        self.applyActions(actions)

        for robot, action in actions.items():
            self.UI.renderAction(robot.location, action)
            self.UI.renderBot(robot.location, robot.hp, robot.player_id)

        self.remove_dead()
        self.cached_actions = None
        self.turn += 1
        self.UI.setTurn(self.turn)
예제 #7
0
class Simulator:
    def __init__(self, player1, player2):
        self.match_id = None

        self.player = player1
        if self.player:
            self.player.set_player_id(1)
        self.player2 = player2
        if self.player2:
            self.player2.set_player_id(0)
        self.UI = SimulatorUI(settings)
        self.UI.setTitle("Robot Game Simulator")

        self.state = GameState(settings, turn=1)
        self.cached_actions = None
        self.human_actions = {}

        self.UI.setTurn(self.state.turn)

        self.UI.bind("w", lambda ev: self.UI.moveSelection((0, -1)))
        self.UI.bind("a", lambda ev: self.UI.moveSelection((-1, 0)))
        self.UI.bind("s", lambda ev: self.UI.moveSelection((0, 1)))
        self.UI.bind("d", lambda ev: self.UI.moveSelection((1, 0)))
        self.UI.bind("<Up>", lambda ev: self.UI.moveSelection((0, -1)))
        self.UI.bind("<Left>", lambda ev: self.UI.moveSelection((-1, 0)))
        self.UI.bind("<Down>", lambda ev: self.UI.moveSelection((0, 1)))
        self.UI.bind("<Right>", lambda ev: self.UI.moveSelection((1, 0)))
        self.UI.bind("<ButtonPress-1>", lambda ev: self.UI.onMouseClick(ev))

        self.UI.bind("l", self.onLoadMatch)
        self.UI.bind("k", self.onLoadTurn)
        self.UI.bind("o", self.onReloadPlayer)
        self.UI.bind("p", self.onSwapPlayer)

        self.UI.bind("t", self.onEditTurn)
        self.UI.bind("f", self.onAddTeammate)
        self.UI.bind("e", self.onAddEnemy)
        self.UI.bind("r", self.onRemove)
        self.UI.bind("c", self.onClear)
        self.UI.bind("<Delete>", self.onRemove)
        self.UI.bind("<BackSpace>", self.onRemove)
        self.UI.bind("h", self.onEditHP)
        self.UI.bind("<space>", self.onShowActions)
        self.UI.bind("<Return>", self.onSimulate)
        self.UI.bind("n", self.onNextAction)
        self.UI.bind("g", self.onSpawnRobots)

        self.UI.run()

    def onReloadPlayer(self, event):
        self.UI.fadeActions()
        self.cached_actions = None
        self.human_actions = {}
        if self.player:
            self.player.reload(from_file=True)
            self.player.set_player_id(1)
        if self.player2:
            self.player2.reload(from_file=True)
            self.player2.set_player_id(0)

    def onSwapPlayer(self, event):
        self.player, self.player2 = self.player2, self.player
        self.onReloadPlayer(None)

    def onLoadMatch(self, event):
        self.match_id = tkSimpleDialog.askinteger(
            "Load match", "Enter match number",
            parent = self.UI.root,
            initialvalue = 2588548,
            minvalue = 1,
            maxvalue = 99999999
        )
        if self.match_id is not None:
            self.moves = getrgmatch.get_match_result(self.match_id)
            self.loadBotsfromTurn(1)

    def onLoadTurn(self, event):
        if self.match_id is not None:
            new_turn = tkSimpleDialog.askinteger(
                "Edit turn", "Enter new turn",
                parent = self.UI.root,
                initialvalue = self.state.turn,
                minvalue = 1,
                maxvalue = 100
            )
            if new_turn is not None:
                self.loadBotsfromTurn(new_turn)

    def loadBotsfromTurn (self, new_turn):
        if self.match_id is not None:
            self.UI.clearActions()
            self.UI.clearBots()
            self.cached_actions = None
            self.human_actions = {}
            self.state = GameState()
            for bot in self.moves[new_turn]:
                loc = tuple(bot['location'])
                # print bot
                self.state.add_robot(loc, bot['player_id'])
                self.state.robots[loc].hp = bot['hp']
                self.UI.renderBot(loc, bot['hp'], bot['player_id'])

            self.UI.setTurn(new_turn)
            self.state.turn = new_turn


    def onEditTurn(self, event):
        new_turn = tkSimpleDialog.askinteger(
            "Edit turn", "Enter new turn",
            parent = self.UI.root,
            initialvalue = self.state.turn,
            minvalue = 1,
            maxvalue = 100
        )
        if new_turn is not None:
            self.UI.fadeActions()
            self.cached_actions = None
            self.human_actions = {}
            self.UI.setTurn(new_turn)
            self.state.turn = new_turn

    def onRemove(self, event):
        self._removeRobot(self.UI.selection)

    def _removeRobot(self, loc):
        if self.state.is_robot(loc):
            self.UI.fadeActions()
            self.cached_actions = None
            if loc in self.human_actions:
                del self.human_actions[loc]
            self.state.remove_robot(loc)
            self.UI.renderEmpty(loc)

    def onAddTeammate(self, event):
        self._addRobot(1, self.UI.selection)

    def onAddEnemy(self, event):
        self._addRobot(0, self.UI.selection)

    def _addRobot(self, player_id, loc):
        self.UI.fadeActions()
        self.cached_actions = None
        if self.state.is_robot(loc):
            self.state.remove_robot(loc)
            if loc in self.human_actions:
                del self.human_actions[loc]

        self.state.add_robot(loc, player_id)
        self.UI.renderBot(loc, 50, player_id)

    def onEditHP(self, event):
        if self.state.is_robot(self.UI.selection):
            robot = self.state.robots[self.UI.selection]
            self.UI.fadeActions()
            self.cached_actions = None
            new_hp = tkSimpleDialog.askinteger(
                "Edit hp", "Enter new hp",
                parent = self.UI.root,
                initialvalue = robot.hp,
                minvalue = 1,
                maxvalue = 50
            )
            if new_hp is not None:
                robot.hp = new_hp
                self.UI.renderBot(self.UI.selection, new_hp, robot.player_id)

    def getActions(self):
        def getPlayerActions(player, player_id):
            if player:
                actions = player.get_actions(self.state, player_id)
            else:
                actions = {}
            for loc, robot in self.state.robots.iteritems():
                if robot.player_id == player_id:
                    action = self.human_actions.get(loc)
                    if action or loc not in actions:
                        actions[loc] = action if action else ['guard']
            return actions
        actions = getPlayerActions(self.player, 1)
        actions.update(getPlayerActions(self.player2, 0))
        return actions

    def onClear(self, event):
        self.UI.clearActions()
        self.UI.clearBots()
        self.cached_actions = None
        self.human_actions = {}
        self.state = GameState(turn=self.state.turn)

    def onShowActions(self, event):
        if self.state.turn < 100:
            if self.player:
                self.player.reload(from_file=True)
            if self.player2:
                self.player2.reload(from_file=True)
            self.UI.clearActions()
            actions = self.getActions()
            self.cached_actions = actions

            for loc, action in actions.iteritems():
                self.UI.renderAction(loc, action)

    def onSimulate(self, event):
        if self.state.turn < 100:
            self.UI.clearActions()
            self.UI.clearBots()
            if self.cached_actions is None:
                actions = self.getActions()
            else:
                actions = self.cached_actions

            self.state = self.state.apply_actions(actions, spawn=False)

            for loc, robot in self.state.robots.iteritems():
                self.UI.renderBot(loc, robot.hp, robot.player_id)

            self.cached_actions = None
            self.human_actions = {}
            self.UI.setTurn(self.state.turn)

    def onNextAction(self, event):
        if not self.state.is_robot(self.UI.selection):
            return
        robot = self.state.robots[self.UI.selection]
        action = self.human_actions.get(self.UI.selection)
        if action is None and self.cached_actions is not None:
            action = self.cached_actions.get(self.UI.selection)
        if action is None:
            action = ['guard']
        x, y = self.UI.selection
        adjacent_locs = ((x, y-1), (x+1, y), (x, y+1), (x-1, y))
        move_locs = [l for l in adjacent_locs if l not in settings.obstacles]
        all_actions = [['guard']]
        all_actions += [['move', loc] for loc in move_locs]
        all_actions += [['attack', loc] for loc in adjacent_locs]
        all_actions += [['suicide']]
        i = (all_actions.index(action) + 1) % len(all_actions)
        action = all_actions[i]
        if self.cached_actions is not None:
            self.cached_actions[self.UI.selection] = action
        self.human_actions[self.UI.selection] = action
        self.UI.clearAction(self.UI.selection)
        self.UI.renderAction(self.UI.selection, action)

    def onSpawnRobots(self, event):
        all_locs = self.state._get_spawn_locations()
        for loc in settings.spawn_coords:
            self._removeRobot(loc)
        for i, loc in enumerate(all_locs):
            player_id = i // settings.spawn_per_player
            self._addRobot(player_id, loc)
예제 #8
0
class Simulator:
    def __init__(self, settings, p1_path, p2_path):
        self.settings = settings
        self.match_id = None
        self.p1_path = p1_path
        self.p2_path = p2_path
        self.code = open(p1_path).read()
        if p2_path is None:
            self.p2_path = map_data = open(pkg_resources.resource_filename('rgkit', 'bots/guardbot.py')).read()
        self.code2 = open(p2_path).read()

        self.player = Player(self.code)
        self.player.set_player_id(1)
        self.player2 = Player(self.code2)
        self.player2.set_player_id(0)
        self.UI = SimulatorUI(settings)
        self.UI.setTitle("Robot Game Simulator")

        self.state = GameState(settings, turn=1)
        self.cached_actions = None

        self.UI.setTurn(self.state.turn)

        self.UI.bind("w", lambda ev: self.UI.moveSelection((0, -1)))
        self.UI.bind("a", lambda ev: self.UI.moveSelection((-1, 0)))
        self.UI.bind("s", lambda ev: self.UI.moveSelection((0, 1)))
        self.UI.bind("d", lambda ev: self.UI.moveSelection((1, 0)))
        self.UI.bind("<Up>", lambda ev: self.UI.moveSelection((0, -1)))
        self.UI.bind("<Left>", lambda ev: self.UI.moveSelection((-1, 0)))
        self.UI.bind("<Down>", lambda ev: self.UI.moveSelection((0, 1)))
        self.UI.bind("<Right>", lambda ev: self.UI.moveSelection((1, 0)))
        self.UI.bind("<ButtonPress-1>", lambda ev: self.UI.onMouseClick(ev))

        self.UI.bind("l", self.onLoadMatch)
        self.UI.bind("k", self.onLoadTurn)
        self.UI.bind("o", self.onReloadPlayer)
        self.UI.bind("p", self.onSwapPlayer)
        
        self.UI.bind("t", self.onEditTurn)
        self.UI.bind("f", self.onAddTeammate)
        self.UI.bind("e", self.onAddEnemy)
        self.UI.bind("r", self.onRemove)
        self.UI.bind("c", self.onClear)
        self.UI.bind("<Delete>", self.onRemove)
        self.UI.bind("<BackSpace>", self.onRemove)
        self.UI.bind("h", self.onEditHP)
        self.UI.bind("<space>", self.onShowActions)
        self.UI.bind("<Return>", self.onSimulate)

        self.UI.run()

    def onReloadPlayer(self, event):
        self.UI.fadeActions()
        self.cached_actions = None
        self.code = open(self.p1_path).read()
        self.code2 = open(self.p2_path).read()
        self.player = Player(self.code)
        self.player.set_player_id(1)
        self.player2 = Player(self.code2)
        self.player2.set_player_id(0)

    def onSwapPlayer(self, event):
        self.p1_path, self.p2_path = self.p2_path, self.p1_path
        
    def onLoadMatch(self, event):
        self.match_id = tkSimpleDialog.askinteger(
            "Load match", "Enter match number", 
            parent = self.UI.root, 
            initialvalue = 2588548,
            minvalue = 1,
            maxvalue = 99999999
        )
        if self.match_id is not None:
            self.moves = getrgmatch.get_match_result(self.match_id)
            self.loadBotsfromTurn(1)
 
    def onLoadTurn(self, event):
        if self.match_id is not None:
            new_turn = tkSimpleDialog.askinteger(
                "Edit turn", "Enter new turn", 
                parent = self.UI.root, 
                initialvalue = self.state.turn,
                minvalue = 1,
                maxvalue = 100
            )
            if new_turn is not None:
                self.loadBotsfromTurn(new_turn)
 
    def loadBotsfromTurn (self, new_turn):
        if self.match_id is not None:
            self.UI.clearActions()
            self.UI.clearBots()
            self.cached_actions = None
            self.state = GameState(self.settings)
            for bot in self.moves[new_turn]:
                loc = tuple(bot['location'])
                # print bot
                self.state.add_robot(loc, bot['player_id'])
                self.state.robots[loc].hp = bot['hp']
                self.UI.renderBot(loc, bot['hp'], bot['player_id'])
                
            self.UI.setTurn(new_turn)
            self.state.turn = new_turn
       
        
    def onEditTurn(self, event):
        new_turn = tkSimpleDialog.askinteger(
            "Edit turn", "Enter new turn", 
            parent = self.UI.root, 
            initialvalue = self.state.turn,
            minvalue = 1,
            maxvalue = 100
        )
        if new_turn is not None:
            self.UI.fadeActions()
            self.cached_actions = None
            self.UI.setTurn(new_turn)
            self.state.turn = new_turn

    def onRemove(self, event):
        if self.state.is_robot(self.UI.selection):
            self.UI.fadeActions()
            self.cached_actions = None
            self.state.remove_robot(self.UI.selection)
            self.UI.renderEmpty(self.UI.selection)

    def onAddTeammate(self, event):
        self.UI.fadeActions()
        self.cached_actions = None
        if self.state.is_robot(self.UI.selection):
            self.state.remove_robot(self.UI.selection)

        self.state.add_robot(self.UI.selection, 1)
        self.UI.renderBot(self.UI.selection, 50, 1)

    def onAddEnemy(self, event):
        self.UI.fadeActions()
        self.cached_actions = None
        if self.state.is_robot(self.UI.selection):
            self.state.remove_robot(self.UI.selection)

        self.state.add_robot(self.UI.selection, 0)
        self.UI.renderBot(self.UI.selection, 50, 0)

    def onEditHP(self, event):
        if self.state.is_robot(self.UI.selection):
            robot = self.state.robots[self.UI.selection]
            self.UI.fadeActions()
            self.cached_actions = None
            new_hp = tkSimpleDialog.askinteger(
                "Edit hp", "Enter new hp", 
                parent = self.UI.root, 
                initialvalue = robot.hp,
                minvalue = 1,
                maxvalue = 50
            )
            if new_hp is not None:
                robot.hp = new_hp
                self.UI.renderBot(self.UI.selection, new_hp, robot.player_id)

    def getActions(self):
        actions = self.player.get_actions(self.state, 0)
        actions2 = self.player2.get_actions(self.state, 0)
        actions.update(actions2)

        return actions

    def onClear(self, event):
        self.UI.clearActions()
        self.UI.clearBots()
        self.cached_actions = None
        self.state = GameState(self.settings)

    def onShowActions(self, event):
        self.player.reload()
        self.player2.reload()
        self.UI.clearActions()
        actions = self.getActions()
        self.cached_actions = actions

        for loc, action in actions.iteritems():
            self.UI.renderAction(loc, action)

    def onSimulate(self, event):
        self.UI.clearActions()
        self.UI.clearBots()
        if self.cached_actions is None:
            actions = self.getActions()
        else:
            actions = self.cached_actions

        self.state = self.state.apply_actions(actions, spawn=False)

        for loc, robot in self.state.robots.iteritems():
            self.UI.renderBot(loc, robot.hp, robot.player_id)

        self.cached_actions = None
        self.UI.setTurn(self.state.turn)
예제 #9
0
class Simulator:
    def __init__(self, player1_path, player2_path):
        self.match_id = None

        self.player = Player(player1_path) if player1_path else None
        if self.player:
            self.player1_path = player1_path
            self.player.set_player_id(1)

        self.player2 = Player(player2_path) if player2_path else None
        if self.player2:
            self.player2_path = player2_path
            self.player2.set_player_id(0)

        self.turn_repeat = False

        self.UI = SimulatorUI(settings)
        self.UI.setTitle("Robot Game Simulator")

        self.state = GameState(settings, turn=1)
        self.cached_actions = None
        self.human_actions = {}

        self.UI.setTurn(self.state.turn)

        self.UI.bind("w", lambda ev: self.UI.moveSelection((0, -1)))
        self.UI.bind("a", lambda ev: self.UI.moveSelection((-1, 0)))
        self.UI.bind("s", lambda ev: self.UI.moveSelection((0, 1)))
        self.UI.bind("d", lambda ev: self.UI.moveSelection((1, 0)))
        self.UI.bind("<Up>", lambda ev: self.UI.moveSelection((0, -1)))
        self.UI.bind("<Left>", lambda ev: self.UI.moveSelection((-1, 0)))
        self.UI.bind("<Down>", lambda ev: self.UI.moveSelection((0, 1)))
        self.UI.bind("<Right>", lambda ev: self.UI.moveSelection((1, 0)))
        self.UI.bind("<ButtonPress-1>", lambda ev: self.UI.onMouseClick(ev))

        self.UI.bind("l", self.onLoadMatch)
        self.UI.bind("k", self.onLoadTurn)
        self.UI.bind("o", self.onReloadPlayer)
        self.UI.bind("p", self.onSwapPlayer)

        self.UI.bind("t", self.onEditTurn)
        self.UI.bind("f", self.onAddTeammate)
        self.UI.bind("e", self.onAddEnemy)
        self.UI.bind("r", self.onRemove)
        self.UI.bind("c", self.onClear)
        self.UI.bind("<Delete>", self.onRemove)
        self.UI.bind("<BackSpace>", self.onRemove)
        self.UI.bind("h", self.onEditHP)
        self.UI.bind("<space>", self.onShowActions)
        self.UI.bind("<Return>", self.onSimulate)
        self.UI.bind("n", self.onNextAction)
        self.UI.bind("g", self.onSpawnRobots)

        self.UI.run()

    def onReloadPlayer(self, event):
        self.UI.fadeActions()
        self.cached_actions = None
        self.human_actions = {}
        if self.player:
            self.player = Player(self.player1_path)
            self.player.set_player_id(1)
        if self.player2:
            self.player2 = Player(self.player2_path)
            self.player2.set_player_id(0)

    def onSwapPlayer(self, event):
        self.UI.clearActions()
        self.UI.clearBots()
        self.onReloadPlayer(None)
        for loc, robot in self.state.robots.iteritems():
            self.state.robots[loc]["player_id"] = 1 - self.state.robots[loc]["player_id"]
            self.UI.renderBot(loc, robot.hp, robot.player_id)

    def onLoadMatch(self, event):
        self.match_id = tkSimpleDialog.askinteger(
            "Load match", "Enter match number",
            parent = self.UI.root,
            initialvalue = 2588548,
            minvalue = 1,
            maxvalue = 99999999
        )
        if self.match_id is not None:
            self.moves = getrgmatch.get_match_result(self.match_id)
            self.loadBotsfromTurn(1)

    def onLoadTurn(self, event):
        if self.match_id is not None:
            new_turn = tkSimpleDialog.askinteger(
                "Edit turn", "Enter new turn",
                parent = self.UI.root,
                initialvalue = self.state.turn,
                minvalue = 1,
                maxvalue = 100
            )
            if new_turn is not None:
                self.loadBotsfromTurn(new_turn)

    def loadBotsfromTurn(self, new_turn):
        if self.match_id is not None:
            self.UI.clearActions()
            self.UI.clearBots()
            self.cached_actions = None
            self.human_actions = {}
            self.state = GameState()
            for bot in self.moves[new_turn]:
                loc = tuple(bot['location'])
                # print bot
                self.state.add_robot(loc, bot['player_id'])
                self.state.robots[loc].hp = bot['hp']
                self.UI.renderBot(loc, bot['hp'], bot['player_id'])

            self.UI.setTurn(new_turn)
            self.state.turn = new_turn

    def onEditTurn(self, event):
        new_turn = tkSimpleDialog.askinteger(
            "Edit turn", "Enter new turn",
            parent = self.UI.root,
            initialvalue = self.state.turn,
            minvalue = 1,
            maxvalue = 100
        )
        if new_turn is not None:
            self.UI.fadeActions()
            self.cached_actions = None
            self.human_actions = {}
            self.UI.setTurn(new_turn)
            self.state.turn = new_turn

    def onRemove(self, event):
        self._removeRobot(self.UI.selection)

    def _removeRobot(self, loc):
        if self.state.is_robot(loc):
            self.UI.fadeActions()
            self.cached_actions = None
            if loc in self.human_actions:
                del self.human_actions[loc]
            self.state.remove_robot(loc)
            self.UI.renderEmpty(loc)

    def onAddTeammate(self, event):
        self._addRobot(1, self.UI.selection)

    def onAddEnemy(self, event):
        self._addRobot(0, self.UI.selection)

    def _addRobot(self, player_id, loc):
        self.UI.fadeActions()
        self.cached_actions = None
        if self.state.is_robot(loc):
            self.state.remove_robot(loc)
            if loc in self.human_actions:
                del self.human_actions[loc]

        self.state.add_robot(loc, player_id)
        self.UI.renderBot(loc, 50, player_id)

    def onEditHP(self, event):
        if self.state.is_robot(self.UI.selection):
            robot = self.state.robots[self.UI.selection]
            self.UI.fadeActions()
            self.cached_actions = None
            new_hp = tkSimpleDialog.askinteger(
                "Edit hp", "Enter new hp",
                parent = self.UI.root,
                initialvalue = robot.hp,
                minvalue = 1,
                maxvalue = 50
            )
            if new_hp is not None:
                robot.hp = new_hp
                self.UI.renderBot(self.UI.selection, new_hp, robot.player_id)

    def getActions(self):
        def getPlayerActions(player, player_id):
            if player:
                actions, _ = player.get_responses(self.state, player_id)
            else:
                actions = {}
            for loc, robot in self.state.robots.iteritems():
                if robot.player_id == player_id:
                    action = self.human_actions.get(loc)
                    if action or loc not in actions:
                        actions[loc] = action if action else ('guard',)
            return actions
        actions = getPlayerActions(self.player, 1)
        actions.update(getPlayerActions(self.player2, 0))
        return actions

    def onClear(self, event):
        self.UI.clearActions()
        self.UI.clearBots()
        self.cached_actions = None
        self.human_actions = {}
        self.state = GameState(turn=self.state.turn)

    def onShowActions(self, event):
        if self.state.turn < 100:
            # the following is needed since if the turn does not change,
            # non-stateless bots behave differently
            if self.player and self.turn_repeat:
                self.player = Player(self.player1_path)
                self.player.set_player_id(1)
            if self.player2 and self.turn_repeat:
                self.player2 = Player(self.player2_path)
                self.player2.set_player_id(0)
            self.UI.clearActions()
            actions = self.getActions()
            self.cached_actions = actions

            for loc, action in actions.iteritems():
                self.UI.renderAction(loc, action)

            self.turn_repeat = True

            try:
                rgsim_text = self.player._module.rgsim_text
                for loc, text in rgsim_text.iteritems():
                    self.UI.renderText(loc, text)

            except AttributeError:
                print "No rgsim_text dict found for player 1, skipping..."
            except:
                print ("Error in rgsim_text dict, please ensure keys are " +
                       "valid locations and values are strings")

    def onSimulate(self, event):
        if self.state.turn < 100:
            self.UI.clearActions()
            self.UI.clearBots()
            if self.cached_actions is None:
                actions = self.getActions()
            else:
                actions = self.cached_actions

            self.state = self.state.apply_actions(actions, spawn=False)

            for loc, robot in self.state.robots.iteritems():
                self.UI.renderBot(loc, robot.hp, robot.player_id)

            self.cached_actions = None
            self.human_actions = {}
            self.UI.setTurn(self.state.turn)
            self.turn_repeat = False

    def onNextAction(self, event):
        if not self.state.is_robot(self.UI.selection):
            return
        robot = self.state.robots[self.UI.selection]
        action = self.human_actions.get(self.UI.selection)
        if action is None and self.cached_actions is not None:
            action = self.cached_actions.get(self.UI.selection)
        if action is None:
            action = ('guard',)
        x, y = self.UI.selection
        adjacent_locs = ((x, y-1), (x+1, y), (x, y+1), (x-1, y))
        move_locs = [l for l in adjacent_locs if l not in settings.obstacles]
        all_actions = [('guard',)]
        all_actions += [('move', loc) for loc in move_locs]
        all_actions += [('attack', loc) for loc in adjacent_locs]
        all_actions += [('suicide',)]
        i = (all_actions.index(action) + 1) % len(all_actions)
        action = all_actions[i]
        if self.cached_actions is not None:
            self.cached_actions[self.UI.selection] = action
        self.human_actions[self.UI.selection] = action
        self.UI.clearAction(self.UI.selection)
        self.UI.renderAction(self.UI.selection, action)

    def onSpawnRobots(self, event):
        all_locs = self.state._get_spawn_locations()
        for loc in settings.spawn_coords:
            self._removeRobot(loc)
        for i, loc in enumerate(all_locs):
            player_id = i // settings.spawn_per_player
            self._addRobot(player_id, loc)
예제 #10
0
class Simulator:
	def __init__(self, settings, player, player2):
		self.settings = settings
		self.player = player
		self.player2 = player2
		self.UI = SimulatorUI(settings)
		self.UI.setTitle("Robot Game Simulator")

		self.robots = []
		self.cached_actions = None
		self.field = game.Field(settings.board_size)
		self.robot_id = 0

		self.turn = 1
		self.UI.setTurn(self.turn)

		self.UI.bind("w", lambda ev: self.UI.moveSelection((0, -1)))
		self.UI.bind("a", lambda ev: self.UI.moveSelection((-1, 0)))
		self.UI.bind("s", lambda ev: self.UI.moveSelection((0, 1)))
		self.UI.bind("d", lambda ev: self.UI.moveSelection((1, 0)))
		self.UI.bind("<Up>", lambda ev: self.UI.moveSelection((0, -1)))
		self.UI.bind("<Left>", lambda ev: self.UI.moveSelection((-1, 0)))
		self.UI.bind("<Down>", lambda ev: self.UI.moveSelection((0, 1)))
		self.UI.bind("<Right>", lambda ev: self.UI.moveSelection((1, 0)))

		self.UI.bind("t", self.onEditTurn)
		self.UI.bind("f", self.onAddTeammate)
		self.UI.bind("e", self.onAddEnemy)
		self.UI.bind("r", self.onRemove)
		self.UI.bind("c", self.onClear)
		self.UI.bind("<Delete>", self.onRemove)
		self.UI.bind("<BackSpace>", self.onRemove)
		self.UI.bind("h", self.onEditHP)
		self.UI.bind("<space>", self.onShowActions)
		self.UI.bind("<Return>", self.onSimulate)

		self.UI.run()

	def onEditTurn(self, event):
		new_turn = tkSimpleDialog.askinteger(
			"Edit turn", "Enter new turn", 
			parent = self.UI.root, 
			initialvalue = self.turn,
			minvalue = 1,
			maxvalue = 100
		)
		if new_turn is not None:
			self.UI.fadeActions()
			self.cached_actions = None
			self.UI.setTurn(new_turn)
			self.turn = new_turn

	def onRemove(self, event):
		if self.getRobot(self.UI.selection) is not None:
			self.UI.fadeActions()
			self.cached_actions = None
			self.removeRobot(self.UI.selection)
			self.UI.renderEmpty(self.UI.selection)

	def onAddTeammate(self, event):
		self.UI.fadeActions()
		self.cached_actions = None
		if self.getRobot(self.UI.selection) is not None:
			self.removeRobot(self.UI.selection)

		self.addRobot(self.UI.selection, 1)
		self.UI.renderBot(self.UI.selection, 50, 1)

	def onAddEnemy(self, event):
		self.UI.fadeActions()
		self.cached_actions = None
		if self.getRobot(self.UI.selection) is not None:
			self.removeRobot(self.UI.selection)

		self.addRobot(self.UI.selection, 0)
		self.UI.renderBot(self.UI.selection, 50, 0)

	def onEditHP(self, event):
		robot = self.getRobot(self.UI.selection)
		if robot is not None:
			self.UI.fadeActions()
			self.cached_actions = None
			new_hp = tkSimpleDialog.askinteger(
				"Edit hp", "Enter new hp", 
				parent = self.UI.root, 
				initialvalue = robot.hp,
				minvalue = 1,
				maxvalue = 50
			)
			if new_hp is not None:
				robot.hp = new_hp
				self.UI.renderBot(self.UI.selection, new_hp, robot.player_id)

	def getRobotID(self):
		ret = self.robot_id
		self.robot_id += 1
		return ret

	def removeRobot(self, loc):
		self.robots.remove(self.field[loc])
		self.field[loc] = None

	def getRobot(self, loc):
		return self.field[loc]

	def addRobot(self, loc, player_id):
		robot_id = self.getRobotID()
		robot = game.InternalRobot(loc, self.settings.robot_hp, player_id, robot_id, self.field)
		self.robots.append(robot)
		self.field[loc] = robot

	def buildGameInfo(self):
		return AttrDict({
			'robots': dict((
				y.location,
				AttrDict(dict(
					(x, getattr(y, x)) for x in
					(self.settings.exposed_properties + self.settings.player_only_properties)
				))
			) for y in self.robots),
			'turn': self.turn,
		})

	def getActions(self):
		self.player._robot = None
		if self.player2 is not None:
			self.player2._robot = None
		game_info = self.buildGameInfo()
		actions = {}

		for robot in self.robots:
			if robot.player_id == 1:
				robot_player = self.player
			else:
				if self.player2 is not None:
					robot_player = self.player2
				else:
					# Don't act
					actions[robot] = ['guard']
					continue

			user_robot = robot_player.get_robot()
			for prop in self.settings.exposed_properties + self.settings.player_only_properties:
				setattr(user_robot, prop, getattr(robot, prop))
			try:
				next_action = user_robot.act(game_info)
				if not robot.is_valid_action(next_action):
					raise Exception('Bot %d: %s is not a valid action from %s' % (robot.player_id + 1, str(next_action), robot.location))
			except Exception:
				traceback.print_exc(file = sys.stdout)
				next_action = ['guard']
			actions[robot] = next_action

		return actions

	def remove_dead(self):
	    to_remove = [x for x in self.robots if x.hp <= 0]
	    for robot in to_remove:
	        self.robots.remove(robot)
	        if self.field[robot.location] == robot:
	            self.field[robot.location] = None
	            self.UI.renderEmpty(robot.location)

	def onClear(self, event):
		self.UI.clearActions()
		self.cached_actions = None
		locations = [robot.location for robot in self.robots]
		self.robots = []
		for loc in locations:
			self.field[loc] = None
			self.UI.renderEmpty(loc)

	def onShowActions(self, event):
		self.UI.clearActions()
		actions = self.getActions()
		self.cached_actions = actions

		for robot, action in actions.items():
			self.UI.renderAction(robot.location, action)

	def applyActions(self, actions):
		commands = list(self.settings.valid_commands)
		commands.remove('guard')
		commands.remove('move')
		commands.insert(0, 'move')

		#this cmd iteration is needed for action priority
		for cmd in commands:
			for robot, action in actions.iteritems():
				if action[0] != cmd:
					continue

				old_loc = robot.location
				try:
					robot.issue_command(action, actions)
				except Exception:
					traceback.print_exc(file=sys.stdout)
					actions[robot] = ['guard']
				if robot.location != old_loc:
					if self.field[old_loc] is robot:
						self.field[old_loc] = None
						self.UI.renderEmpty(old_loc)
					self.field[robot.location] = robot

	def onSimulate(self, event):
		self.UI.clearActions()
		if self.cached_actions is None:
			actions = self.getActions()
		else:
			actions = self.cached_actions

		self.applyActions(actions)

		for robot, action in actions.items():
			self.UI.renderAction(robot.location, action)
			self.UI.renderBot(robot.location, robot.hp, robot.player_id)

		self.remove_dead()
		self.cached_actions = None
		self.turn += 1
		self.UI.setTurn(self.turn)