Пример #1
0
def main():
    if len(sys.argv) == 2:
        map_name = sys.argv[1]
    else:
        exit(1)
    map_file = open(map_name, 'r')

    # ввод данных
    map_data = map_file.read()
    links = re.findall('\w+-\w+', map_data)
    rooms = re.findall('\w+ \d+ \d+', map_data)
    paths = re.findall('(L.*?)\n', map_data)
    print(paths)

    # парсинг данных на узлы, ребра и перемещения за каждый шаг
    rooms_dict = {}
    links_list = []
    for room in rooms:
        buf = room.split(' ')
        rooms_dict[buf[0]] = (Room(buf[0],
                                   int(buf[1]) * ZOOM,
                                   int(buf[2]) * ZOOM, NODE_SIZE))
        print(buf[0], buf[1], buf[2])
    for link in links:
        buf = link.split('-')
        if not buf[0].startswith('L'):
            line = Link(None, None)
            for room in rooms_dict:
                room = rooms_dict[room]
                if room.name == buf[0]:
                    line.start = room
                elif room.name == buf[1]:
                    line.end = room
            links_list.append(line)

    start_room = re.findall('##start\n(\w+)', map_data)[0].split('\n')[0]

    moves_list = []
    moved_ants = set()
    for path in paths:
        move_per_ant = ' ' + path
        move_per_ant = move_per_ant.split(' L')
        moves = {}
        for ant_move in move_per_ant:
            if ant_move != '':
                ant_move = ant_move.split('-')
                if not ant_move[0] in moved_ants:
                    moved_ants.add(ant_move[0])
                    moves[ant_move[0]] = Move(rooms_dict[start_room],
                                              rooms_dict[ant_move[1]],
                                              ant_move[0])
                else:
                    previous_ant_move = moves_list[-1][ant_move[0]]
                    moves[ant_move[0]] = Move(previous_ant_move.end,
                                              rooms_dict[ant_move[1]],
                                              ant_move[0])
        moves_list.append(moves)

    game = Game(links_list, moves_list)
    game.run()
Пример #2
0
 def possible_moves(self, gamestate):
     moves = []
     for factory_idx, factory in enumerate(gamestate.factories):
         for tile in set(factory):
             for line_idx in range(-1, 5):
                 move = Move(factory_idx, tile, line_idx)
                 if gamestate.is_valid_move(move, gamestate.next_player):
                     moves.append(move)
     for tile in set([t for t in gamestate.center if t != Tile.white]):
         for line_idx in range(-1, 5):
             move = Move(-1, tile, line_idx)
             if gamestate.is_valid_move(move, gamestate.next_player):
                 moves.append(move)
     return moves
Пример #3
0
    def get_next_move(self, config, player, possible_moves):
        while True:
            print("Choose which piece to move and where to (x1 y1 x2 y2).")
            print("Or type `exit` to resign:")
            line = input()

            if line == 'exit':
                return None

            try:
                from_row, from_column, to_row, to_column = map(
                    int, line.split())
            except ValueError:
                print("Invalid input")
                continue

            from_position = (from_row, from_column)
            to_position = (to_row, to_column)

            move = Move(player, from_position, to_position)

            if move not in possible_moves:
                print("Invalid move")
                continue

            return move
Пример #4
0
def add_moves(move_data):
    """Seed moves from csv to database"""

    print("Moves")

    Move.query.delete()

    for row in open(move_data):
        row = row.rstrip()
        row = row.split(",")
        move_code = row[0]
        type_code = row[1]
        move_name = row[2]
        beats = row[3]
        follows_move = row[6]
        leads_move = row[7]
        same_side = row[8]

        move = Move(move_code=move_code,
                    type_code=type_code,
                    move_name=move_name,
                    beats=beats,
                    follows_move=follows_move,
                    leads_move=leads_move,
                    same_side=same_side)

        db.session.add(move)

    db.session.commit()
Пример #5
0
def find_deadlocks(state: State) -> Iterable[Pos]:
    """Find non-goal boxes that are deadlock by other boxes, e.g. two boxes
	being next to each other against a wall, or clusters of four boxes.
	"""
    occupied = state.boxes | state.level.walls
    adjacent = [[(-1, -1), (-1, 0), (0, -1)], [(-1, 0), (-1, 1), (0, 1)],
                [(0, 1), (1, 0), (1, 1)], [(0, -1), (1, -1), (1, 0)]]
    return (box for box in state.boxes - state.level.goals if any(
        all(box.add(Move(*a)) in occupied for a in adj) for adj in adjacent))
