Ejemplo n.º 1
0
 def __init__(self, source="data/maps/first.tmx"):
     self.source = source
     self.players = 2
     self.tmxdata = TiledMap(source)
     self.map_width = self.tmxdata.width
     self.map_height = self.tmxdata.height
     self.tile_width = self.tmxdata.tilewidth
     self.tile_height = self.tmxdata.tileheight
     self.floor_list = self.get_tile_info('floor')
     self.objects_list = self.get_tile_info('items')
     self.city_list = self.get_tile_info('city')
     self.screen = r'data/maps/map_screen.png'
     self.layers = [self.floor_list, self.objects_list, self.city_list]
Ejemplo n.º 2
0
def extract_collision_objects_from_tile_layers(
        tmx_data: pytmx.TiledMap,
        collision_layer_names: List[str]) -> List[pygame.Rect]:
    collison_objects = list()

    for layer_name in collision_layer_names:
        collision_layer = tmx_data.get_layer_by_name(layer_name)
        for x in range(collision_layer.width):
            for y in range(collision_layer.height):
                image = tmx_data.get_tile_image(x, y, 1)
                if image:
                    collison_objects.append(
                        pygame.Rect(
                            x * tmx_data.tilewidth,
                            y * tmx_data.tileheight,
                            tmx_data.tilewidth,
                            tmx_data.tileheight,
                        ))
    return collison_objects
Ejemplo n.º 3
0
 def _get_player(tmx_data: pytmx.TiledMap):
     player: pytmx.TiledObject = tmx_data.get_object_by_name('player')
     size = Dimensions(27, 35)
     return Player(
         PlayerGraphicsComponent(),
         PlayerInputComponent(),
         PlayerPhysicsComponent(),
         position=Point(player.x, player.y - size.height),
         size=size
     )
Ejemplo n.º 4
0
def loadTiled(config, fPath, tiles, nCounts):
    tm = TiledMap(fPath)
    assert len(tm.layers) == 1
    layer = tm.layers[0]
    W, H = layer.width, layer.height
    tilemap = np.zeros((H, W), dtype=object)
    for w, h, dat in layer.tiles():
        f = dat[0]
        tex = f.split('/')[-1].split('.')[0]
        tilemap[h, w] = core.Tile(config, tiles[tex], h, w, nCounts, tex)
    return tilemap
Ejemplo n.º 5
0
    def _get_collisions(tmx_data: pytmx.TiledMap) -> Tuple:
        rects = []
        slopes = []

        obj: pytmx.TiledObject
        for obj in tmx_data.get_layer_by_name('collision'):
            points = getattr(obj, 'points', None)
            if points:
                slopes.append(Triangle(obj))
            else:
                rect = pygame.Rect(obj.x, obj.y, obj.width, obj.height)
                rects.append(rect)

        return tuple(rects), tuple(slopes)
Ejemplo n.º 6
0
    def __init__(self, map_name):

        self.tile_sets = {}

        tm = TiledMap(map_name)
        self.size = tm.width * tm.tilewidth, tm.height * tm.tileheight
        self.tmx_data = tm
        self.position = [0, 0]

        tile_set_name = ""

        for tile in self.tmx_data.images:
            if tile is not None:
                tile_set = tile[0]
                tile_set_name = tile_set
                if tile_set not in self.tile_sets:
                    self.tile_sets[tile_set] = load_image(tile_set)

        self.tile_set = self.tile_sets[tile_set_name]

        """
        self.blocking_elements = []

        print("Objects in map:")
        for obj in self.tmx_data.objects:
            print(obj)
            print("BLOCK\t{0}".format(obj.points))
            for k, v in obj.properties.items():
                print("PROPS\t{0}\t{1}".format(k, v))
                if (k == "block") and (v == "true"):
                    print("FOUND BLOCK")
                    self.blocking_elements.append(obj)

        print("GID (tile) properties:")
        for k, v in self.tmx_data.tile_properties.items():
            print("{0}\t{1}".format(k, v))
        """

        self.bg_surface = SDL_CreateRGBSurface(SDL_SWSURFACE,
                                               self.size[0],
                                               self.size[1],
                                               32,
                                               0x000000FF,
                                               0x0000FF00,
                                               0x00FF0000,
                                               0xFF000000)
