2

我一直在为我正在做的一个小型角色扮演游戏开发影子施法者。

我遇到的问题是,当我在游戏中使用它时,它只是一种减慢速度并导致可怕滞后的方式。

请不要被帖子的长度吓到。它相当简单,但为了让您可以运行我也包含所有 Bresenham 算法的代码。

原理如下: - 制作黑色表面 - 定义具有位置和半径的光源。- 使用 Bresenham 的圆算法获得由该位置和半径定义的圆的圆周上的所有点。- 对于沿圆周的每个点,使用 Bresenham 的线算法从光源的位置绘制一条线。- 然后遍历线的点并检查它们是否与屏幕上显示的每个障碍物发生碰撞。- 如果没有碰撞,则以该点为中心绘制一个半径为 10 像素左右的白色圆圈。- 如果发生碰撞,沿圆周移动到下一个点。- 最后在一个表面上用所有白色圆圈对表面进行blit,黑色的透明度值为100,白色的透明度值为100。

到目前为止,我尝试了以下方法: 确实减少了延迟: - 将障碍物列表限制为屏幕上显示的那些 - 将屏幕边缘视为障碍物,以减少不可见区域的迭代。- 仅在圆周围的每 3 个点和沿线的 12 个点上迭代。这并没有改变任何东西: - 使用从光源到范围边缘或障碍物的椭圆而不是沿线的许多圆圈。问题是我必须为每个椭圆重新绘制表面,然后旋转整个椭圆。

如果您对如何提高效率有任何建议,我会很高兴来到这里。

Bresenham 线算法:

def get_line(start, end):
    """Bresenham's Line Algorithm
    Produces a list of tuples from start and end

    >>> points1 = get_line((0, 0), (3, 4))
    >>> points2 = get_line((3, 4), (0, 0))
    >>> assert(set(points1) == set(points2))
    >>> print points1
    [(0, 0), (1, 1), (1, 2), (2, 3), (3, 4)]
    >>> print points2
    [(3, 4), (2, 3), (1, 2), (1, 1), (0, 0)]
    """
    # Setup initial conditions
    x1, y1 = start
    x2, y2 = end
    dx = x2 - x1
    dy = y2 - y1

    # Determine how steep the line is
    is_steep = abs(dy) > abs(dx)

    # Rotate line
    if is_steep:
        x1, y1 = y1, x1
        x2, y2 = y2, x2

    # Swap start and end points if necessary and store swap state
    swapped = False
    if x1 > x2:
        x1, x2 = x2, x1
        y1, y2 = y2, y1
        swapped = True

    # Recalculate differentials
    dx = x2 - x1
    dy = y2 - y1

    # Calculate error
    error = int(dx / 2.0)
    ystep = 1 if y1 < y2 else -1

    # Iterate over bounding box generating points between start and end
    y = y1
    points = []
    for x in range(x1, x2 + 1):
        coord = (y, x) if is_steep else (x, y)
        points.append(coord)
        error -= abs(dy)
        if error < 0:
            y += ystep
            error += dx

    # Reverse the list if the coordinates were swapped
    if swapped:
        points.reverse()
    return points

布雷森汉姆圈算法:

def get_circle((dx,dy),radius):
    "Bresenham complete circle algorithm in Python"
    # init vars
    switch = 3 - (2 * radius)
    points = set()
    x = 0
    y = radius
    # first quarter/octant starts clockwise at 12 o'clock
    while x <= y:
        # first quarter first octant
        points.add((x,-y))
        # first quarter 2nd octant
        points.add((y,-x))
        # second quarter 3rd octant
        points.add((y,x))
        # second quarter 4.octant
        points.add((x,y))
        # third quarter 5.octant
        points.add((-x,y))        
        # third quarter 6.octant
        points.add((-y,x))
        # fourth quarter 7.octant
        points.add((-y,-x))
        # fourth quarter 8.octant
        points.add((-x,-y))
        if switch < 0:
            switch = switch + (4 * x) + 6
        else:
            switch = switch + (4 * (x - y)) + 10
            y = y - 1
        x = x + 1
    offset_points = set()
    for pt in points:
        offset_points.add((pt[0]+dx,pt[1]+dy))

    return offset_points

