Beispiel #1
0
    def __init__(self, num_of_rows=7, num_of_cols=7):
        self.current_player = PLAYER
        self.num_of_rows = num_of_rows
        self.num_of_cols = num_of_cols
        self.board_fields = []
        self.player_positions = [-1, -1]
        self.best_direction_to_go = -1
        self.best_num_of_steps = -1

        ai_player_x = 0
        ai_player_y = self.num_of_cols // 2

        player_x = self.num_of_rows - 1
        player_y = self.num_of_cols // 2

        print(ai_player_x, ai_player_y, player_x, player_y)
        for i in range(num_of_rows):

            for j in range(num_of_cols):

                if i == ai_player_x and j == ai_player_y:

                    self.player_positions[0] = len(self.board_fields)
                    self.board_fields.append(
                        Field(ai_player_x, ai_player_y, AI_PLAYER, True))

                elif i == player_x and j == player_y:

                    self.player_positions[1] = len(self.board_fields)
                    self.board_fields.append(
                        Field(player_x, player_y, PLAYER, True))

                else:

                    self.board_fields.append(Field(i, j))
    def __init__(self):
        self.time_per_move = -1
        self.timebank = -1
        self.last_update = None
        self.max_rounds = -1

        self.round = 0
        self.player_names = []
        self.players = {}
        self.me = None
        self.opponent = None
        self.field = Field()
Beispiel #3
0
def read_field(lines, symbol_by_cell):
    # read size
    x_size, y_size = map(int, lines[0].split())

    # read field
    field = [[None] * y_size for _ in range(x_size)]

    read_cells(field, lines, symbol_by_cell, x_size, y_size)

    walls = read_walls(lines, x_size, y_size)

    return Field(field, walls, has_key=symbol_by_cell.get(Key().to_symbol(), None) is not None)
Beispiel #4
0
def generate_field(x_size, y_size):
    cells = [[Empty() for _ in range(y_size)] for _ in range(x_size)]
    vertical_walls = [[True for _ in range(y_size)] for _ in range(x_size)]
    horizontal_walls = [[True for _ in range(y_size)] for _ in range(x_size)]
    field = Field(cells, (vertical_walls, horizontal_walls), has_key=False)
    game_field = GameField(field)

    generate_walls(game_field)

    config = GenerationConfig(x_size, y_size)

    exit_direction = calc_random_direction()
    for exit_count in range(config.max_exits_on_map):
        random_put_cell_on(field,
                           Exit(exit_direction),
                           wall_required_at=exit_direction)
        random_put_cell_on(field, Key())

    teleport_counter = 0
    for _ in range(config.random_cell_count):
        random_cell_type = calc_random_cell_type()
        if teleport_counter == config.max_teleport_count:
            while random_cell_type is Teleport:
                random_cell_type = calc_random_cell_type()
        if random_cell_type is Stun:
            random_put_cell_on(field, Stun(config.default_stun_duration))
        elif random_cell_type is RubberRoom:
            random_direction = calc_random_direction()
            random_put_cell_on(field,
                               RubberRoom(random_direction),
                               without_wall_at_direction=random_direction)
        elif random_cell_type is Teleport:
            teleport_counter += 1
            random_put_cell_on(
                field, Teleport(calc_random_position_on(field).as_tuple()))

    while fix_bad_rubber_room(game_field):
        pass

    return game_field.field
Beispiel #5
0
def UCTPlayGame(nn, nn2=None):
    """ Self-play using MCTS, returns s_t's, pi_t's, and z to use for training.
    """
    width = config.board_width
    height = config.board_height
    cells_each_player = config.cells_each_player

    field = Field()
    field.width = width
    field.height = height
    field.parse(init_cells(field.width, field.width, cells_each_player))
    state = GOLADState(field)

    data = {}
    data['s'] = []
    data['pi'] = []
    c = None
    current_nn = nn  # use nn for first player
    while (state.GetMoves() != []):
        c, pi = UCT(rootstate=state,
                    itermax=config.mcts_itermax,
                    nn=current_nn,
                    verbose=config.verbose,
                    rootnode=c)
        m = c.move
        data['s'].append(state.Convert())
        data['pi'].append(pi)
        if config.verbose:
            print ("\nTurn {}, Player {}, Best Move: {}" \
                .format(state.timestep, state.current_player, str(m)))
            state.field.pprint()
        state.DoMove(m)
        if nn2 is not None:
            if current_nn == nn:
                current_nn = nn2
            else:
                current_nn = nn

    if config.verbose:
        print('Result: {}'.format(state.GetResult(0)))
        state.field.pprint()
    data['z'] = [[state.GetResult(0)]] * len(
        data['s'])  # get result from perspective of first player (ie rootnode)

    return data