Ejemplo n.º 7
0
    def __init__(self, level, controls):
        super().__init__()

        self.set_background_color(33/255, 46/255, 56/255)

        # set up timing system
        self.timeline = Timeline()
        self.last_time = 0.0

        def extract_tile_id(filename, flags, tileset):
            def inner(rect, flags):
                x, y, w, h = rect
                return x // w + y // h * tileset.columns
            return inner

        tile_list = tiles(self)
        tiled_map = TiledMap(level, image_loader=extract_tile_id)
        level = self.render.attach_new_node("level")
        width = tiled_map.width
        height = tiled_map.height * 3**0.5 / 2
        level.set_pos(width / 2, -height / 2, 0)

        def get_track(x, y):
            for i, layer in enumerate(tiled_map):
                tile = tile_list.get(tiled_map.get_tile_image(x, y, i))
                if isinstance(tile, Track):
                    return tile
            return None

        z = {}
        for layer in tiled_map:
            for x, y, tile_id in layer.tiles():
                if (tile_type := tile_list.get(tile_id)) is not None:
                    tile = level.attach_new_node("tile")
                    tile.set_pos(*from_hex(x, y), z.get((x, y), 0))
                    z[(x, y)] = z.get((x, y), 0) + tile_type.height
                    tile_type.instance_to(tile)
                    tile_type.register(tile, self.timeline, x, y, get_track)
Ejemplo n.º 8
0
    def __init__(self, map_name):

        self.tile_sets = {}

        tm = TiledMap(map_name)
        self.size = tm.width * tm.tilewidth, tm.height * tm.tileheight
        self.tmx_data = tm
        self.position = [0, 0]

        for tile_set in self.tmx_data.tilesets:
            name = tile_set.name
            tile_set_path = MAPS.get_path("{0}.png".format(name))
            self.tile_sets[tile_set_path] = load_image(tile_set_path)
        """
        self.blocking_elements = []

        print("Objects in map:")
        for obj in self.tmx_data.objects:
            print(obj)
            print("BLOCK\t{0}".format(obj.points))
            for k, v in obj.properties.items():
                print("PROPS\t{0}\t{1}".format(k, v))
                if (k == "block") and (v == "true"):
                    print("FOUND BLOCK")
                    self.blocking_elements.append(obj)

        print("GID (tile) properties:")
        for k, v in self.tmx_data.tile_properties.items():
            print("{0}\t{1}".format(k, v))
        """

        layers = "background", "behind", "front"
        self.surfaces = {}

        for layer in layers:
            self.surfaces[layer] = SDL_CreateRGBSurface(
                SDL_SWSURFACE, self.size[0], self.size[1], 32, 0x000000FF,
                0x0000FF00, 0x00FF0000, 0xFF000000)
Ejemplo n.º 9
0
class MyMap:
    def __init__(self, source="data/maps/first.tmx"):
        self.source = source
        self.players = 2
        self.tmxdata = TiledMap(source)
        self.map_width = self.tmxdata.width
        self.map_height = self.tmxdata.height
        self.tile_width = self.tmxdata.tilewidth
        self.tile_height = self.tmxdata.tileheight
        self.floor_list = self.get_tile_info('floor')
        self.objects_list = self.get_tile_info('items')
        self.city_list = self.get_tile_info('city')
        self.screen = r'data/maps/map_screen.png'
        self.layers = [self.floor_list, self.objects_list, self.city_list]

    def get_tile_info(self, name, scaling=config.SCALING):
        tiles_list = []
        layer = self.tmxdata.get_layer_by_name(name)
        for column_index, row_index, image in layer.tiles():
            tile = Tile()
            if row_index % 2 == 0:
                tile.x = column_index * (TILE_WIDTH * scaling)
                tile.y = (self.map_height - row_index - 1) * (
                    (TILE_HEIGHT * scaling) / 2)
            else:
                tile.x = column_index * (TILE_WIDTH * scaling) + (
                    (TILE_WIDTH * scaling) / 2)
                tile.y = (self.map_height - row_index - 1) * (
                    (TILE_HEIGHT * scaling) / 2)
            tile.coordinates = (column_index, row_index)
            tile.column_index = column_index
            tile.row_index = row_index
            tile.width = self.tile_width * scaling
            tile.height = self.tile_height * scaling + 10 * config.SCALING
            tile.image = str(image[0])
            tiles_list.append(tile)
        return tiles_list
view_clip_rect_dimensions = [view_clip_rect.width, view_clip_rect.height]

font = Font(resource_path(os.path.join("data", "AGENCYR.TTF")), 32)
fonts = [font]