Пример #6
0
 def selected_move(self, event, move_canvas):
     factory_idx = self.view.selected_factory()
     if factory_idx is None:
         return None
     color = self.view.selected_color(factory_idx)
     if isinstance(move_canvas, PatternLines):
         line_idx = move_canvas.clicked_row(event)
     else:
         line_idx = -1
     player = move_canvas.master.player_id
     return Move(factory_idx, tile_of_color(color), line_idx)
Пример #7
0
def parse_move(tree):
    device_log = tree.DeviceLog
    move = Move()

    add_children(move, device_log.Header)

    for child in device_log.Device.Info.iterchildren():
        tag = normalize_tag(child.tag)
        attr = "device_info_%s" % tag.lower()
        set_attr(move, attr, child.text)

    normalize_move(move)
    return move
Пример #8
0
def section3(data, x, y, *verbs):
    last_travel = data._last_travel
    if last_travel[0] == x and last_travel[1][0] == verbs[0]:
        verbs = last_travel[1]  # same first verb implies use whole list
    else:
        data._last_travel = [x, verbs]

    m, n = divmod(y, 1000)
    mh, mm = divmod(m, 100)

    if m == 0:
        condition = (None,)
    elif 0 < m < 100:
        condition = ("%", m)
    elif m == 100:
        condition = ("not_dwarf",)
    elif 100 < m <= 200:
        condition = ("carrying", mm)
    elif 200 < m <= 300:
        condition = ("carrying_or_in_room_with", mm)
    elif 300 < m:
        condition = ("prop!=", mm, mh - 3)

    if n <= 300:
        action = make_object(data.rooms, Room, n)
    elif 300 < n <= 500:
        action = n  # special computed goto
    else:
        action = make_object(data.messages, Message, n - 500)

    move = Move()
    if len(verbs) == 1 and verbs[0] == 1:
        move.is_forced = True
    else:
        move.verbs = [make_object(data.vocabulary, Word, verb_n) for verb_n in verbs if verb_n < 100]  # skip bad "109"
    move.condition = condition
    move.action = action
    data.rooms[x].travel_table.append(move)
Пример #9
0
    def handle_keys(self, event, shift=False):
        """Handle key events, e.g. or movement, save, load, undo, restart, etc.
		"""
        self.path = None
        self.selected = None
        if event.keysym == "q":
            self.master.destroy()
            return
        if event.keysym == "r":
            self.game.load_level()
        if event.keysym == "s":
            self.game.save_snapshot()
        if event.keysym == "l":
            self.game.load_snapshot()
        if event.keysym == "d":
            # TODO calculate just once, then store whether to show them in UI
            self.game.state.level.deadends = set() if self.game.state.level.deadends else \
              search.find_deadends(self.game.state.level)
        if event.keysym == "z":
            self.game.state.undo()
        if event.keysym == "y":
            self.game.state.redo()
        if event.keysym in ("Prior", "Next"):
            # TODO move logic for this to SokobanGame class
            inc = lambda num: (num + 1 if event.keysym == "Next" else num - 1
                               ) % len(self.game.levels)
            cur = inc(self.game.current)
            # shift: fast-forward to next unsolved level, if any
            while shift and self.game.scores[cur] and cur != self.game.current:
                cur = inc(cur)
            self.game.load_level(cur)
            self.draw_state(redraw_level=True)
        if event.keysym in DIRECTIONS:
            dr, dc = DIRECTIONS[event.keysym]
            if self.game.state.move(Move(dr, dc, not shift)) and shift:
                self.after(20, self.handle_keys, event, shift)
        if event.keysym == "space":
            self.path = solver.solve(self.game.state)
            self.move_path()
        if event.keysym == "period":
            self.show_reachable ^= True
        self.update_state()
Пример #10
0
def display_board(channel):

    moves = Move.query_board_moves(channel)

    moves_listed = []

    for move in sorted(moves):
        for item in move:
            moves_listed.append(item)

    print moves_listed

    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]

    #cb = current_board
    cb = []

    if not moves:
        for num in numbers:
            cb.append("   ")
    else:
        for num in numbers:
            if num in moves_listed:
                cb.append(moves_listed[1])
                moves_listed = moves_listed[2:]
            else:
                cb.append("   ")


    print cb

    board = '''
    | ''' + cb[0] + '''   | ''' + cb[1] + '''   | ''' + cb[2] + '''   |
    |---+---+---|
    | ''' + cb[3] + '''   | ''' + cb[4] + '''   | ''' + cb[5] + '''   |
    |---+---+---|
    | ''' + cb[6] + '''   | ''' + cb[7] + '''   | ''' + cb[8] + '''   |
    '''

    return board
