[英]Having a Sprite Follow a Line of a Specific Color Pygame
我正在尝试制作一个 pacman 版本,他和鬼魂只能在谷歌地图上的道路上移动。 我理解使用网格作为边界的概念,但这仅适用于方形游戏板。 因此,我正在寻找有关如何让精灵仅在特定颜色的预绘制线上移动的指导。
我可以用作游戏板的可能地图就是这个。 在这张地图中,您可以看到只使用了两种颜色,一种是灰,一种是黑色,而且图像中有一些曲线。 任何有关如何使这项工作的建议将不胜感激,谢谢大家!
有一个tostring()
函数pygame.image
它返回一个bytes
表示图像对象。 更多关于它的信息: https : //www.pygame.org/docs/ref/image.html#pygame.image.tostring
如果正确计算其位置,则可以获得每个像素的颜色。 无论如何,这看起来很有趣,所以我使用您链接的图像编写了一个小程序。 这段代码有点问题,肯定可以改进,玩家会去他能找到的最黑暗的方块,不一定是黑色的,但这只是给出一个大概的想法:
import pygame
def draw_player(pos):
# Draw a red square as the player
pygame.display.update(pygame.draw.rect(screen, (255, 0, 0), (pos[0], pos[1], 10, 10)))
def pos_rgb_sum(pos):
str_pos = 3 * (pos[1] * bg_size[0] + pos[0]) # The position of current pixel in bg_str. Remember every pixel has 3 values
return sum(bg_str[str_pos: str_pos + 3])
def darkest_neighbor(pos):
# Return the darkest neighbor for the position on the board
darkest_pos, darkest_val = None, 255 * 3 + 1 # So that every value is darker than starting value
for x in range(pos[0] - 1, pos[0] + 2):
for y in range(pos[1] - 1, pos[1] + 2):
if (x, y) == pos:
continue
curr_darkness = pos_rgb_sum((x, y))
if curr_darkness <= darkest_val and (x, y) not in visited: # Try to create movement
darkest_val = curr_darkness
darkest_pos = (x, y)
return darkest_pos
pygame.init()
# Load image and get its string representation
background = pygame.transform.smoothscale(pygame.image.load("wzcPy.png"), (500, 500))
bg_str = pygame.image.tostring(background, "RGB")
bg_size = background.get_size()
screen = pygame.display.set_mode(bg_size)
screen.blit(background, (0, 0))
pygame.display.update()
# A set that will contain positions visited by player
visited = set()
player_pos = None
for x in range(background.get_width()): # Find a black square to position player
for y in range(background.get_height()):
if pos_rgb_sum((x, y)) == 0:
player_pos = (x, y)
break
if player_pos is not None:
break
while pygame.event.wait().type != pygame.QUIT:
visited.add(player_pos)
draw_player(player_pos)
player_pos = darkest_neighbor(player_pos)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.