예제 #1
0
파일: loadLevel.py 프로젝트: DanCher17/Game
def loadLevel(name):
    tramps = pygame.sprite.Group()
    monsters = pygame.sprite.Group()
    stars = pygame.sprite.Group()
    entities = pygame.sprite.Group()
    ground = []

    world_map = tmxreader.TileMapParser().parse_decode(name)
    resources = helperspygame.ResourceLoaderPygame()
    resources.load(world_map)

    sprite_layers = helperspygame.get_layers_from_map(resources)

    monsters_layer_1 = sprite_layers[0]
    for monster in monsters_layer_1.objects:
        x = monster.x
        y = monster.y
        mn = Monster_1(x, y)
        monsters.add(mn)
        entities.add(monsters)
    monsters_layer_2 = sprite_layers[1]
    for monster in monsters_layer_2.objects:
        x = monster.x
        y = monster.y
        mn = Monster_2(x, y)
        monsters.add(mn)
        entities.add(monsters)
    monsters_layer_3 = sprite_layers[2]
    for monster in monsters_layer_3.objects:
        x = monster.x
        y = monster.y
        mn = Monster_3(x, y)
        monsters.add(mn)
        entities.add(monsters)
    stars_layer = sprite_layers[3]
    for star in stars_layer.objects:
        x = star.x
        y = star.y
        st = Star(x, y)
        stars.add(st)
        entities.add(stars)
    tramps_layer = sprite_layers[4]
    for tramp in tramps_layer.objects:
        x = tramp.x
        y = tramp.y
        tr = Trampoline(x, y)
        tramps.add(tr)
        entities.add(tramps)
    for i in range(200):
        gr = Ground(i * 32, 390)
        ground.append(gr)
        tp = Ground(i * 32, 0)
        ground.append(tp)
    entities.add(ground)
    colliders = (monsters, stars, tramps, ground)

    return sprite_layers, entities, colliders
예제 #2
0
    def __init__(self, tile_map, track_name):
        self.level_over = False

        # Level sprites
        self.entities = pygame.sprite.Group()
        self.walls = pygame.sprite.Group()
        self.enemies = pygame.sprite.Group()
        self.hero = None

        # Miscellaneous
        self.track_name = track_name
        self.background = Surface(
            (WIN_WIDTH, WIN_HEIGHT))  # create a surface (image)
        self.background.fill(
            Color(BACKGROUND_COLOR))  # fill the surface with background color

        # Parse a tile map
        path = os.path.join(os.getcwd(), "images", "tiles")
        world_map = tmxreader.TileMapParser().parse_decode('%s/%s.tmx' %
                                                           (path, tile_map))
        resources = helperspygame.ResourceLoaderPygame()
        resources.load(world_map)
        self.sprite_layers = helperspygame.get_layers_from_map(resources)
        walls_layer = self.sprite_layers[1]
        goblins_layer = self.sprite_layers[2]
        hero_layer = self.sprite_layers[3]

        # Create walls
        for row in range(0, walls_layer.num_tiles_x):
            for col in range(0, walls_layer.num_tiles_y):
                if walls_layer.content2D[col][row] is not None:
                    wall = Wall(row * BLOCK_SIZE, col * BLOCK_SIZE)
                    self.walls.add(wall)

        # Create goblins
        for gob in goblins_layer.objects:
            if gob is not None:
                goblin = Goblin(self, gob.x, gob.y)
                self.enemies.add(goblin)

        # Create a hero
        hero = hero_layer.objects[0]
        self.hero = Viking(hero.x, hero.y, self)

        # Assemble entities list (game objects that need to be drawn every cycle)
        self.entities.add(self.enemies)
        self.entities.add(self.hero)
예제 #3
0
    def load_level(self):
        world_map = tmxreader.TileMapParser().parse_decode(
            f'levels/{self.level_now}.tmx')
        resources = helperspygame.ResourceLoaderPygame()
        resources.load(world_map)

        self.sprite_layers = helperspygame.get_layers_from_map(resources)

        platforms_layer = self.sprite_layers[0]
        spike_layer = self.sprite_layers[1]

        for row in range(0, platforms_layer.num_tiles_x):
            for col in range(0, platforms_layer.num_tiles_y):
                if platforms_layer.content2D[col][row] is not None:
                    p = platforms.Platform(row * 32, col * 32)
                    self.platforms_group.add(p)

                if spike_layer.content2D[col][row] is not None:
                    s = platforms.Spike(row * 32, col * 32)
                    self.spikes.add(s)
        exit_layer = self.sprite_layers[3]

        for exit in exit_layer.objects:
            try:
                x = exit.x
                y = exit.y
            except:
                pass
            else:
                self.exit = platforms.Exit(x, y)
                self.all_objects.add(self.exit)

        player_layer = self.sprite_layers[2]
        for pl in player_layer.objects:
            try:
                self.start_x = pl.x
                self.start_y = pl.y - 64
            except:
                pass
            else:
                self.player = player.Player(self.start_x, self.start_y)
                self.all_objects.add(self.player)

        self.total_x = platforms_layer.num_tiles_x * 32
        self.total_y = platforms_layer.num_tiles_y * 32
        self.camera = camera.Camera(self.camera_configure, self.total_x,
                                    self.total_y)
