代码之家  ›  专栏  ›  技术社区  ›  Ken Bassett

Python:使用可移动的图钉创建地图

  •  2
  • Ken Bassett  · 技术社区  · 8 年前

    我正在用Python创建一个非常基本的幻想游戏。我有一个图像文件,我想成为世界地图,我有一个图像文件,它是一个pin,用于玩家在地图上的位置。到目前为止,我已经使用PIL将图钉粘贴到地图上。每当用户希望其角色移动时,我都可以调用一个函数来运行以下命令,并使用新的地图图像更新游戏的gui:

    world_map = Image.open('fantasy-world-1.jpg')
    player_pin = Image.open('player_pin.jpg')
    world_map.paste(player_pin, (x-coord, y-coord))
    world_map.save('map_with_pin.png')
    

    对我来说,这似乎不是最好的方式。

    pin的图像位于白色背景上,并且也粘贴了白色背景,覆盖了地图的一部分。有没有办法使背景或特定颜色透明?

    或者使用pygame或其他模块有没有更简单的方法?

    谢谢

    1 回复  |  直到 8 年前
        1
  •  1
  •   skrx    8 年前

    下面是一个简短的演示,演示如何在pygame中通过鼠标单击来移动对象。首先将对象的位置存储在变量中(称为 pos 此处)。如果用户单击鼠标按钮,则可以选择鼠标位置(或者 event.pos pygame.mouse.get_pos() )并将其分配给 销售时点情报系统 变量来更新它。然后只需绘制背景和pin图像( arrow_img 在本例中)每个帧,并使用 销售时点情报系统 作为pin的blit目标。

    import pygame as pg
    
    pg.init()
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    BLUE = pg.Color('dodgerblue1')
    
    background_img = pg.Surface(screen.get_size())
    background_img.fill((30, 30, 30))
    arrow_img = pg.Surface((54, 54), pg.SRCALPHA)
    pg.draw.polygon(arrow_img, BLUE, [(0, 0), (27, 0), (0, 27)])
    pg.draw.polygon(arrow_img, BLUE, [(10, 17), (17, 10), (52, 44), (44, 52)])
    
    pos = (100, 100)  # Position of the arrow.
    
    done = False
    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            elif event.type == pg.MOUSEBUTTONDOWN:
                # Change the position of the arrow.
                pos = event.pos
                print(event.pos)
    
        # Blit the background to clear the screen.
        screen.blit(background_img, (0, 0))
        # Blit the arrow.
        screen.blit(arrow_img, pos)
    
        pg.display.flip()
        clock.tick(30)
    
    pg.quit()
    
    推荐文章