Fundamentals of Computer Science I: Media Computing (CS151.02 2007F)

Randomized Drawing


Summary: Up to this point, all of the programs we have written are, in some sense, predictable. That is, the output depends only on the input. However, there are also programs that we want to be a bit less predictable, such as simulations of events, games, and the like. We may also want to have some unpredictability in the drawings we make, so that we can derive inspiration from unexpected results. (In some cases, we might even consider a series of similar images that have some variation within a consistent set of constraints.) In this reading, we consider Scheme's tools for supporting such unpredictability, particularly the random procedure.

Introduction: Simulation

Many computing applications involve the simulation of games or events, with the hope of gaining insights and identifying underlying principles. In some cases, simulations can apply definite, well-known formulae. For example, in studying the effect of a pollution source in a lake or stream, one can keep track of pollutant concentrations in various places. Then, since the flow of water and the interactions of pollutants is reasonably well understood, one can follow the flow of the pollutants over a period of time, according to known equations.

In other cases, specific outcomes involve some chance. For example, when an automobile begins a trip and encounters a traffic light, it may be a matter of chance as to whether the light is green or not. Similar uncertainties arise when considering specific organisms or when tabulating outcomes involving flipping a coin, tossing a die, or dealing cards. In these cases, one may know about the probability of an event occurring (a head occurs about half the time), but the outcome of any one event depends on chance.

In studying events that involve some chance, one approach is to model the event or game, using a random-number generator as the basis for decisions. If such models are run on computers many times, the results may give some statistical information about what outcomes are likely and how often each type of outcome might be expected to occur. This approach to problem solving is called the Monte Carlo Method.

Randomness is also useful in image generation. A number of artists, from the founders of the Dada movement to Jackson Pollock and beyond, have reveled in the images that can be created by random or unpredictable processes. The Dadaists employed random selection to write poetry and subconscious drawing to create images. Pollock threw paint with an expectation that interesting patterns would result. (And yes, those are incredible simplifications of the philosophies and techniques of these artists.) By combining a random-number generator with some drawing techniques, we can produce some potentially interesting images.

The random Procedure

A random number generator for a typical computer language is a procedure that produces a different value each time it is called. Such procedures simulate a random selection process. Scheme provides the procedure random for this purpose. This procedure returns integer values that depend on its parameter. In particular, random returns an integer value between 0 and one less than its parameter, inclusive.

> (random 10)
1
> (random 10)
9
> (random 10)
7
> (random 10)
0
> (random 10)
5
> (random 10)
1
> (random 10)
0

Simulating a Die

We can use random to write a program to simulate the rolling of a die. The simulation generates integers from 1 to 6, to correspond to the faces on the die cube. The details of this simulation are shown in the following procedure:

;;; Procedure:
;;;   roll-a-die
;;; Parameters:
;;;   None
;;; Purpose:
;;;   To simulate the rolling of one six-sided die.
;;; Produces:
;;;   An integer between 1 and 6, inclusive.
;;; Preconditions:
;;;   [None]
;;; Postconditions:
;;;   Returns an integer between 1 and 6, inclusive.
;;;   It should be difficult (or impossible) to predict which
;;;     number is produced.
(define roll-a-die
  (lambda ()
    (+
      (random 6)    ; a value in the range [0 .. 5]
      1)))          ; now in the range [1 .. 6]

We can use that procedure to simulate the roll of two dice.

(define roll-dice
  (lambda ()
    (+ (roll-a-die) (roll-a-die))))

Procedures for Randomized Drawing

We can use a number of simple techniques to generate such randomized art. What can we randomize? One thing to start with is colors. Given a list of colors, it is easy to select one of those colors.

;;; Value:
;;;   colors.rainbow
;;; Type:
;;;   List of colors 
;;; Contains:
;;;   A list of colors of the rainbow, suitable for processing by 
;;;   random-rainbow-color.
(define colors.rainbow
  (list color.red color.orange color.yellow color.green color.blue
        color.indigo color.violet))

;;; Procedure:
;;;   random-rainbow-color
;;; Parameters:
;;;   [None]
;;; Purpose:
;;;   Picks a "random" (unpredictable) color from the basic colors
;;;   of the rainbow.
;;; Produces:
;;;   color, a string
;;; Preconditions:
;;;   Value colors.rainbow has been defined as a list of colors.
;;; Postconditions:
;;;   color is a color.
;;;   It is difficult for someone to predict what color random-color
;;;     will return.
(define random-rainbow-color
  (lambda ()
    (list-ref colors.rainbow
              (random (length colors.rainbow)))))

It's also possible to be a bit more open in our random selection. For example, we can choose a random color simply by choosing random red, green, and blue components.

;;; Procedure:
;;;   random-color
;;; Parameters:
;;;   (none)
;;; Purpose:
;;;   Selects and returns a random color.
;;; Produces:
;;;   color, a color.
;;; Postconditions:
;;;   It is difficult to predict color.
(define random-color
  (lambda ()
    (rgb.new (random 256) (random 256) (random 256))))

Similarly, we can choose a random brush. The easiest way to choose a random brush is to select a random element of the brushes list.

;;; Procedure
;;;   select-random-brush!
;;; Parameters:
;;;   (none)
;;; Purpose:
;;;   Select one of the brushes.
;;; Produces:
;;;   (nothing)
;;; Postconditions:
;;;   It is difficult to predict the brush.
(define select-random-brush!
  (lambda ()
    (envt.set-brush! (list-ref (brush.list) (random (length (brush.list)))))))