Пример #11
0
    def get_next_move(self, config, player, possible_moves):
        pygame.event.clear()
        while True:
            self.render(config)

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    return None
                if event.type == pygame.MOUSEBUTTONDOWN:
                    x, y = event.pos

                    x = x - self.board_x
                    y = y - self.board_y

                    if ((0 < x < self.board_length)
                            and (0 < y < self.board_length)):
                        column = x // self.cell_length
                        row = y // self.cell_length

                        position = (row, column)

                        if self.selected_piece:
                            from_position = self.selected_piece
                            to_position = position

                            if config.board[row][column] != Piece.NONE:
                                self.selected_piece = position
                                continue

                            self.selected_piece = None

                            move = Move(player, from_position, to_position)

                            if move not in possible_moves:
                                continue

                            return move

                        self.selected_piece = position
Пример #12
0
 def move(self, gamestate):
     print(len(self.possible_moves(gamestate)))
     # Given the gamestate as an instance of Model, return a random Move
     possible_factories = [
         i for i in range(NUM_FACTORIES) if gamestate.factories[i]
     ]
     if len(gamestate.center) > 1 or Tile.white not in gamestate.center:
         possible_factories.append(-1)
     factory = np.random.choice(possible_factories)
     if factory == -1:
         tile = np.random.choice(
             [tile for tile in gamestate.center if tile != Tile.white])
     else:
         tile = np.random.choice(gamestate.factories[factory])
     board = gamestate.boards[gamestate.next_player]
     possible_pattern_lines = [
         i for i in range(NUM_TILES)
         if board.pattern_lines[i].open_for_tile(tile)
     ]
     possible_pattern_lines.append(-1)
     pattern_line = np.random.choice(possible_pattern_lines)
     return Move(factory, tile, pattern_line)
Пример #13
0
def section3(data, x, y, *verbs):
    last_travel = data._last_travel
    if last_travel[0] == x and last_travel[1][0] == verbs[0]:
        verbs = last_travel[1]  # same first verb implies use whole list
    else:
        data._last_travel = [x, verbs]

    m, n = divmod(y, 1000)
    mh, mm = divmod(m, 100)

    if m == 0:
        condition = (None, )
    elif 0 < m < 100:
        condition = ('%', m)
    elif m == 100:
        condition = ('not_dwarf', )
    elif 100 < m <= 200:
        condition = ('carrying', mm)
    elif 200 < m <= 300:
        condition = ('carrying_or_in_room_with', mm)
    elif 300 < m:
        condition = ('prop!=', mm, mh - 3)

    if n <= 300:
        action = make_object(data.rooms, Room, n)
    elif 300 < n <= 500:
        action = n  # special computed goto
    else:
        action = make_object(data.messages, Message, n - 500)

    move = Move()
    if len(verbs) == 1 and verbs[0] == 1:
        move.is_forced = True
    else:
        move.verbs = [
            make_object(data.vocabulary, Word, verb_n) for verb_n in verbs
            if verb_n < 100
        ]  # skip bad "109"
    move.condition = condition
    move.action = action
    data.rooms[x].travel_table.append(move)
Пример #14
0
def strava_import(current_user, activity_id):
    client = get_strava_client(current_user)
    activity = client.get_activity(activity_id=activity_id)
    stream_types = [
        'time', 'distance', 'latlng', 'temp', 'heartrate', 'velocity_smooth',
        'altitude'
    ]
    streams = client.get_activity_streams(activity_id, types=stream_types)

    activity_string = map_type(activity.type)

    result = db.session.query(
        Move.activity_type).filter(Move.activity == activity_string).first()
    if result:
        activity_type, = result
    else:
        activity_type = None

    device = find_device(current_user)

    move = Move()
    move.user = current_user
    move.duration = activity.elapsed_time
    move.ascent = float(activity.total_elevation_gain)
    move.speed_avg = float(activity.average_speed)
    move.hr_avg = heart_rate(activity.average_heartrate)
    move.temperature_avg = celcius_to_kelvin(activity.average_temp)
    move.device = device
    move.date_time = activity.start_date_local
    move.activity = activity_string
    move.activity_type = activity_type
    move.distance = float(activity.distance)
    move.import_date_time = datetime.now()
    move.import_module = __name__
    move.strava_activity_id = activity_id
    move.public = False
    move.source = "Strava activity id=%d; external_id='%s'" % (
        activity_id, activity.external_id)

    if streams:
        lengths = set([len(streams[stream].data) for stream in streams])
        assert len(lengths) == 1
        length, = lengths
    else:
        length = 0

    move.speed_max = move.speed_avg

    all_samples = []
    for i in range(0, length):
        time = timedelta(seconds=streams['time'].data[i])
        distance = float(streams['distance'].data[i])

        if 'heartrate' in streams:
            hr = float(streams['heartrate'].data[i])
        else:
            hr = None

        if 'latlng' in streams:
            lat, lng = streams['latlng'].data[i]
        else:
            lat = None
            lng = None

        if 'altitude' in streams:
            altitude = float(streams['altitude'].data[i])
        else:
            altitude = None

        if 'velocity_smooth' in streams:
            speed = float(streams['velocity_smooth'].data[i])
        else:
            speed = None

        if 'temp' in streams:
            temperature = celcius_to_kelvin(streams['temp'].data[i])
        else:
            temperature = None

        sample = Sample()
        sample.sample_type = SAMPLE_TYPE
        sample.move = move
        sample.time = time
        sample.utc = (activity.start_date + time).replace(tzinfo=None)
        sample.distance = distance
        sample.latitude = degree_to_radian(lat)
        sample.longitude = degree_to_radian(lng)
        sample.hr = heart_rate(hr)
        sample.temperature = temperature
        sample.speed = speed
        sample.altitude = altitude
        move.speed_max = max(move.speed_max, speed)
        all_samples.append(sample)

    derive_move_infos_from_samples(move, all_samples)

    db.session.add(move)
    db.session.flush()
    postprocess_move(move)
    db.session.commit()
    return move
