Wednesday, April 15, 2015

CSE Custom Functions

On April 9, 2015 my teacher showed my class how to create custom functions using void. Some of the functions behave like calculators while others behave as stamps. Also, we learned how to use keyPressed to alter the shape of our stamps. Below is the code that my teacher showed the class and my modified version of that code.
*In order for the codes to work on other computers the loadFont must be changed*


                                                       Code taught by Mr.  Miles
// custom functions and methods
PFont f;

// returnType functionName(parameterType parameterName, ...)
void setup() { // function header
 f = loadFont("BankGothic-Medium-48.vlw");
 textFont(f, 32);
 size(1000, 800);
}

void draw() {
 fill(255);
 text(factorial(16), 15, 50);
}

// returnType functionName(parameterType parameterName, ...)
// factorial 5! = 5 * 4 * 3 * 2 * 1
int factorial(int a) {
 // a! = a * (a - 1) * (a - 2) * ... * 1
 // a! = 1 * 2 * 3 * ... * a

   int product = 1;

 for (int i = a; i > 1; i--) {
   product = product * i; // product *= i;
 }

 return product;
}

// default stamp function
void stamp() {
 stamp(1);
}

// specialized stamp function
void stamp(float s) {
 stroke(100, 34, 3);
 fill(255, 0, 0, 100);
 ellipse(mouseX, mouseY, 40 * s, 40 * s);
 ellipse(mouseX, mouseY, 30 * s, 30 * s);
 ellipse(mouseX, mouseY, 20 * s, 20 * s);
 fill(100, 50);
 rect(mouseX - 20 * s, mouseY - 20 * s, 40 * s, 40 * s);
}

void mousePressed() {
 stamp();
}

void keyPressed(){
 if(key == 's'){
   stamp(.5);
 }
 else if(key == 'w'){
   stamp(3);
 }
}

                                                                       My modified code
PFont f;

//void is a return type
//setup is the function name
// in parenthesis is the parameter type
void setup(){
 f = loadFont("NanumGothicBold-30.vlw");
 textFont(f,20);
 size(500,500);
}

void draw(){
 fill(0);
text(factorial(5), width/2,height/2);
}

// factorial 5! = 5*4*3*2*1

int factorial(int a){
// a = a * (a-1) * (a-2) * (a-3) .... (factorial)
// a = 1 + 2 + 3 + 4 ... = a            (factorial)

int product = 1;

for(int i = a; i > 1 ; i--){
 product = product * i;
}
return product;
}


//stamp function
void stamp(){
 stamp(1);

}

void stamp(float s){
 stroke(#FA0D0D);
 strokeWeight(4);
 fill(255,200);
 ellipse(mouseX,mouseY, 20*s, 20*s);
 fill(255,0);
 rect(mouseX-20,mouseY-20, 40*s, 40*s);

}


void mousePressed(){
  stamp();
}

void keyPressed(){
 if(key == 's'){
   stamp(.5);
 }
 else if(key == 'w'){
   stamp(3);
 }

}




No comments:

Post a Comment