Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在海龟图形中显示两条重叠线_Python_Python 3.x_Random_Turtle Graphics_Random Walk - Fatal编程技术网

Python 如何在海龟图形中显示两条重叠线

Python 如何在海龟图形中显示两条重叠线,python,python-3.x,random,turtle-graphics,random-walk,Python,Python 3.x,Random,Turtle Graphics,Random Walk,我用海龟做了一个随机行走程序,我想通过改变颜色来显示两只海龟的交叉点 `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):

我用海龟做了一个随机行走程序,我想通过改变颜色来显示两只海龟的交叉点

`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遍历浮点平面时,代码中还有额外的复杂性,但我们需要将其强制为整数平面,以适应我们的备份存储并减少不需要的图形瑕疵