python - 如何在 turtle 图形中显示两条重叠的线

标签 python python-3.x random turtle-graphics random-walk

Screenshot of output image

我使用 turtle 制作了一个随机行走程序,我希望它通过改变颜色来显示两只 turtle 交叉路径的位置。

`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()

当 turtle 在浮点平面上行走时,代码会变得更加复杂,但我们需要将其强制到整数平面以适应我们的后备存储并减少不需要的绘图伪影。

enter image description here

关于python - 如何在 turtle 图形中显示两条重叠的线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58100349/

相关文章:

python - 键盘中断程序不返回值

python - 将填充颜色添加到 none 或 alpha 0,在使用 ffmpeg-python 时返回渲染视频中的绿色背景

python - python中的多维外积

java - 使用 Jython 在 Spring Boot 应用程序中包含 Python 脚本失败 - 找不到模块

Python Dtrace 已打补丁,但仍然得到 "invalid probe specifier"运行测试脚本

javascript - 将静态问题转化为动态问题

c - C编程“胡扯”游戏

Python 扰码器程序

python3 : regex group 1, 意外结果

haskell - 在模拟中控制内存分配/GC?