def shadow_gen(shadow_surf,source,cir_pt,obstacles):
    line_points = get_line(source.pos,cir_pt)
    for line_pt in line_points[0::12]:
        for obs in obstacles:
            pygame.draw.circle(shadow_surf, WHITE, line_pt, 20, 0) #radius to 5px and 0 to fill the circle
            if obs.rect.collidepoint(line_pt) or pygame.Rect(0,0,500,500).collidepoint(line_pt) == False:
                return

我的光源、障碍物和阴影遮罩的课程:

class Obstacle(object):
    def __init__(self,x,y):
        self.surf = pygame.Surface((150,150))
        self.rect = pygame.Rect((x,y),(150,150))
        self.surf.fill(pygame.color.Color('blue'))

class Light_Source(object):
    def __init__(self,x,y,range_):
        self.range = range_
        self.pos = (x,y)


class Night_Mask(object):
    def __init__(self):
        self.surf = pygame.Surface((500,500)) #Screenwidth and height
        self.alpha = 100
        self.light_sources = []

        '''setting initial alpha and colorkey'''
        self.surf.set_colorkey(WHITE)
        self.surf.set_alpha(self.alpha)


    def apply_shadows(self, obstacles):
        shadow_surf = pygame.Surface((500,500))
        for source in self.light_sources:
            circle_pts = list(get_circle(source.pos,source.range))
            for cir_pt in circle_pts[0::3]:
                shadow_gen(shadow_surf,source,cir_pt,obstacles)
        self.surf.blit(shadow_surf, (0, 0))

阴影生成函数允许我在不使用 Night_Mask 类的 apply_shadows 方法中的异常的情况下打破线和障碍循环:

def shadow_gen(shadow_surf,source,cir_pt,obstacles):
    line_points = get_line(source.pos,cir_pt)
    for line_pt in line_points[0::12]:
        for obs in obstacles:
            pygame.draw.circle(shadow_surf, WHITE, line_pt, 20, 0) #radius to 5px and 0 to fill the circle
            if obs.rect.collidepoint(line_pt) or pygame.Rect(0,0,500,500).collidepoint(line_pt) == False:
                return

最后是运行上述所有内容的主要 pygame 示例循环:

pygame.init()
screen = pygame.display.set_mode((500, 500))

bg = pygame.Surface((500,500))
bg.fill(pygame.color.Color('yellow'))

ob_a = Obstacle(75,80)
ls = Light_Source(75,75,300)
night_m = Night_Mask()
night_m.light_sources.extend([ls])

while True:  
    screen.fill(pygame.color.Color('black'))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    ls.pos = pygame.mouse.get_pos()

    night_m.apply_shadows([ob_a])

    screen.blit(bg, (0,  0))
    screen.blit(ob_a.surf,ob_a.rect)
    screen.blit(night_m.surf, (0, 0))

    pygame.display.flip()

这是从头到尾的完整代码,用于轻松复制粘贴:

import pygame
import sys

WHITE = (255,255,255)
'''FUNCTIONS'''
def get_line(start, end):
    """Bresenham's Line Algorithm
    Produces a list of tuples from start and end

    >>> points1 = get_line((0, 0), (3, 4))
    >>> points2 = get_line((3, 4), (0, 0))
    >>> assert(set(points1) == set(points2))
    >>> print points1
    [(0, 0), (1, 1), (1, 2), (2, 3), (3, 4)]
    >>> print points2
    [(3, 4), (2, 3), (1, 2), (1, 1), (0, 0)]
    """
    # Setup initial conditions
    x1, y1 = start
    x2, y2 = end
    dx = x2 - x1
    dy = y2 - y1

    # Determine how steep the line is
    is_steep = abs(dy) > abs(dx)

    # Rotate line
    if is_steep:
        x1, y1 = y1, x1
        x2, y2 = y2, x2

    # Swap start and end points if necessary and store swap state
    swapped = False
    if x1 > x2:
        x1, x2 = x2, x1
        y1, y2 = y2, y1
        swapped = True

    # Recalculate differentials
    dx = x2 - x1
    dy = y2 - y1

    # Calculate error
    error = int(dx / 2.0)
    ystep = 1 if y1 < y2 else -1

    # Iterate over bounding box generating points between start and end
    y = y1
    points = []
    for x in range(x1, x2 + 1):
        coord = (y, x) if is_steep else (x, y)
        points.append(coord)
        error -= abs(dy)
        if error < 0:
            y += ystep
            error += dx

    # Reverse the list if the coordinates were swapped
    if swapped:
        points.reverse()
    return points

