Thursday, January 15, 2015

CSE Loops

Recently I had a new assignment in Computer Science Engineering. We had to modify a code given to us by adding a  keyPressed() function (Links to an external site.) that updated the background color. The code we were given to modify is below.

/* global variables to keep track of the amount of red, green and blue (respectively) in the background */

int r, g, b;


/* setup the window with an initial background color of black */

void setup(){

 size(300, 300);

 r = 0;

 g = 0;

 b = 0;

 background(r, g, b);

}


/* update the background color */

void draw(){

 background(r, g, b);

}


/* DO NOT MODIFY ANY CODE ABOVE THIS LINE */


/* allows the user to increase and decrease the values of r, g, and b */



In order to update the background color I added these codes:

void keyPressed() {

 if (key == 'r') { // change fill color

   r+= 20;

 } else if (key == 'g') { // change fill color

   g += 20;

 } else if (key == 'b') { // change fill color

   b += 20;

 } else if (key == 't') { // change fill color

   r -= 20;

 } else if (key == 'h') { // change fill color

   g -= 20;

 } else if (key == 'n') { // change fill color

   b -= 20;

 }

}



//Key

//r=red +20

//g=green+20

//b=blue+20



//t=red-20

//h=green-20

//n=blue-20

Basically, these codes say if the key r is pressed increase red by 20, if the key g is pressed increase green by green and if the key b is pressed increase blue by 20. I then used the keys t, h, and n to decrease red, green and blue by 20 depending on which button was pressed. I also made a key at the end so my teacher would know which keys to press to increase and decrease certain colors. This code was very easy and didn't take long at all. The full code is down below.

/* global variables to keep track of the amount of red, green and blue (respectively) in the background */

int r, g, b;



/* setup the window with an initial background color of black */

void setup() {

 size(300, 300);

 r = 0;

 g = 0;

 b = 0;

 background(r, g, b);
}



/* update the background color */

void draw() {

 background(r, g, b);
}
void keyPressed() {
 if (key == 'r') { // change fill color
   r+= 20;
 } else if (key == 'g') { // change fill color
   g += 20;
 } else if (key == 'b') { // change fill color
   b += 20;
 } else if (key == 't') { // change fill color
   r -= 20;
 } else if (key == 'h') { // change fill color
   g -= 20;
 } else if (key == 'n') { // change fill color
   b -= 20;
 }
}

//Key
//r=red +20
//g=green+20
//b=blue+20

//t=red-20
//h=green-20

//n=blue-20

“If the code and the comments do not match, possibly both are incorrect.”
– Norm Schryer





No comments:

Post a Comment