修改布雷森汉姆的直线算法 [英] Modifying Bresenham's line algorithm

查看:81
本文介绍了修改布雷森汉姆的直线算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Bresenham的线算法来计算网格上的视场。我正在使用的代码可以毫无问题地计算行数,但是我很难将其始终返回从起点到终点的行数。我需要怎么做才能使所有返回的行都从(x0,y0)到(x1,y1)

I'm trying to use Bresenham's line algorithm to compute Field of View on a grid. The code I'm using calculates the lines without a problem but I'm having problems getting it to always return the line running from start point to endpoint. What do I need to do so that all lines returned run from (x0,y0) to (x1,y1)

def bresenham_line(self, x0, y0, x1, y1):
steep = abs(y1 - y0) > abs(x1 - x0)
if steep:
    x0, y0 = y0, x0  
    x1, y1 = y1, x1

if x0 > x1:
    x0, x1 = x1, x0
    y0, y1 = y1, y0

if y0 < y1: 
    ystep = 1
else:
    ystep = -1

deltax = x1 - x0
deltay = abs(y1 - y0)
error = -deltax / 2
y = y0

line = []    
for x in range(x0, x1 + 1):
    if steep:
        line.append((y,x))
    else:
        line.append((x,y))

    error = error + deltay
    if error > 0:
        y = y + ystep
        error = error - deltax
return line


推荐答案

请记住是否已切换x0和x1,然后再反转列表。

Remember whether you switched x0 and x1 and then reverse the list if you did.

if x0 > x1:
    x0, x1 = x1, x0
    y0, y1 = y1, y0

成为

switched = False
if x0 > x1:
    switched = True
    x0, x1 = x1, x0
    y0, y1 = y1, y0

,最后,只需添加:

if switched:
    line.reverse()

这篇关于修改布雷森汉姆的直线算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