background = Surface(screen_size)
# noinspection PyArgumentList
background.fill(Color(0, 0, 0, 255))
background.convert(screen)
background_texture = renderer.load_texture(background)
background_sprite = Sprite(background_texture)

sorted_sprite_list = SortableContainer((0, 0))

view_offset = [332.0, -1100.0]
tmx_data = TiledMap(resource_path(os.path.join("data", "test_map.tmx")),
                    image_loader=pygame_sdl2_image_loader)
tile_width = tmx_data.tilewidth
tile_height = tmx_data.tileheight
tile_dimensions = [tile_width, tile_height]

tile_map = []
for y in range(0, tmx_data.height):
    tile_col = []
    for x in range(0, tmx_data.width):
        layer_index = 0
        tile_layer = []
        for layer in tmx_data.visible_layers:
            y_offset = layer.offsety
            image = tmx_data.get_tile_image(y, x, layer_index)
            new_tile = None
            if image is not None:
Ejemplo n.º 11
0
 def _get_lemons(tmx_data: pytmx.TiledMap):
     obj: pytmx.TiledObject
     for obj in tmx_data.get_layer_by_name('spawns'):
         if obj.name == 'lemon':
             yield Lemon(position=Point(obj.x, obj.y))
Ejemplo n.º 12
0
def load_tmx(filename, *args, **kwargs):
    # for .14 compatibility
    from pytmx import TiledMap

    tiledmap = TiledMap(filename)
    return tiledmap