예제 #4
0
def demo_pygame(file_name):
    """
    Example showing how to use the paralax scrolling feature.
    """

    # parser the map (it is done here to initialize the
    # window the same size as the map if it is small enough)
    world_map = tmxreader.TileMapParser().parse_decode(file_name)

    # init pygame and set up a screen
    pygame.init()
    pygame.display.set_caption("tiledtmxloader - " + file_name +
                               " - keys: arrows, 0-9")
    screen_width = min(1024, world_map.pixel_width)
    screen_height = min(768, world_map.pixel_height)
    screen = pygame.display.set_mode((screen_width, screen_height))

    # load the images using pygame
    resources = helperspygame.ResourceLoaderPygame()
    resources.load(world_map)

    # prepare map rendering
    assert world_map.orientation == "orthogonal"

    # renderer
    renderer = helperspygame.RendererPygame()

    # create hero sprite
    # use floats for hero position
    hero_pos_x = screen_width
    hero_pos_y = screen_height
    hero = create_hero(hero_pos_x, hero_pos_y)

    # cam_offset is for scrolling
    cam_world_pos_x = hero.rect.centerx
    cam_world_pos_y = hero.rect.centery

    # set initial cam position and size
    renderer.set_camera_position_and_size(cam_world_pos_x, cam_world_pos_y,
                                          screen_width, screen_height)

    # retrieve the layers
    sprite_layers = helperspygame.get_layers_from_map(resources)

    # filter layers
    sprite_layers = [
        layer for layer in sprite_layers if not layer.is_object_group
    ]

    # add the hero the the right layer, it can be changed using 0-9 keys
    layer = get_sprite_layer(1, sprite_layers, world_map.layers)
    if layer is not None:
        layer.add_sprite(hero)

    # layer add/remove hero keys
    num_keys = [pygame.K_0, pygame.K_1, pygame.K_2, pygame.K_3, pygame.K_4, \
                    pygame.K_5, pygame.K_6, pygame.K_7, pygame.K_8, pygame.K_9]

    # variables for the main loop
    clock = pygame.time.Clock()
    running = True
    speed = 0.075 * 10
    # set up timer for fps printing
    pygame.time.set_timer(pygame.USEREVENT, 1000)

    # mainloop
    while running:
        dt = clock.tick()

        # event handling
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.USEREVENT:
                print("fps: ", clock.get_fps())
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    running = False
                elif event.key in num_keys:
                    # find out which layer to manipulate
                    idx = num_keys.index(event.key)
                    # make sure this layer exists
                    if idx < len(world_map.layers):
                        layer = get_sprite_layer(idx, sprite_layers,
                                                 world_map.layers)
                        if layer is not None:
                            if layer.contains_sprite(hero):
                                layer.remove_sprite(hero)
                                print("removed hero sprite from layer", idx)
                            else:
                                layer.add_sprite(hero)
                                print("added hero sprite to layer", idx)
                    else:
                        print("no such layer or more than 10 layers: " +
                              str(idx))

        # find directions
        pressed = pygame.key.get_pressed()
        direction_x = pressed[pygame.K_RIGHT] - \
                                        pressed[pygame.K_LEFT]
        direction_y = pressed[pygame.K_DOWN] - \
                                        pressed[pygame.K_UP]

        # make sure the hero moves with same speed in all directions (diagonal!)
        dir_len = math.hypot(direction_x, direction_y)
        dir_len = dir_len if dir_len else 1.0
        # update position
        hero_pos_x += speed * dt * direction_x / dir_len
        hero_pos_y += speed * dt * direction_y / dir_len
        hero.rect.midbottom = (hero_pos_x, hero_pos_y)

        # adjust camera according to the hero's position, follow him
        renderer.set_camera_position(hero.rect.centerx, hero.rect.centery)

        # clear screen, might be left out if every pixel is redrawn anyway
        screen.fill((255, 0, 255))

        # render the map
        for sprite_layer in sprite_layers:
            if sprite_layer.is_object_group:
                # we dont draw the object group layers
                # you should filter them out if not needed
                continue
            else:
                renderer.render_layer(screen, sprite_layer)

        pygame.display.flip()
