PyNuts PyNuts - 1 month ago 22
Python Question

Python Turtle color change

im currently playing around with pythons turtle module and im trying to make a grid of opaque square shapes, say 30x30 that can change color based on some property (doesn't matter what property) my question is, is there anyway to change the color of a shape once its already been drawn down on the canvas?

Ive tried adding all the square shapes to an array, both stamps and polygons, but it seems impossible to change the color of any of them once they have been drawn.

i know stamp doesn't work because its like a footprint of where the turtle was but is there any method at all that allows for this with polygons or some other method im not aware of?

I didn't add any snippets of code because its a pretty basic question and can be used for many things.

Answer

Yes, you can do it. The key to this, and many complicated turtle problems, is using stamps. They are individually, or collectively, removable. And since they take on the shape of the turtle itself, they can be images or arbitrary polygons of any size or color you wish:

from turtle import Turtle, Screen
from random import randrange, choice

GRID = 15  # GRID by GRID of squares
SIZE = 30  # each square is SIZE by SIZE

def change():
    block = choice(blocks)
    blocks.remove(block)

    position, color, stamp = block

    turtle.clearstamp(stamp)
    turtle.setposition(position)

    color = [min(int(primary * 1.5), 255) for primary in color]  # lighten color
    turtle.color(color)
    blocks.append((position, color, turtle.stamp()))

    screen.ontimer(change, 100)


HALF_SIZE = SIZE // 2

screen = Screen()
screen.colormode(255)
screen.register_shape("block", ((HALF_SIZE, -HALF_SIZE), (HALF_SIZE, HALF_SIZE), (-HALF_SIZE, HALF_SIZE), (-HALF_SIZE, -HALF_SIZE)))

turtle = Turtle(shape="block", visible=False)
turtle.speed("fastest")
turtle.up()

blocks = list()

HALF_GRID = GRID // 2

for x in range(-HALF_GRID, HALF_GRID):
    for y in range(-HALF_GRID, HALF_GRID):
        turtle.goto(x * SIZE, y * SIZE)
        color = [randrange(32), randrange(32), randrange(32)]
        turtle.color(color)
        blocks.append((turtle.position(), color, turtle.stamp()))

screen.ontimer(change, 100)

screen.exitonclick()
Comments