2015-05-16, post № 28

programming, Pygame, Python, #-gon, #around, #around the center, #black, #change, #changing, #circle, #color, #color change, #colors, #controlled, #creating, #grid, #light, #lighting, #lightness, #polygon, #polygons, #random, #randomly assigned colors, #red, #saving, #shadow, #shadows, #tile, #tiles, #tiles.txt, #vector, #vector math, #vectors

Thinking about vectors and polygons a bit more, I came up with an idea to mimic shadows. In this program you can create colorful polygons with no limited quantity of individual points anywhere on the screen. Furthermore you then can move a light source (represented as a yellow circle) to change the polygon’s pitch black shadow.


The shadow can also be modified in that its distance to the polygon can be changed. To understand the shadow’s creation, there is also an option to visualize the path the light would — in reality — go.


Due to the shadow not changing in size (only in distance to its polygon) but rather in distance, I implemented the option to get a grid as the background. That way you more have the impression that the shadow is casted onto another surface beneath the surface containing all the polygons and not floating on the same surface.


To have a nice contrast from the polygons to their shadow, I decided to give every polygon a randomly assigned color by creation.


Lastly the program will save every polygon that has been drawn in a file called tiles.txt. It will be saved in the current working directory (in short cwd). If you create a new polygon or change the color of an existing one, it will automatically be saved.


  • Right-clicking moves the light source,
  • Left-clicking adds one new point (for polygon creation),
  • Left-clicking in flowdraw-mode adds points while holding the button,
  • Middle-clicking will connect the new points and create another polygon,
  • Scrolling (mouse wheel) changes the shadow-polygon distance,
  • Scrolling while holding ‘Space’ changes the distance ten times as rapid,
  • ‘l’ toggles if the path of the light is shown,
  • ‘b’ toggles if the background grid is shown,
  • ‘f’ toggles flowdraw-mode,
  • ‘r’ removes the polygon containing a point nearest to the mouse courser,
  • ‘c’ changes the polygon’s color containing a point nearest to the mouse courser,
  • ‘s’ lets you manually save your progress.
  • All the key bindings can be changed by linking — in the code posted below — main.keys.X to another pygame.K_X.

An example how tiles.txt can look (here for drawing ‘Jblog’ and some triangles): shadow_tiles.txt

Source code: shadow.py
Jonathan Frech's blog; built 2024/05/27 06:43:58 CEST