예제 #5
0
def loadLevel(name):
    # объявляем глобальные переменные
    global playerX, playerY  # это координаты героя
    global total_level_height, total_level_width
    global sprite_layers  # все слои карты

    world_map = tmxreader.TileMapParser().parse_decode(  # загружаем карту
            '%s/%s.tmx' % (FILE_DIR, name))
    # инициируем преобразователь карты
    resources = helperspygame.ResourceLoaderPygame()
    resources.load(world_map)  # и преобразуем карту в понятный pygame формат

    # получаем все слои карты
    sprite_layers = helperspygame.get_layers_from_map(resources)

    # берем слои по порядку 0 - слой фона, 1- слой блоков,
    # 2 - слой смертельных блоков,
    # 3 - слой объектов монстров, 4 - слой объектов телепортов
    platforms_layer = sprite_layers[1]
    dieBlocks_layer = sprite_layers[2]

    # перебираем все координаты тайлов
    for row in range(0, platforms_layer.num_tiles_x):
        for col in range(0, platforms_layer.num_tiles_y):
            if platforms_layer.content2D[col][row] is not None:
                # как и прежде создаем объкты класса Platform
                pf = Platform(row * PLATFORM_WIDTH, col * PLATFORM_WIDTH)
                platforms.append(pf)
            if dieBlocks_layer.content2D[col][row] is not None:
                bd = BlockDie(row * PLATFORM_WIDTH, col * PLATFORM_WIDTH)
                platforms.append(bd)

    teleports_layer = sprite_layers[4]
    for teleport in teleports_layer.objects:
        try:  # если произойдет ошибка на слое телепортов
            goX = int(teleport.properties["goX"]) * PLATFORM_WIDTH
            goY = int(teleport.properties["goY"]) * PLATFORM_HEIGHT
            x = teleport.x
            y = teleport.y - PLATFORM_HEIGHT
            tp = BlockTeleport(x, y, goX, goY)
            entities.add(tp)
            platforms.append(tp)
            animatedEntities.add(tp)
        except:  # то игра не вылетает, а просто выводит сообщение о неудаче
            print(u"Ошибка на слое телепортов")

    monsters_layer = sprite_layers[3]
    for monster in monsters_layer.objects:
        try:
            x = monster.x
            y = monster.y
            if monster.name == "Player":
                playerX = x
                playerY = y - PLATFORM_HEIGHT
            elif monster.name == "Princess":
                pr = Princess(x, y - PLATFORM_HEIGHT)
                platforms.append(pr)
                entities.add(pr)
                animatedEntities.add(pr)
            else:
                up = int(monster.properties["up"])
                maxUp = int(monster.properties["maxUp"])
                left = int(monster.properties["left"])
                maxLeft = int(monster.properties["maxLeft"])
                mn = Monster(x, y - PLATFORM_HEIGHT, left, up, maxLeft, maxUp)
                entities.add(mn)
                platforms.append(mn)
                monsters.add(mn)
        except:
            print(u"Ошибка на слое монстров")

    # Высчитываем фактические ширину и высоту уровня
    total_level_width = platforms_layer.num_tiles_x * PLATFORM_WIDTH
    total_level_height = platforms_layer.num_tiles_y * PLATFORM_HEIGHT