def get_circle((dx,dy),radius):
    "Bresenham complete circle algorithm in Python"
    # init vars
    switch = 3 - (2 * radius)
    points = set()
    x = 0
    y = radius
    # first quarter/octant starts clockwise at 12 o'clock
    while x <= y:
        # first quarter first octant
        points.add((x,-y))
        # first quarter 2nd octant
        points.add((y,-x))
        # second quarter 3rd octant
        points.add((y,x))
        # second quarter 4.octant
        points.add((x,y))
        # third quarter 5.octant
        points.add((-x,y))        
        # third quarter 6.octant
        points.add((-y,x))
        # fourth quarter 7.octant
        points.add((-y,-x))
        # fourth quarter 8.octant
        points.add((-x,-y))
        if switch < 0:
            switch = switch + (4 * x) + 6
        else:
            switch = switch + (4 * (x - y)) + 10
            y = y - 1
        x = x + 1
    offset_points = set()
    for pt in points:
        offset_points.add((pt[0]+dx,pt[1]+dy))

    return offset_points

def shadow_gen(shadow_surf,source,cir_pt,obstacles):
    line_points = get_line(source.pos,cir_pt)
    for line_pt in line_points[0::12]:
        for obs in obstacles:
            pygame.draw.circle(shadow_surf, WHITE, line_pt, 20, 0) #radius to 5px and 0 to fill the circle
            if obs.rect.collidepoint(line_pt) or pygame.Rect(0,0,500,500).collidepoint(line_pt) == False:
                return

'''CLASSES'''                
class Obstacle(object):
    def __init__(self,x,y):
        self.surf = pygame.Surface((150,150))
        self.rect = pygame.Rect((x,y),(150,150))
        self.surf.fill(pygame.color.Color('blue'))

class Light_Source(object):
    def __init__(self,x,y,range_):
        self.range = range_
        self.pos = (x,y)


class Night_Mask(object):
    def __init__(self):
        self.surf = pygame.Surface((500,500)) #Screenwidth and height
        self.alpha = 100
        self.light_sources = []


        '''setting initial alpha and colorkey'''
        self.surf.set_colorkey(WHITE)
        self.surf.set_alpha(self.alpha)


    def apply_shadows(self, obstacles):
        shadow_surf = pygame.Surface((500,500))
        for source in self.light_sources:
            circle_pts = list(get_circle(source.pos,source.range))
            for cir_pt in circle_pts[0::3]:
                shadow_gen(shadow_surf,source,cir_pt,obstacles)
        self.surf.blit(shadow_surf, (0, 0))


'''MAIN GAME'''
pygame.init()
screen = pygame.display.set_mode((500, 500))

bg = pygame.Surface((500,500))
bg.fill(pygame.color.Color('yellow'))

ob_a = Obstacle(75,80)
ls = Light_Source(75,75,300)
night_m = Night_Mask()
night_m.light_sources.extend([ls])

while True:  
    screen.fill(pygame.color.Color('black'))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    ls.pos = pygame.mouse.get_pos()

    night_m.apply_shadows([ob_a])

    screen.blit(bg, (0,  0))
    screen.blit(ob_a.surf,ob_a.rect)
    screen.blit(night_m.surf, (0, 0))

    pygame.display.flip()
4

1 回答 1

1

您的滞后问题似乎来自方法Night_Mask.apply_shadows(self, obstacles)。这似乎是由于嵌套 for 循环需要经过的纯迭代量。

减少range_构造函数中的值Light_Source(x, y, range_)通过减少上述方法迭代来减少滞后,但视觉效果更差。我发现在将变量设置为超过 ~65-70 之后,fps 开始真正下降。

有一个 Pygame 图形库,可以很好地处理阴影。

页面链接:http : //pygame.org/project-Pygame+Advanced+Graphics+Library-660-4586.html 从网站直接下载8.1.1版本:链接

这是来自该站点的库的描述:

这是一个通用的图形库,可以轻松快速地创建复杂的效果,并且使用最少的代码。运行注释很好的示例,每个示例不到一页(不包括注释),并学习如何制作复杂的效果,如阴影和抗锯齿。

这是来自页面的图像,显​​示了阴影的示例。 在此处输入图像描述

我下载并测试了这个库,效果很好。我在 Pygame1.9.2a0 上测试了 python 3.4

我相信这是解决您问题的最简单方法,并且应该也可以帮助您处理未来的项目。我希望这有帮助。

于 2016-06-20T07:21:56.023 回答