Пример #15
0
def parse_move(tree):
    move = Move()
    move.activity = "Unknown activity"
    move.import_date_time = datetime.now()

    return move
Пример #16
0
def create_move():
    move = Move()
    move.activity = GPX_ACTIVITY_TYPE
    move.import_date_time = datetime.now()
    return move
Пример #17
0
def strava_import(current_user, activity_id):
    client = get_strava_client(current_user)
    activity = client.get_activity(activity_id=activity_id)
    stream_types = ['time', 'distance', 'latlng', 'temp', 'heartrate', 'velocity_smooth', 'altitude']
    streams = client.get_activity_streams(activity_id, types=stream_types)

    device_ids = [device_id for device_id, in db.session.query(func.distinct(Move.device_id))
        .join(User)
        .join(Device)
        .filter(Device.name != gpx_import.GPX_DEVICE_NAME)
        .filter(Move.user == current_user).all()]

    assert len(device_ids) == 1
    device_id = device_ids[0]

    device = db.session.query(Device).filter_by(id = device_id).one();

    activity_string = map_type(activity.type)

    result = db.session.query(Move.activity_type).filter(Move.activity == activity_string).first()
    if result:
        activity_type, = result
    else:
        activity_type = None

    move = Move()
    move.user = current_user
    move.duration = activity.elapsed_time
    move.ascent = float(activity.total_elevation_gain)
    move.speed_avg = float(activity.average_speed)
    move.hr_avg = heart_rate(activity.average_heartrate)
    move.temperature_avg = celcius_to_kelvin(activity.average_temp)
    move.device = device
    move.date_time = activity.start_date_local
    move.activity = activity_string
    move.activity_type = activity_type
    move.distance = float(activity.distance)
    move.import_date_time = datetime.now()
    move.import_module = __name__
    move.strava_activity_id = activity_id
    move.public = False
    move.source = "Strava activity id=%d; external_id='%s'" % (activity_id, activity.external_id)

    lengths = set([len(streams[stream].data) for stream in streams])
    assert len(lengths) == 1
    length, = lengths

    move.speed_max = move.speed_avg

    all_samples = []
    for i in range(0, length):
        time = timedelta(seconds=streams['time'].data[i])
        distance = float(streams['distance'].data[i])

        if 'heartrate' in streams:
            hr = float(streams['heartrate'].data[i])
        else:
            hr = None

        if 'latlng' in streams:
            lat, lng = streams['latlng'].data[i]
        else:
            lat = None
            lng = None

        if 'altitude' in streams:
            altitude = float(streams['altitude'].data[i])
        else:
            altitude = None

        if 'velocity_smooth' in streams:
            speed = float(streams['velocity_smooth'].data[i])
        else:
            speed = None

        if 'temp' in streams:
            temperature = celcius_to_kelvin(streams['temp'].data[i])
        else:
            temperature = None

        sample = Sample()
        sample.sample_type = SAMPLE_TYPE
        sample.move = move
        sample.time = time
        sample.utc = (activity.start_date + time).replace(tzinfo=None)
        sample.distance = distance
        sample.latitude = degree_to_radian(lat)
        sample.longitude = degree_to_radian(lng)
        sample.hr = heart_rate(hr)
        sample.temperature = temperature
        sample.speed = speed
        sample.altitude = altitude
        move.speed_max = max(move.speed_max, speed)
        all_samples.append(sample)

    derive_move_infos_from_samples(move, all_samples)

    db.session.add(move)
    db.session.commit()
    return move
