Problem with array of objects from a class

I think you’ve initialised your array incorrectly.

check this video if you want to confirm how to initialize an array. Timestamp is 3:48.

static int dimStart=3;
int dim=dimStart;
Snake.sDir dir;
Snake[] nPiece = new Snake[dim];

static class Snake {

  public int x;
  public int y;

  enum sDir {
    Up, Left, Down, Right
  }
  public void move(int a, int b) {

    x=a;
    y=b;
  }
  public void reset(int a, int b) {

    x=a;
    y=b;
  }
};

void sSetup(Snake[] s) {
  
  s[0].x=width/2;
  s[0].y=height/2;
  for (int a=1; a<s.length; a++) {
    s[a].x=s[a-1].x-10;
    s[a].y=s[a-1].y;
  }
}

void sMove() {

  switch(key) {

  case 'w':
    dir=Snake.sDir.Up;
    break;
  case 'a':
    dir=Snake.sDir.Left;
    break;
  case 's':
    dir=Snake.sDir.Down;
    break;
  case 'd':
    dir=Snake.sDir.Right;
    break;
  }
}

void setup() {

  for(int i=0;i<nPiece.length;i++){
  
  nPiece[i] = new Snake();
  }
    sSetup(nPiece);
  size(1080, 720);
}

void draw() {

  background(0);
  for (int a=0; a<nPiece.length; a++) {
    rect(nPiece[a].x, nPiece[a].y, 10, 10);
  }
}
1 Like