We’ll also practice writing(fruitful)functions; functions let programmers consolidate common programming patterns, providing us a way us of reducing repetition and creating reusable blocks of code. Moreover, we’ll use assert to make sure our functions are behaving appropriately; think of assertions as the scaffolding used during a building’s(our sketch’s) construction. Once everything is working we can take down the scaffolding.
f = (random(51, 204), random(51, 204), random(51, 204))
c1 = (f[0] - d0, f[1] - d1, f[2] - d2)
c2 = (f[0] + d0, f[1] + d1, f[2] + d2)
fill(*c1)
rect(width/4, height/2, width/2, height)
fill(*c2)
rect(3*width/4, height/2, width/2, height)
fill(*f)
square(width/4, height/2, width/8)
square(3*width/4, height/2, width/8)
Which colors work well together and which clash? Add some code to print or display the colors that are randomly generated and note the colors of your favorite and least favorite matches.
Passing Tuples to Functions
In this lab we’ll be representing colors as tuples, for example f in the above code. In Python we can pass a tuple to functions that expect multiple parameters, like fill, using a weird syntax involving *, for example, fill(*f). Python allows us to spread a tuple when passing it to a function that expects multiple arguments; it is equivalent to fill(f[0], f[1], f[2]).
Accessibility — Contrast Ratio
One important consideration when designing computer interfaces is accessibility. For example, we should take into account color blindness and other types of low vision. One best practice is to ensure high contrast between background and foreground colors.
“WCAG 2.0 level AA requires a contrast ratio of at least 4.5:1 for normal text and 3:1 for large text. WCAG 2.1 requires a contrast ratio of at least 3:1 for graphics and user interface components(such as form input borders). WCAG Level AAA requires a contrast ratio of at least 7:1 for normal text and 4.5:1 for large text.” — Webaim
In order to compute the contrast ratio, first we need to compute the relative luminance of an RGB color(R8bit, G8bit, B8bit). Here’s the pseudo-code for the calculation:
WARM-UP: Interactions of Color
def setup():
size(500, 250)
rectMode(CENTER)
noStroke()
squares()
def draw():
pass
def mousePressed():
squares()
def squares():
background(0)
d0, d1, d2 = random(-51, 51), random(-51, 51), random(-51, 51)
f = (random(51, 204), random(51, 204), random(51, 204))
c1 = (f[0] - d0, f[1] - d1, f[2] - d2)
c2 = (f[0] + d0, f[1] + d1, f[2] + d2)
fill(*c1)
rect(width/4, height/2, width/2, height)
fill(*c2)
rect(3*width/4, height/2, width/2, height)
fill(*f)
square(width/4, height/2, width/8)
square(3*width/4, height/2, width/8)
Passing Tuples to Functions
Accessibility — Contrast Ratio
Computing Luminance