However, that procedure can choose from perhaps too many brushes. We might create a similar procedure that selects from a particular list of brushes.

;;; Procedure:
;;;   randomly-select-brush!
;;; Parameters:
;;;   brushes, a list of strings
;;; Purpose:
;;;   Select one of brushes.
;;; Produces:
;;;   (nothing)
;;; Preconditions:
;;;   All the strings in brushes name valid brushes.
;;; Postconditions:
;;;   The current brush is an element of brushes.
;;;   It is equally likely that each element of brushes is now the
;;;     active brush
(define randomly-select-brush!
  (lambda (brushes)
    (envt.set-brush! (list-ref brushes (random (length brushes))))))

If we wanted to select one of the circle brushes, we might use

> (randomly-select-brush! (list "Circle (01)" "Circle (03)" "Circle (05)" 
                                "Circle (07)" "Circle (09)" "Circle (11)" 
                                "Circle (13)" "Circle (15)" "Circle (17)" 
                                "Circle (19)"))

or

> (randomly-select-brush! (brush.list "Circle"))

In fact, we can rewrite select-random-brush! using this procedure.

(define select-random-brush!
  (lambda ()
    (randomly-select-brush! (list-brushes))))

It is, of course, also possible that we'll want to randomly select from other lists (not just lists of brushes). For example, we might want randomly select a shade of blue by selecting an element of the list of all colors with “blue” in their names. Hence, we'll define a generalized random selection procedure.

;;; Procedure:
;;;   list.random-element
;;; Parameters:
;;;   values, a list
;;; Purpose:
;;;   Randomly select an element of values.
;;; Produces:
;;;   value, a value
;;; Preconditions:
;;;   values is nonempty.
;;; Postconditions:
;;;   value is an element of values.
;;;   value is equally likely to be any element of values.
(define list.random-element
  (lambda (values)
    (list-ref values (random (length values)))))

We can now select a random shade of blue with the following procedure.
;;; Value:
;;;   colors.blues
;;; Type: 
;;;   List of colors.
;;; Value:
;;;   All the colors whose name includes the word "blue".
(define colors.blues
  (map cname->rgb (cname.list "blue")))


;;; Procedure: 
;;;   random-blue
;;; Parameters:
;;;   (none)
;;; Purpose:
;;;   Selects a color with blue in its name.
;;; Produces:
;;;   some-blue, a color
;;; Preconditions:
;;;   blue-colors is defined.
;;; Postconditions:
;;;   some-blue is a color whose name includes "blue".
;;;   It is difficult to predict which blue it is.
(define random-blue
  (lambda ()
    (list.random-element blue-colors)))

We can also rewrite randomly-select-brush! to use list.random-element. (The process of identifying common procedures and then rewriting code to use these common procedures is called refactoring, and it's a good practice.)

(define randomly-select-brush!
  (lambda (brushes)
    (envt.set-brush! (list.random-element brushes))))

Combining Procedures

Okay. Where are we? We have a way to randomly select colors and to randomly select brushes. Now we need ways to randomly draw things. For lines, circles, and rectangles, we can simply randomly select all of the parameters (perhaps within certain limits, such as the width and height of the image). For example, here is a procedure to draw a line between two randomly selected points.

;;; Procedure:
;;;   draw-random-line!
;;; Parameters:
;;;   image, an image
;;; Purpose:
;;;   Draw a random line in the image, assuming that its width
;;;   and height are as specified.
;;; Produces:
;;;   (nothing)
;;; Postconditions:
;;;   A new line has been added to image, using the current color
;;;   and brush.
(define draw-random-line!
  (lambda (image)
    (line image (random (image.width image)) (random (image.height image))
                (random (image.width image)) (random (image.height image)))))

There are many interesting variants, such as ones that use a fixed starting point, a fixed line length, and so on and so forth.

Now we know how to select colors unpredictably, how to select brushes unpredictably, and how to draw lines unpredictably. We can write a procedure that puts all of these techniques together.

;;; Procedure:
;;;   splat!
;;; Parameters:
;;;   image, an image
;;; Purpose:
;;;   Draw a line between random points, using a random color and
;;;   a random brush.
;;; Produces:
;;;   (nothing)
;;; Postconditions:
;;;   The foreground color may have changed.
;;;   The brush may have changed.
;;;   The image now contains another line.
(define splat!
  (lambda (image)
    (envt.set-fgcolor! (random-color))
    (select-random-brush!)
    (draw-random-line! image)
    (update-displays)))

Creative Commons License

Samuel A. Rebelsky, rebelsky@grinnell.edu

Copyright 2007 Janet Davis, Matthew Kluber, and Samuel A. Rebelsky. (Selected materials copyright by John David Stone and Henry Walker and used by permission.)

This material is based upon work partially supported by the National Science Foundation under Grant No. CCLI-0633090. Any opinions, findings, and conclusions or recommendations expressed in this material are those of the author(s) and do not necessarily reflect the views of the National Science Foundation.

This work is licensed under a Creative Commons Attribution-NonCommercial 2.5 License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc/2.5/ or send a letter to Creative Commons, 543 Howard Street, 5th Floor, San Francisco, California, 94105, USA.