Пример #18
0
Sokoban Planning Algorithms, by Tobias Küster, 2014-2017, 2020

This module provides the planning algorithms used in the Sokoban game, i.e.
everything that goes beyond simulating a simple move or push. Currently it
includes algorithms for finding the path to a certain position, for planning
how to push a box to a certain position, or for identifying "dead-end" positions
in a level. More might be added in the future.
"""

from typing import List, Set, Optional, Iterable
import collections
import heapq

from model import State, Level, Pos, Move

MOVES = [Move(dr, dc) for dr, dc in ((0, +1), (0, -1), (-1, 0), (+1, 0))]
MOVES_P = [Move(dr, dc, True) for dr, dc, _ in MOVES]


def reachable(state: State) -> Set[Pos]:
    """ Flood-fill to get all cells reachable by player in the current state
	without pushing any box.
	"""
    seen = set()
    queue = collections.deque([state.player])
    while queue:
        pos = queue.popleft()
        if pos not in seen:
            seen.add(pos)
            queue.extend(pos2 for pos2 in map(pos.add, MOVES)
                         if state.is_free(pos2))
Пример #19
0
def create_move():
    move = Move()
    move.activity = GPX_ACTIVITY_TYPE
    move.import_date_time = datetime.now()
    return move
Пример #20
0
def parse_move(tree):
    move = Move()
    add_children(move, tree.header)
    normalize_move(move)
    return move
Пример #21
0
pos_inventory = Pos(783, 119)
pos_next = Pos(728, 645)
pos_muffin = Pos(134, 482)
pos_agree = Pos(248, 661)
pos_accept = Pos(577, 661)
pos_forward = Pos(412, 485)
back = Pos(413, 641)
low_left = Pos(56, 641)
low_right = Pos(765, 641)
high_left = Pos(211, 483)
high_right = Pos(614, 483)
high_high_center = Pos(408, 129)
pos_castel = Pos(211, 128)

# Move
left = Move(high_left, back)
right = Move(high_right, back)
up_castel = Move(pos_castel, back)
forward = Move(pos_forward, back)
rotate_left = Move(low_left, low_right)
rotate_right = Move(low_right, low_left)
inventory = Move(pos_inventory, pos_inventory)

# Location
home = Location([])
field = Location([rotate_right])
tree_house = SunLocation([forward] * 4)
cake_house = SunLocation([forward, left])
boulder = Location([rotate_left, forward, forward])
vinyl_door = Location([forward, right])
apple_tree = SunLocation([rotate_left] + [forward] * 6)
Пример #22
0
 def _random_move(self):
     return Move.random()
Пример #23
0
def play_game(input, channel, user):
    """Utilizes input from slack channel to process game play"""

    if input[0] == 'play':
        if len(input) == 1:
            message = """You need to tag someone to play! \n
                        TYPE:  '/ttt play @an_awesome_person' """
            return send_message(channel, message)
        elif Channel.query_channel_game is True:
            #Querying channel to see if game in plan
            message = """Sorry game in play!
                        TYPE:" '/ttt board' to show the board! """
            return send_message(channel, message)
        else:
            Channel.link_game_channel(channel, user, input[1])
            message = """Time to play! \n
            From left to right, top to bottom the spaces are numbers 1-9
            TYPE: '/ttt move (then your number)' to make a move!"""
            return send_message(channel, message)

    elif input[0] == 'board':
        return send_message(channel, display_board(channel))

    elif input[0] == 'move':
        if input[1] is None:
            message = """Please specify space!"""
            return send_message(channel, message)
        else:
            if Move.whose_turn(channel) != user:
                message = "Not your turn!"
                return send_message(channel, message)
            elif Move.move_made(input[1], channel):
                message = "Move already made!"
                return send_message(channel, message)
            else:
                Move.create_move(channel, user, input[1])
                is_game_over = Move.game_over(channel, user)
                if (is_game_over[0] is True):
                    Move.clear_game(channel)
                    return send_message(channel, "Yay, you won!")
                else:
                    if (Move.board_full(channel) is True):
                        message = "Cat's game! Try again."
                        Move.clear_game(channel)
                        return send_message(channel, message)
                    else:
                        message = "Your turn: " + Move.whose_turn(channel)
                        send_message(channel, display_board(channel))
                        return send_message(channel, message)

    return