python - 如何在海龟图形中显示两条重叠的线
问题描述
我使用海龟制作了一个随机游走程序,我希望它通过改变颜色来显示两只海龟交叉路径的位置。
`import turtle as T
import random as R
t = T.Turtle()
u = T.Turtle()
t.speed(0)
u.speed(0)
t.hideturtle()
u.hideturtle()
t.color("red")
u.color("blue")
def randWalk(num):
for i in range(0, num):
x = R.choice((-1,1))
X = R.choice((-1,1))
y = R.choice((-1,1))
Y = R.choice((-1,1))
t.forward(x)
u.forward(X)
if y == 1:
t.left(90)
t.forward(1)
else:
t.right(90)
t.forward(1)
if Y == 1:
u.left(90)
u.forward(1)
else:
u.right(90)
u.forward(1)
randWalk(4000)`
解决方案
Turtle 无法询问当前屏幕上的颜色,因此解决此问题的一种方法可能是拥有某种后备存储,您可以在其中跟踪将哪种颜色写入哪个像素。这是一个使用 Python 列表的粗略示例:
from turtle import Screen, Turtle
from random import choice
WIDTH, HEIGHT = 300, 300
PEN_COLORS = ['red', 'blue']
OVERLAP_COLOR = 'green'
def randWalk(number):
for _ in range(number):
for turtle in turtles:
direction = choice((-1, 1))
turtle.forward(direction)
x, y = map(round, turtle.position())
old_color = color = turtle.pencolor()
turtle.undo() # undo forward()
if grid[y][x] and grid[y][x] != color:
color = OVERLAP_COLOR
turtle.pencolor(color)
turtle.goto(x, y) # redo forward()
turtle.pencolor(old_color)
grid[y][x] = color
choice((turtle.left, turtle.right))(90)
screen.update()
screen = Screen()
screen.setup(WIDTH, HEIGHT)
screen.tracer(False)
grid = [[None] * WIDTH for _ in range(HEIGHT)]
turtles = []
for color in PEN_COLORS:
turtle = Turtle()
turtle.hideturtle()
turtle.pencolor(color)
turtles.append(turtle)
randWalk(4000)
screen.tracer(True)
screen.exitonclick()
代码中还有额外的复杂性,因为海龟在浮点平面上行走,但我们需要将其强制转换为整数平面以适应我们的后备存储并减少不需要的绘图伪影。
推荐阅读
- mongodb - MongoDB条件搜索与父文档和数组中的嵌套文档
- javascript - 使用生产构建注册服务工作者脚本时出错
- python - 如何将源文件传输到 Dask 工作人员?
- r - 用总和约束解决 R 中的简单二次优化
- c# - 为什么回调动作指向的方法不是分配的?
- jenkins-pipeline - 如何在沙盒管道脚本中将 Jenkins 配置为来自 Artifactory 的 @Grab 依赖项
- .net - 是否可以从 Powershell 脚本生成 MSIL?
- linux - 为什么 dotnet 在 Linux 上产生多个进程?
- reactjs - 想用 redux 给每个元素不同的状态
- mpandroidchart - mpandroidchart,一段时间没有数据时不画线