简体   繁体   中英

Can you make a Python Turtle detect if it's touching a specific colour?

Is it possible for a turtle to detect whether it is touching a specific colour, or not, without using a grid system (ie allocating each cell a colour.) I am trying to create a pixelated world that a creature will navigate, and interact with, depending on what sort of tile it is touching, which will be determined based on the tile's colour.

The best you could try to replicate this Scratch project in Python would be a grid based system using the python framework, pygame.

This would mean you need to code the background, user, interface, commands, collisions. A bigger feat to do all by your own hands.

My files indicate that this would be a good video series to get started:

Setup: https://youtu.be/VO8rTszcW4s

Creating The Game: https://youtu.be/3UxnelT9aCo

I hope your endeavor is fruitful!

We can force turtle to do this by dropping down to the tkinter level. Although we think of things that the turtle draws as dead ink (as opposed to shaped turtles or stamps), they are in fact live ink from tkinter's point of view -- which is why we can clear an individual turtle's drawings and call undo() . Here's a fragile example that does this:

from turtle import Screen, Turtle
from random import random

WIDTH, HEIGHT = 800, 800
DIAMETER = 200

def chameleon(x, y):
    turtle.ondrag(None)
    overlapping = canvas.find_overlapping(x, -y, x, -y)  # adjust to tkinter coordinates

    if overlapping:
        color = canvas.itemcget(overlapping[0], "fill")

        if color:
            turtle.fillcolor(color)

    turtle.goto(x, y)
    turtle.ondrag(chameleon)

screen = Screen()
screen.setup(WIDTH, HEIGHT)
canvas = screen.getcanvas()

turtle = Turtle()
turtle.hideturtle()
turtle.speed('fastest')
turtle.penup()

for x in range(-WIDTH//2, WIDTH//2, DIAMETER):
    for y in range(-HEIGHT//2, HEIGHT//2, DIAMETER):
        turtle.goto(x + DIAMETER/2, y + DIAMETER/2)
        color = random(), random(), random()
        turtle.dot(DIAMETER - 1, color)

turtle.home()
turtle.shape('turtle')
turtle.shapesize(2)
turtle.showturtle()
turtle.ondrag(chameleon)

screen.mainloop()

As you drag the turtle around the screen, it will pick up color from things drawn on the screen. This isn't a clear turtle that you're seeing through, it's reading the ink, which you can confirm for yourself as you move over the background. This code may be turtle implementation specific.

I'm not sure how well this will scale up (or more likely scale down towards pixel size objects) but should give you an idea what's possible if you're willing to embrace turtle's tkinter underpinnings, or simply use tkinter itself.

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