This exercise gives you a little more practice with writing
loops. That will help with the next exam!
A second goal of this
exercise is to make
sure that you know how to color every pixel individually using a
function that depends on the pixel's coordinates and
some other interesting information.
Your First Task
Write a program that opens a square graphics window of size
S × S. The program then has a loop that prints the
numbers from -12.0 to +12.0 in increasing increments of 0.25. These
numbers appear on the graphics screen by calling these commands
(where t is the number that you want to print):
The whole program will take about 24 seconds to run. No need for
double buffering.
Adding a Function
Add a function to your program with this prototype:
void shade(double t);
The function does a putpixel(px, py, color) for every pixel location
(px, py). For a pixel that is at (px, py), you
should calculate the color by these formulas:
Calculate a double number called denominator that is equal to two times
S. Use a double number for this, so that when when we divide by this
number, we will get a double number as the answer.
If t is negative, then calculate an integer called blue_amount
by the formula:
int(255 * pow((S + py - px)/denominator, -t/6.0))
If t is non-negative, then calculate an integer called
blue_amount by the formula:
int(255 * pow((py + px)/denominator, t/6.0))
You'll need to include <cmath> in order to get the pow function.
From these formulas, the number blue_amount is an integer that could
be as small as 0 or as large as 255. This number is used to create a
new color that has a varying amount of blue. In winbgim, colors are
integers, so you should declare an int called color and assign:
color = COLOR(0, 0, blue_amount);
This uses the COLOR function to create a color that has no red, no green
and an amount of blue that depends on the blue_amount variable.
The function you write must then use putpixel to color every pixel in the
window according to the color calculated above.
The formulas
that I've written above create two kinds of patterns:
If t is negative, then you'll get a shading from blue (in the bottom
left corner) to black (in the top right corner). If t is not
negative, then the shading goes from blue (in the lower right corner)
to black (in the upper left corner).
Once you've written this function, please call it in your main program
instead of printing t. Also, get rid of the clearviewport and delay.
Extra Requirement:
How often does your function calculate t/6.0?
Can you ensure that this value is computed only once?
Don't keep calculating it over and over!
Calculate it once and store the result in a local variable. This
makes the function more efficient.