Most tiny ray tracers are the same program: for each pixel, shoot a ray, find the nearest sphere, shade it. The heart is ray-sphere intersection, which is just a quadratic.
A ray is origin + t * direction. A sphere is every point at distance radius from center. Substitute one into the other and you get a t² + b t + c = 0:
from math import sqrt
def hit_sphere(center, radius, origin, direction):
oc = [o - c for o, c in zip(origin, center)]
a = sum(d * d for d in direction)
b = 2.0 * sum(o * d for o, d in zip(oc, direction))
c = sum(o * o for o in oc) - radius * radius
disc = b * b - 4 * a * c
if disc < 0:
return None # the ray misses
t = (-b - sqrt(disc)) / (2 * a)
return t if t > 1e-4 else None
Negative discriminant: miss. Otherwise take the nearer root, and ignore hits behind the camera or glued to the origin (that 1e-4).
Shading: normal is (p - center) / radius, brightness is max(0, dot(normal, to_light)). That is Lambert. Everything else (shadows, reflections) is recursion on the same function.