Array Object Logical Error
in
Programming Questions
•
10 months ago
Greetings
I am studing the book Learning Processing by Daniel Shiffman
I am at the exercise 9-7 trying to do the advanced problem and my classes are
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Snake s0;
Snake s1;
void setup() {
size(displayWidth/2,displayHeight/2);
smooth();
// Initialize
s0 = new Snake(50);
s1 = new Snake(25);
}
void draw() {
background(255);
// Update and display
s0.update(mouseX-30,mouseY);
s0.display();
// Update and display
s1.update(mouseX+30,mouseY);
s1.display();
}
~~~~~~~~~~~~~~~~~~~~~~~~
class Snake {
Point[] points;
// The constructor determines the length of the snake
Snake(int n) {
points = new Point[n];
for(int i = 0; i < points.length; i++){
points[i] = new Point(0,0);
}
}
void update(int newX, int newY) {
// Shift all elements down one spot.
// xpos[0] = xpos[1], xpos[1] = xpos = [2], and so on.
// Stop at the second to last element.
for (int i = 0; i < points.length-1; i++ ) {
points[i] = points[i+1];
points[i] = points[i+1];
}
// Update the last spot in the array with the mouse location.
points[points.length-1].x = newX;
points[points.length-1].y = newY;
}
void display() {
// Draw everything
for (int i = 0; i < points.length; i++ ) {
// Draw an ellipse for each element in the arrays.
// Color and size are tied to the loop's counter: i.
stroke(0);
fill(255-i*5);
ellipse(points[i].x,points[i].y,i,i);
}
}
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class Point {
int x;
int y;
Point(int x_, int y_) {
x = x_;
y = y_;
}
}
Could someone tell me what is the problem?
The ouput should be
http://www.learningprocessing.com/exercises/chapter-9/exercise-9-7/
http://www.learningprocessing.com/exercises/chapter-9/exercise-9-7/
1