Ejemplo n.º 13
0
    def __init__(self, level, controls):
        super().__init__()

        self.set_background_color(33 / 255, 46 / 255, 56 / 255)

        # set up timing system
        self.timeline = Timeline()
        self.timeline.speed = 0
        self.last_time = 0.0

        self.tile_list = tiles(self)

        def extract_tile(filename, flags, tileset):
            filename = Path(filename).name
            tiles = self.tile_list[filename]

            def inner(rect, flags):
                x, y, w, h = rect
                return tiles[x // w + y // h * tileset.columns]

            return inner

        tiled_map = TiledMap(level, image_loader=extract_tile)
        self.level = self.render.attach_new_node("level")
        self.tile_nodes = self.level.attach_new_node("tiles")
        width = tiled_map.width
        height = tiled_map.height * 3**0.5 / 2
        self.level.set_pos(width / 2, -height / 2, 0)

        self.z = defaultdict(int)
        self.track = {}
        self.clear = {}
        self.trains = []
        for layer in tiled_map:
            for x, y, tile_type in layer.tiles():
                if tile_type is not None:
                    if isinstance(tile_type, Train):
                        train_node = tile_type.train.copyTo(self.level)
                        train_node.set_pos(*from_hex(x, y), self.z[x, y])
                        self.trains.append(
                            TrainInstance(tile_type, train_node, x, y))
                    if isinstance(tile_type, Track):
                        self.track[x, y] = tile_type
                    else:
                        tile = self.tile_nodes.attach_new_node("tile")
                        tile.set_pos(*from_hex(x, y), self.z[x, y])
                        self.z[x, y] += tile_type.height
                        self.clear[x, y] = self.clear.get(
                            (x, y), True) and tile_type.clear
                        tile_type.node.instanceTo(tile)

        self.track_nodes = None
        self.update_track()

        self.timeline.subscribe(self.update_trains)

        # use antialiasing
        self.render.set_antialias(AntialiasAttrib.MMultisample)

        # position camera
        self.camera.set_pos(0, 8, 8)
        self.camera.look_at(0, 0, 0)
        self.disable_mouse()

        # create a light
        ambient = ambient_light(colour=(.3, .3, .3, 1))
        self.ambient = self.render.attach_new_node(ambient)
        self.render.set_light(self.ambient)

        # create another light
        directional = directional_light(colour=(1, 1, 1, 1),
                                        direction=(-1, -2, -3))
        self.directional = self.render.attach_new_node(directional)
        self.render.set_light(self.directional)

        # load control scheme from file
        self.load_controls(controls)
        self.task_mgr.add(self.loop, 'loop')

        # create a ui
        aspect_ratio = self.get_aspect_ratio()

        self.tile_tray = self.aspect2d.attach_new_node("tile_tray")
        tile_tray_bg = OnscreenImage(image='data/black.png',
                                     pos=(0, 0, -1.66),
                                     scale=(aspect_ratio, 0, 1),
                                     color=(0, 0, 0, .3),
                                     parent=self.tile_tray)
        self.tile_tray.setTransparency(TransparencyAttrib.MAlpha)

        self.play = OnscreenImage(image='data/play.png',
                                  pos=(-0.9 * aspect_ratio, 0, 0.85),
                                  scale=0.08,
                                  parent=self.aspect2d)
        self.play.setTransparency(TransparencyAttrib.MAlpha)
        self.stop = OnscreenImage(image='data/stop.png',
                                  pos=(-0.9 * aspect_ratio, 0, 0.85),
                                  scale=0.08,
                                  parent=self.aspect2d)
        self.stop.setTransparency(TransparencyAttrib.MAlpha)
        self.stop.hide()

        self.playing = False

        track_id_to_thumb = {
            1: 'straight_1-2-3-4.png',
            2: 'curved_1-2-3-4.png',
            3: 'straight_1-_-3-4.png',
            4: 'straight_1-2-_-4.png',
            5: 'straight_1-2-3-_.png',
            6: 'curved_1-_-3-4.png',
            7: 'curved_1-2-_-4.png',
            8: 'curved_1-2-3-_.png',
        }
        self.thumbs = random.choices(list(track_id_to_thumb), k=3)
        self.selected_thumb = None

        for n, thumb in enumerate(self.thumbs):
            _thumb = OnscreenImage(image='thumbs/' + track_id_to_thumb[thumb],
                                   pos=((n + 1) * 2 / (len(self.thumbs) + 1) -
                                        1, 0, -.82),
                                   scale=.15,
                                   parent=self.tile_tray)
            _thumb.setTransparency(TransparencyAttrib.MAlpha)

        self.preview = self.level.attach_new_node("preview")
        self.preview.setTransparency(TransparencyAttrib.MAlpha)
        self.preview.setColorScale(2, 2, 2, 0.65)
        self.preview.hide()

        self.rotating_cw = False
        self.rotating_ccw = False

        self.mouse_handler = MouseHandler(self.camera, self.tile_nodes)
Ejemplo n.º 14
0
def build_rects(
    tmxmap: pytmx.TiledMap,
    layer: Union[int, str],
    tileset: Optional[Union[int, str]],
    real_gid: Optional[int],
) -> List[pygame.Rect]:
    """
    Generate a set of non-overlapping rects that represents the distribution of the specified gid.

    Useful for generating rects for use in collision detection

    GID Note: You will need to add 1 to the GID reported by Tiled.

    Parameters:
        tmxmap: TiledMap object
        layer: int or string name of layer
        tileset: int or string name of tileset
        real_gid: Tiled GID of the tile + 1 (see note)

    Returns:
        list of pygame Rect objects

    """
    if isinstance(tileset, int):
        try:
            tileset = tmxmap.tilesets[tileset]
        except IndexError:
            msg = "Tileset #{0} not found in map {1}."
            logger.debug(msg.format(tileset, tmxmap))
            raise IndexError

    elif isinstance(tileset, str):
        try:
            tileset = [t for t in tmxmap.tilesets if t.name == tileset].pop()
        except IndexError:
            msg = 'Tileset "{0}" not found in map {1}.'
            logger.debug(msg.format(tileset, tmxmap))
            raise ValueError

    elif tileset:
        msg = "Tileset must be either a int or string. got: {0}"
        logger.debug(msg.format(type(tileset)))
        raise TypeError

    gid = None
    if real_gid:
        try:
            gid, flags = tmxmap.map_gid(real_gid)[0]
        except IndexError:
            msg = "GID #{0} not found"
            logger.debug(msg.format(real_gid))
            raise ValueError

    if isinstance(layer, int):
        layer_data = tmxmap.get_layer_data(layer)
    elif isinstance(layer, str):
        try:
            layer = [l for l in tmxmap.layers if l.name == layer].pop()
            layer_data = layer.data
        except IndexError:
            msg = 'Layer "{0}" not found in map {1}.'
            logger.debug(msg.format(layer, tmxmap))
            raise ValueError

    p = itertools.product(range(tmxmap.width), range(tmxmap.height))
    if gid:
        points = [(x, y) for (x, y) in p if layer_data[y][x] == gid]
    else:
        points = [(x, y) for (x, y) in p if layer_data[y][x]]

    rects = simplify(points, tmxmap.tilewidth, tmxmap.tileheight)
    return rects