Add random_color and the color palette

random_color returns an immutable (red, green, blue) tuple of integers from 0 to 255
and random_palette_color picks a named color. Both take an optional random.Random
so that tests can seed them.

Task: MIL-003#1
Task: MIL-003#2
This commit is contained in:
2026-10-07 23:59:02 +08:00
parent b3153b9dc1
commit 9318a07fa0
5 changed files with 127 additions and 0 deletions
+3
View File
@@ -8,10 +8,13 @@ The challenges so far are @ref turtle_challenges.square.draw_square and
first argument, so it can be tested without a window.
"""
from turtle_challenges.colors import random_color, random_palette_color
from turtle_challenges.dashed_line import draw_dashed_line
from turtle_challenges.square import draw_square
__all__ = [
"draw_dashed_line",
"draw_square",
"random_color",
"random_palette_color",
]
+44
View File
@@ -0,0 +1,44 @@
"""!
@file colors.py
@brief Random colors for the challenges.
A color is either a name from the palette (challenge 3) or an RGB tuple
(challenges 4 and 5). A tuple is the right type for an RGB value: it is
immutable, so a color cannot change after it is made.
"""
import random
from turtle_challenges.constants import (
COLOR_CHANNEL_MAX,
COLOR_CHANNEL_MIN,
COLOR_PALETTE,
)
## Generator used when a caller passes none; tests pass a seeded one instead.
_DEFAULT_RANDOM = random.Random()
def random_color(rng: random.Random | None = None) -> tuple[int, int, int]:
"""!
@brief Pick a random RGB color.
@param rng Random generator to draw from; a shared one is used if omitted.
@return A tuple of red, green and blue, each from 0 to 255.
"""
generator = rng if rng is not None else _DEFAULT_RANDOM
red = generator.randint(COLOR_CHANNEL_MIN, COLOR_CHANNEL_MAX)
green = generator.randint(COLOR_CHANNEL_MIN, COLOR_CHANNEL_MAX)
blue = generator.randint(COLOR_CHANNEL_MIN, COLOR_CHANNEL_MAX)
return (red, green, blue)
def random_palette_color(rng: random.Random | None = None) -> str:
"""!
@brief Pick a random color name from the palette.
@param rng Random generator to draw from; a shared one is used if omitted.
@return One of the names in `COLOR_PALETTE`.
"""
generator = rng if rng is not None else _DEFAULT_RANDOM
return generator.choice(COLOR_PALETTE)
+18
View File
@@ -14,6 +14,12 @@ WINDOW_TITLE = "Turtle Challenges"
## colors can be given as RGB tuples from 0 to 255.
COLOR_MODE = 255
## Smallest value of one color channel.
COLOR_CHANNEL_MIN = 0
## Largest value of one color channel.
COLOR_CHANNEL_MAX = COLOR_MODE
## Degrees in a right angle.
RIGHT_ANGLE_DEGREES = 90
@@ -32,6 +38,18 @@ DASH_LENGTH = 10
## Challenge 2: length of the gap after each dash, in turtle units.
GAP_LENGTH = 10
## Challenge 3: named colors a polygon is drawn in.
COLOR_PALETTE: tuple[str, ...] = (
"CornflowerBlue",
"DarkOrchid",
"IndianRed",
"DeepSkyBlue",
"LightSeaGreen",
"wheat",
"SlateGray",
"SeaGreen",
)
## Command line name of challenge 1.
CHALLENGE_SQUARE = "square"