如何在网格中绘制一行字符(嵌套列表)
给定一个 w x h 大小的网格,通过以下方式生成,
self.grid = [ ['-'] * self.w ] * self.h
我希望在所述网格中的两点之间“绘制”一条字符“线”。以下代码是我想出的代码
def line( self, char, (x1, y1), (x2, y2) ):
self.point( char, (x1, y1) )
x = x1 + cmp( x2, x1 )
y = y1 + cmp( y2, y1 )
while x != x2 or y != y2:
self.point( char, (x, y) )
x = x + cmp( x2, x )
y = y + cmp( y2, y )
self.point( char, (x2, y2) )
,其中 point() 函数只是用 char 填充网格中的单个点。
这就像直线和完美对角线的魅力一样。它也适用于“弯曲”的线,从某种意义上说,它不会抛出错误,但它看起来并不完全像两点之间的线,更像......我不知道,曲棍球棒。
例如,给定一个 10x7 网格,并且
line( 'X', (1,1), (5,9) )
我得到的调用我
----------
-X--------
--X-------
---X------
----X-----
-----XXXXX
----------
想要的可能更像是
----------
-X--------
---X------
-----X----
-------X--
---------X
----------
我将如何做到这一点,同时在此过程中不会破坏直线和完美对角线?我是否需要两段不同的代码来处理这两种情况,或者一种算法可以同时处理这两种情况吗?
Given a w x h sized grid, produced in the following way
self.grid = [ ['-'] * self.w ] * self.h
I wish to "draw" a "line" of characters between two points in said grid. The following code is what I've come up with
def line( self, char, (x1, y1), (x2, y2) ):
self.point( char, (x1, y1) )
x = x1 + cmp( x2, x1 )
y = y1 + cmp( y2, y1 )
while x != x2 or y != y2:
self.point( char, (x, y) )
x = x + cmp( x2, x )
y = y + cmp( y2, y )
self.point( char, (x2, y2) )
Where the point() function simply fills in a single point in the grid with char.
This works like a charm for straight lines and perfect diagonals. It works for "crooked" lines too, in the sense that it doesn't throw errors, but it doesn't exactly look like a line between two points, more like... I don't know, a hockey stick.
For example, given a 10x7 grid and the call
line( 'X', (1,1), (5,9) )
I get
----------
-X--------
--X-------
---X------
----X-----
-----XXXXX
----------
What I'd like is probably something more like
----------
-X--------
---X------
-----X----
-------X--
---------X
----------
How would I do this, while not breaking it for straight lines and perfect diagonals in the process? Do I need two distinct pieces of code to handle the two cases, or can one algorithm do both?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您坚持自己编程,您应该使用 Bresenham 直线算法。此外,像这样初始化网格时要小心:
因为要使用同一列表的
self.h
副本:请改用
或 Numpy 数组。
You should be using Bresenham's line algorithm, if you insist on programming this yourself at all. Furthermore, be careful about initialising the grid like this:
because of edning up with
self.h
copies of the same list:Use
or Numpy arrays instead.