【问题标题】:Loading a map in Pygame / Python在 Pygame / Python 中加载地图
【发布时间】:2012-03-05 22:03:23
【问题描述】:

如何在 Pygame / Python 中加载地图文件?

我想加载这种格式的地图文件;

http://pastebin.com/12DZhrtp

编辑:我猜这是一个 for 循环,但我不确定该怎么做。

【问题讨论】:

标签: python file map load pygame


【解决方案1】:

虽然有些人帮助打开了文件,但我了解您实际上希望将文本文件导入为地图: 这不是我写的,但一直用它作为我的游戏的例子:

# This code is in the Public Domain
# -- richard@mechanicalcat.net



class Map:
    def __init__(self, map, tiles):
        self.tiles = pygame.image.load(tiles)

        l = [line.strip() for line in open(map).readlines()]
        self.map = [[None]*len(l[0]) for j in range(len(l))]
        for i in range(len(l[0])):
            for j in range(len(l)):
                tile = l[j][i]
                tile = tile_coords[tile]
                if tile is None:
                    continue
                elif isinstance(tile, type([])):
                    tile = random.choice(tile)
                cx, cy = tile
                if random.choice((0,1)):
                    cx += 192
                if random.choice((0,1)):
                    cy += 192
                self.map[j][i] = (cx, cy)

    def draw(self, view, viewpos):
        '''Draw the map to the "view" with the top-left of "view" being at
           "viewpos" in the map.
        '''
        sx, sy = view.get_size()
        bx = viewpos[0]/64
        by = viewpos[1]/64
        for x in range(0, sx+64, 64):
            i = x/64 + bx
            for y in range(0, sy+64, 64):
                j = y/64 + by
                try:
                    tile = self.map[j][i]
                except IndexError:
                    # too close to the edge
                    continue
                if tile is None:
                    continue
                cx, cy = tile
                view.blit(self.tiles, (x, y), (cx, cy, 64, 64))

    def limit(self, view, pos):
        '''Limit the "viewpos" variable such that it defines a valid top-left
           rectangle of "view"'s size over the map.
        '''
        x, y = pos
        # easy
        x = max(x, 0)
        y = max(y, 0)

        # figure number of tiles in a view, hence max x and y viewpos
        sx, sy = view.get_size()
        nx, ny = sx/64, sy/64
        mx = (len(self.map[0]) - nx) * 64
        my = (len(self.map) - ny) * 64
        print y, my

        return (min(x, mx), min(y, my))

def main():
    pygame.init()
    win = pygame.display.set_mode((640, 480))

    map = Map('map.txt', 'tiles.png')
    viewpos = (0,0)
    move = False
    clock = pygame.time.Clock()
    sx, sy = win.get_size()
    while 1:
        event = pygame.event.poll()
        while event.type != NOEVENT:
            if event.type in (QUIT, KEYDOWN):
                sys.exit(0)
            elif event.type == MOUSEBUTTONDOWN:
                x, y = viewpos
                dx, dy = event.pos
                x += dx - sx/2
                y += dy - sy/2
                viewpos = map.limit(win, (x, y))
                move = True
            event = pygame.event.poll()

        win.fill((0,0,0))
        map.draw(win, viewpos)
        pygame.display.flip()

        clock.tick(30)


if __name__ == '__main__':
    main()

【讨论】:

    【解决方案2】:

    如果您从字面上询问如何在 Python 中加载文件——忽略问题的pygame 方面——那么它非常简单。

    >>> with open('a.map', 'r') as f:
    ...     for line in f:
    ...         print line,
    ... 
    x g g g x
    x g g g x
    x g x g x
    x g g g x
    x x x x x
    
    KEY:
    x = wall
    g = grass / floor
    

    现在无需打印每一行,您可以简单地阅读它并将其存储在您正在使用的任何数据结构中。

    不过,我对pygame 一无所知——如果它有一些自定义功能,我无能为力。

    【讨论】:

    • 有为 pygame 构建的地图库,但是,不清楚这就是 Jack 正在寻找的东西。如:pygame.org/…
    【解决方案3】:

    由于地图只是一个二维数组,因此需要两个循环来完成整个过程。

            self.map = [[None]*len(l[0]) for j in range(len(l))]
            for i in range(len(l[0])):
                for j in range(len(l)):
    

    细节可以在很多地方找到。这是一个: http://www.mechanicalcat.net/richard/log/Python/PyGame_sample__drawing_a_map__and_moving_around_it

    在里面你可以决定画什么。在您的情况下:墙、草或地板,它们将是精灵。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-04
      • 1970-01-01
      相关资源
      最近更新 更多