簡體   English   中英

讓 Sprite 跟隨特定顏色的線條 Pygame

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM