简体   繁体   中英

Can a python turtle assess a background pixel color/change in color of the turtle screen to stop at a line or border?

What I want to do is very simple in principle (if at all possible with pyton turtle). I want to draw a square and make the turtle stay inside the square when it gets to the line without explicitly giving coordinates when to turn. Instead of

if t.xcor() >= 300 or t.xcor() <= -300:
    t.dx *= -1

write a program to assess the underlying pixel color and stop/turn at line...

import turtle

win = turtle.Screen()
win.setup(600,600)
win.tracer(0)

t = turtle.Turtle()
t.shape('circle')
t.pensize(10)
t.up()
t.fd(200)
t.down()
t.lt(90)
t.fd(200)
for i in range(3):
    t.lt(90)
    t.fd(400)

t.lt(90)
t.fd(200)
t.up()
t.goto(0,0)
t.color('red')
t.dx = 1
t.dy = 1

while True:
    win.update()
    t.goto(t.xcor()+t.dx, t.ycor()+t.dy)
    #### Stop/change direction/follow line when pixel.color.whatever = 'black'

You can't do this from within turtle, but you can do it by dropping down to turtle's tkinter underpinnings. However, it's detecting colors of overlapping objects , not pixels , and it can be slow:

Turtle Graphics - Extract Color from onscreenclick

How to get the area of shape filled using turtle

And finally, avoiding pixel color detection altogether by using distance() instead:

Python Collision Detection with x and y coordinates for border

How do i make colour detection in turtle

Which I can demonstrate reworking your example code:

from turtle import Screen, Turtle
from random import randrange

TARGET_DIAMETER = 300
CURSOR_SIZE = 20

screen = Screen()
screen.setup(600, 600)
screen.tracer(False)

target = Turtle()
target.shape('circle')
target.color('yellow')
target.shapesize(TARGET_DIAMETER / CURSOR_SIZE)

turtle = Turtle()
turtle.shape('turtle')
turtle.color('red')
turtle.penup()
turtle.setheading(randrange(360))

def move():
    turtle.forward(2)

    if turtle.distance(target) > TARGET_DIAMETER/2 - CURSOR_SIZE/2:
        turtle.undo()
        turtle.setheading(randrange(360))

    screen.update()
    screen.ontimer(move)

move()

screen.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM