Skip to main content
 首页 » 编程设计

Python:创建带有可移动图钉的 map

2025年01月19日32shangdawei

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

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') 

对我来说,这似乎不是解决问题的最佳方式。

大头针的图片是白底的,白底也是粘贴的,遮住了 map 的一部分。有没有办法使背景或特定颜色透明?

或者是否有更简单的方法使用 pygame 或其他一些模块来解决这个问题?

谢谢!

请您参考如下方法:

这是一个简短的演示,说明如何在 pygame 中通过单击鼠标移动对象。首先将对象的位置存储在变量中(此处称为 pos)。如果用户单击鼠标按钮,您将获取鼠标位置(event.pos 或 pygame.mouse.get_pos())并将其分配给 pos 变量来更新它。然后每帧绘制背景和图钉图像(本例中为 arrow_img),并使用 pos 作为图钉的 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()