Wednesday, December 3, 2014

CSE Moving Lines

A few days ago in Computer Science Engineering we learned how to create lines that follow the mouse and has a background that changes color when the mouse is pressed. The background was the easiest part because all we had to do was create an int, we chose color c then using what we learned previously when doing our assignment called 2 programs. Using that information I created the code below:

 void mousePressed() {
  c = color((int)random(256), (int)random(256), (int)random(256));
}

Then we created two variables to keep track of the vertical lines x position and the horizontal lines y position. We called these two global variables int x and int y. While talking in class we learned about mouseX and mouseY. mouseX and mouseY keep track of the current horizontal  and vertical coordinates of the mouse. This is helpful because  in order for the lines to follow the mouse the computer must know where the mouse is. We all agreed that if statements should be used in this code. Our first if statement was, if the position of mouseX was less than x or to the left the x position of the line should be decreased. We type this into processing and realized it worked. We used this same mindset to finish the rest of the code. So, if mouseY was above, they-position of the line should decrease, and so on. Our finished code is below. 

  if (mouseX < x) {
    x--;
  } // otherwise

  else if (mouseX > x) {
    x++;
  }

  if (mouseY < y) {
    y--;
  } // otherwise

  else if (mouseY > y) {
    y++;
  }

  line(x, 0, x, height);
  line(0, y, width, y);
} // end of draw

Once we pieced these two codes together we were finished the assignment. The entire code is down below. 

// lines  follow the mouse
// we need to keep track of the vertical line's x-position
// we need to keep track of the horizontal line's y-position

// global variables
int x;
int y;
color c;

void setup() {
  size(700, 500);
  c = color((int)random(256), (int)random(256), (int)random(256));
  background(c);

  frameRate(300);
  x = width / 2;
  y = height / 2;
} // end of setup

void draw() {
  background(c);

  // if mouse is to the left, decrease x-position of the line
  if (mouseX < x) {
    x--;
  } // otherwise
  else if (mouseX > x) {
    x++;
  }

  // if mouse is above, decrease y-position of the line
  if (mouseY < y) {
    y--;
  } // otherwise
  else if (mouseY > y) {
    y++;
  }

  line(x, 0, x, height);
  line(0, y, width, y);
} // end of draw

void mousePressed() {
  c = color((int)random(256), (int)random(256), (int)random(256));
}

/*
// single condition if statement
 if(condition){
 ...
 }

 // multi-condition if statement
 if(condition){
 ...
 }
 else if(condition){
 ...
 }
 ...
 else{
 ...
 }

 */

“It’s OK to figure out murder mysteries, but you shouldn’t need to figure out code.  You should be able to read it.”
– Steve McConnell
   

No comments:

Post a Comment