コード例 #1
0
 def _recon(self, shares):
     if isinstance(shares, dict):
         shares = shares.values()
     if not all(map(shares[0].__eq__, shares)):
         log.error("Inconsistent shares received in Null-scheme reconstruction")
         return None
     secret = copy.deepcopy(shares[0])
     return secret
コード例 #2
0
 def activate(self,
              board: GameBoard,
              state: GameState,
              action: Action,
              forceHit: bool = False) -> Tuple[GameState, Outcome]:
     """Apply the step method to a deepcopy of the given GameState."""
     s1 = deepcopy(state)
     outcome = self.step(board, s1, action, forceHit)
     return s1, outcome
コード例 #3
0
    def reset(self) -> None:
        """Restore the match to its original (before initialization) stage."""
        self.state: GameState = deepcopy(self.origin)

        self.actions_history = []
        self.outcome = []

        self.winner = ''
        self.end = False
        self.update = False

        self._goInit()
コード例 #4
0
    def __init__(self,
                 gid: str,
                 red: Agent,
                 blue: Agent,
                 board: GameBoard = None,
                 state: GameState = None,
                 seed: int = 42,
                 useLoggers: bool = True):
        """
        Initialize the state-machine.

        :param gid:         Unique identifier.
        :param board:       Static descriptor of the game.
        :param state:       Dynamic descriptor of the game.
        :param red:         String value of the player to use. Check module agent.interactive for a list.
        :param blue:        String value of the player to use. Check module agent.interactive for a list.
        :param seed:        Random seed value (default: 42)
        """
        if useLoggers:
            self.logger = logging.getLogger(__name__)
        else:
            self.logger = logging.getLogger("internal")

        self.gid: str = gid
        self.seed: int = seed

        self.actions_history: List[Action] = []
        self.states_history: List[GameState] = []

        self.outcome: List[Outcome] = []

        self.winner: str = ''
        self.end: bool = False
        self.update: bool = False

        self.board: GameBoard = board
        self.state: GameState = state
        self.origin: GameState = deepcopy(state)

        self.gm: GameManager = GameManager()

        self.red: Agent = red
        self.blue: Agent = blue
        self.humans: bool = isinstance(self.red, Human) or isinstance(
            self.blue, Human)

        self.first = None
        self.second = None

        self.step = self._goInit
コード例 #5
0
def template_upgrade(data: dict) -> None:
    """Checks for other templates in the same dictionary, if found update the template based on another template."""
    for k in data.keys():
        if k == 'template':
            continue

        if 'template' in data[k]:
            tmpl = data[data[k]['template']]
        elif 'template' not in data:
            continue
        else:
            tmpl = data['template']

        data[k] = update(deepcopy(tmpl), data[k])
        logger.info(f'upgraded template: {k}')
コード例 #6
0
ファイル: greedy.py プロジェクト: IDSIA/NewTechnoWar
    def placeFigures(self, board: GameBoard, state: GameState) -> None:
        """
        Find the initial position for the figure where the state has the best value. The generation of the position is
        done randomly 100 times.

        :param board:   board of the game
        :param state:   the current state
        """
        # select area
        x, y = np.where(state.placement_zone[self.team] > 0)
        figures = state.getFigures(self.team)

        # choose groups of random positions
        indices = [
            np.random.choice(len(x), size=len(figures), replace=False)
            for _ in range(100)
        ]

        scores = []
        s = deepcopy(state)

        for i in range(len(indices)):
            # select a group of positions
            group = indices[i]
            for j in range(len(group)):
                # move each unit to its position
                figure = figures[j]
                dst = Hex(x[group[j]], y[group[j]]).cube()
                s.moveFigure(figure, figure.position, dst)

            score = stateScore(self.team, self.goal_params, board, s)
            scores.append((score, group))

        # choose the better group
        score, group = self.opt(scores)

        for j in range(len(group)):
            figure = figures[j]
            dst = Hex(x[group[j]], y[group[j]]).cube()
            state.moveFigure(figure, dst=dst)

        logger.info(f'{self.team:5}: placed his troops in {group} ({score})')
コード例 #7
0
    def _goResponse(self) -> None:
        """Response step."""
        self.logger.debug(
            f'{self.seed:10} step: response {self.second.team:5}')
        state0 = deepcopy(self.state)

        try:
            response = self.second.chooseResponse(self.board, self.state)
        except ValueError as e:
            self.logger.debug(
                f'{self.seed:10} {self.second.team:5} {"exception":9}: {e}')
            response = NoResponse(self.second.team)

        outcome = self.gm.step(self.board, self.state, response)

        self._store(state0, response, outcome)
        self.logger.info(
            f'{self.seed:10} {self.second.team:5} {"response":9}: {response} {outcome.comment}'
        )

        self._goCheck()
コード例 #8
0
    def _goRound(self) -> None:
        """Round step."""
        self.logger.debug(f'{self.seed:10} step: round {self.first.team:5}')
        self.update = False
        state0 = deepcopy(self.state)

        try:
            action = self.first.chooseAction(self.board, self.state)
        except ValueError as e:
            self.logger.debug(
                f'{self.seed:10} {self.first.team:5} {"exception":9}: {e}')
            action = PassTeam(self.first.team)

        outcome = self.gm.step(self.board, self.state, action)

        self._store(state0, action, outcome)
        self.logger.info(
            f'{self.seed:10} {self.first.team:5} {"action":9}: {action} {outcome.comment}'
        )

        self._goCheck()
コード例 #9
0
ファイル: greedy.py プロジェクト: IDSIA/NewTechnoWar
    def chooseFigureGroups(self, board: GameBoard, state: GameState) -> None:
        """
        Find the best color that gives the optimal score.

        :param board:   board of the game
        :param state:   the current state
        """
        colors = list(state.choices[self.team].keys())
        scores = []

        for color in colors:
            s = deepcopy(state)
            s.choose(self.team, color)

            score = stateScore(self.team, self.goal_params, board, s)
            scores.append((score, color))

        score, color = self.opt(scores)
        state.choose(self.team, color)

        logger.info(f'{self.team:5}: choose positions color {color}')
コード例 #10
0
    def chooseFigureGroups(self, board: GameBoard, state: GameState) -> None:
        """
        Plays a quick game with each color and choose the color with the best score.

        :param board:   board of the game
        :param state:   the current state
        """
        colors = list(state.choices[self.team].keys())

        max_color = None
        max_value = -math.inf

        for color in colors:
            s: GameState = deepcopy(state)
            s.choose(self.team, color)
            score, _ = self.search(board, s)

            if score > max_value:
                max_value = score
                max_color = color

        state.choose(self.team, max_color)
        logging.info(f'{self.team:5}: choose positions color {max_color}')
コード例 #11
0
 def _share(self, secret):
     return [copy.deepcopy(secret) for i in xrange(self._n)]