Beispiel #6
0
    def test_Field_getUnknownTile(self):

        field = Field(100,100)
        tile = field.getTile(1,2)
        self.assertIsNotNone(tile)
Beispiel #7
0
    def test_Field_setTile(self):

        field = Field(100, 100)
        tile = Tile()
        field.setTile(3,4, tile)
        self.assertEqual(tile, field.getTile(3, 4))
class Game:
    def __init__(self):
        self.time_per_move = -1
        self.timebank = -1
        self.last_update = None
        self.max_rounds = -1

        self.round = 0
        self.player_names = []
        self.players = {}
        self.me = None
        self.opponent = None
        self.field = Field()

    def update(self, data):
        # start timer
        self.last_update = time.time()
        for line in data.split('\n'):

            line = line.strip()
            if len(line) <= 0:
                continue

            tokens = line.split()
            if tokens[0] == "settings":
                self.parse_settings(tokens[1], tokens[2])
            elif tokens[0] == "update":
                if tokens[1] == "game":
                    self.parse_game_updates(tokens[2], tokens[3])
                else:
                    self.parse_player_updates(tokens[1], tokens[2], tokens[3])
            elif tokens[0] == "action":
                self.timebank = int(tokens[2])
                # Launching bot logic happens after setup finishes

    def parse_settings(self, key, value):
        if key == "timebank":
            self.timebank = int(value)
        elif key == "time_per_move":
            self.time_per_move = int(value)
        elif key == "player_names":
            self.player_names = value.split(',')
            self.players = {name: Player(name) for name in self.player_names}
        elif key == "your_bot":
            self.me = self.players[value]
            self.opponent = self.players[[name for name in self.player_names if name != value][0]]
        elif key == "your_botid":
            self.me.id = value
            self.opponent.id = str(2 - (int(value) + 1))
        elif key == "field_width":
            self.field.width = int(value)
        elif key == "field_height":
            self.field.height = int(value)
        elif key == "max_rounds":
            self.max_rounds = int(value)
        else:
            stderr.write('Cannot parse settings input with key {}'.format(key))

    def parse_game_updates(self, key, value):
        if key == "round":
            self.round = int(value)
        elif key == "field":
            self.field.parse(value)
        else:
            stderr.write('Cannot parse game update with key {}'.format(key))

    def parse_player_updates(self, player_name, key, value):
        player = self.players.get(player_name)

        if player is None:
            stderr.write('Cannot find player with name {}'.format(player_name))
            return

        if key == "living_cells":
            player.living_cells = int(value)
        elif key == "move":
            player.previous_move = value
        else:
            stderr.write('Cannot parse {} update with key {}'.format(player_name, key))

    def time_remaining(self):
        return self.timebank - int(1000 * (time.clock() - self.last_update))

    @staticmethod
    def print_move(move):
        """issue an order"""
        stdout.write('{}\n'.format(move))
        stdout.flush()

    def run(self, bot):
        """parse input, update game state and call the bot classes do_turn method"""
        not_finished = True
        data = ''

        while not stdin.closed and not_finished:
            try:
                current_line = stdin.readline().rstrip('\r\n')

                if len(current_line) <= 0:
                    time.sleep(1)
                    continue

                data += current_line + "\n"
                if current_line.lower().startswith("action"):
                    self.update(data)

                    move = bot.make_move(self)
                    self.print_move(move)

                    data = ''
                elif current_line.lower().startswith("quit"):
                    not_finished = False
            except EOFError:
                break
            except KeyboardInterrupt:
                raise
            except:
                # don't raise error or return so that bot attempts to stay alive
                traceback.print_exc(file=stderr)
                stderr.flush()
Beispiel #9
0
arguments, setting = gf.create_arguments(arguments, sys.argv[1:], setting)

itteration = 1
map = np.array([[0 for _ in range(setting.width // setting.pixel_size)]
                for _ in range(setting.height // setting.pixel_size)])

trees = gf.create_trees(arguments, setting, map)
if not arguments['non_gui']:
    delay = 0
    pygame.font.init()
    pygame.init()

    screen = pygame.display.set_mode(
        (setting.width, setting.height))  # создание экрана
    field = Field(screen, setting)
    dashboard = Dashboard(screen, setting)
    dashboard.switches[0].pressed = arguments['step_mode']
    next_step = False

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

            for button in dashboard.buttons:  # отработка нажатий кнопок и выключателей
                button.button_down(event)
            for switcher in dashboard.switches:
                switcher.press(event)

            if event.type == pygame.KEYDOWN:  # следующий шаг в step mode при нажатии пробела или стрелки