예제 #6
0
파일: main.py 프로젝트: ArystanIgen/pygame
def loadLevel(name, game):
    global playerX, playerY  # объявляем глобальные переменные, это координаты героя
    global total_level_height, total_level_width
    global sprite_layers  # все слои карты
    world_map = tmxreader.TileMapParser().parse_decode(
        '%s/%s.tmx' % (FILE_DIR, name))  # загружаем карту
    resources = helperspygame.ResourceLoaderPygame(
    )  # инициируем преобразователь карты
    resources.load(world_map)  # и преобразуем карту в понятный pygame формат

    sprite_layers = helperspygame.get_layers_from_map(
        resources)  # получаем все слои карты

    # берем слои по порядку 0 - слой фона, 1- слой блоков, 2 - слой смертельных блоков
    # 3 - слой объектов монстров, 4 - слой объектов телепортов
    platforms_layer = sprite_layers[1]
    dieBlocks_layer = sprite_layers[2]

    for row in range(
            0,
            platforms_layer.num_tiles_x):  # перебираем все координаты тайлов
        for col in range(0, platforms_layer.num_tiles_y):
            if platforms_layer.content2D[col][row] is not None:
                pf = Platform(row * PLATFORM_WIDTH, col * PLATFORM_WIDTH
                              )  # как и прежде создаем объкты класса Platform
                game.entities.add(pf)
                game.platforms.append(pf)

            if dieBlocks_layer.content2D[col][row] is not None:
                bd = BlockDie(row * PLATFORM_WIDTH, col * PLATFORM_WIDTH)
                game.dieskeletgroup.add(bd)
                game.entities.add(bd)
                game.platforms.append(bd)

    teleports_layer = sprite_layers[4]
    for teleport in teleports_layer.objects:
        try:  # если произойдет ошибка на слое телепортов
            goX = int(teleport.properties["goX"]) * PLATFORM_WIDTH + 35
            goY = int(teleport.properties["goY"]) * PLATFORM_HEIGHT
            x = teleport.x
            y = teleport.y - PLATFORM_HEIGHT
            tp = BlockTeleport(x, y, goX, goY)
            game.entities.add(tp)
            game.platforms.append(tp)
            game.teleport.add(tp)
        except:  # то игра не вылетает, а просто выводит сообщение о неудаче
            print(u"Ошибка на слое телепортов")

    monsters_layer = sprite_layers[3]
    for monster in monsters_layer.objects:
        try:
            x = monster.x
            y = monster.y
            if monster.name == "Player":
                playerX = x
                playerY = y - PLATFORM_HEIGHT
            elif monster.name == "Princess":
                cp = Cup(x, y - 10)
                game.cupgroup.add(cp)
                game.entities.add(cp)
                game.platforms.append(cp)

            else:
                up = int(monster.properties["up"])
                maxUp = int(monster.properties["maxUp"])
                left = int(monster.properties["left"])
                maxLeft = int(monster.properties["maxLeft"])
                mn = Monster(x, y - PLATFORM_HEIGHT, left, up, maxLeft, maxUp)
                game.monsters.add(mn)
        except:
            print(u"Ошибка на слое монстров")

    total_level_width = platforms_layer.num_tiles_x * PLATFORM_WIDTH  # Высчитываем фактическую ширину уровня
    total_level_height = platforms_layer.num_tiles_y * PLATFORM_HEIGHT  # высоту
예제 #7
0
def loadLevel(name):
    world_map = tmxreader.TileMapParser().parse_decode(
        '%s/%s.tmx' % (FILE_DIR, name))  # загружаем карту
    resources = helperspygame.ResourceLoaderPygame(
    )  # инициируем преобразователь карты
    resources.load(world_map)  # и преобразуем карту в понятный pygame формат

    sprite_layers = helperspygame.get_layers_from_map(
        resources)  # получаем все слои карты

    # берем слои по порядку
    # 0 - слой фона,
    # 1 - слой блоков,
    # 2 - слой смертельных блоков
    # 3 - слой объектов монстров,
    # 4 - слой объектов телепортов
    platforms_layer = sprite_layers[1]
    dieBlocks_layer = sprite_layers[2]

    for row in range(
            0,
            platforms_layer.num_tiles_x):  # перебираем все координаты тайлов
        for col in range(0, platforms_layer.num_tiles_y):
            if platforms_layer.content2D[col][row]:
                pf = Platform(row * PLATFORM_WIDTH, col * PLATFORM_WIDTH
                              )  # как и прежде создаем объкты класса Platform
                platforms.append(pf)
            if dieBlocks_layer.content2D[col][row]:
                bd = BlockDie(row * PLATFORM_WIDTH, col * PLATFORM_WIDTH)
                platforms.append(bd)

    teleports_layer = sprite_layers[4]
    for teleport in teleports_layer.objects:
        goX = int(teleport.properties["goX"]) * PLATFORM_WIDTH
        goY = int(teleport.properties["goY"]) * PLATFORM_HEIGHT
        x = teleport.x
        y = teleport.y - PLATFORM_HEIGHT
        tp = BlockTeleport(x, y, goX, goY)
        entities.add(tp)
        platforms.append(tp)
        animatedEntities.add(tp)

    playerX = 65
    playerY = 65

    monsters_layer = sprite_layers[3]
    for monster in monsters_layer.objects:
        x = monster.x
        y = monster.y
        if monster.name == "Player":
            playerX = x
            playerY = y - PLATFORM_HEIGHT
        elif monster.name == "Princess":
            pr = Princess(x, y - PLATFORM_HEIGHT)
            platforms.append(pr)
            entities.add(pr)
            animatedEntities.add(pr)
        else:
            up = int(monster.properties["up"])
            maxUp = int(monster.properties["maxUp"])
            left = int(monster.properties["left"])
            maxLeft = int(monster.properties["maxLeft"])
            mn = Monster(x, y - PLATFORM_HEIGHT, left, up, maxLeft, maxUp)
            entities.add(mn)
            platforms.append(mn)
            monsters.add(mn)

    total_level_width = platforms_layer.num_tiles_x * PLATFORM_WIDTH  # Высчитываем фактическую ширину уровня
    total_level_height = platforms_layer.num_tiles_y * PLATFORM_HEIGHT  # высоту

    return playerX, playerY, total_level_height, total_level_width, sprite_layers