Creating a moving snake on a predefined grid

I’m working on a game on which a snake/ centipede can move on a grid by mouseclicking on grid spaces next to it. Its body consists of 10 pieces which all follow the previous locations of its head. My question is, where do I start? I have several ideas but am quite clueless on where to start or if it will work at all. My idea was to run it through a for loop which generates the body parts then run it through an if loop that would check the clicked location and create a new rectangle on the specific grid. I assume there has to be another way of doing it with other functions available. I checked the API but couldn’t quite find something. Any help?

? what you searched for ?

or


please show us your code up to now

  • grid logic
  • mouseclick? and on NEXT logic
  • create rect on that location

As of now, a grid which also includes a mouseclicked function. There’s objects hidden on the grid which the snake has to collect for points.

int score = 0;
int[][] items = new int[30][30];


void placeFruitInit() {
  
  for ( int i = 0; i < 30; i++) {
    for ( int j = 0; j < 30; j++) {
      
      items[i][j] = int(random(-5, -1));
      
    }
  }
};


void placeFruit() {
  
  for ( int i = 0; i < 30; i++) {
    for ( int j = 0; j < 30; j++) {
      
      int t = items[i][j];
      
      if ( t < 0 ) {
        
        fill(128);
        stroke(0);
        rect(30*i, 30*j, 30, 30);
        
      } else if ( t == 2 ) {
        
        fill(255, 0, 0);
        stroke(0);
        rect(30*i+2, 30*j+2, 26, 26);
        
      } else if ( t == 3 ) {
        
        fill(255, 255, 0);
        stroke(0);
        rect(30*i+2, 30*j+2, 26, 26);
        
      } else if ( t == 4 ) {
        
        fill(0, 255, 0);
        stroke(0);
        rect(30*i+2, 30*j+2, 26, 26);
          
      }      
    }
  }
};

placeFruitInit() is called in setup. Rest in draw.

Method for mouseClicked()

void mouseClickGrid() {
  
  int x = int( mouseX / 30 );
  int y = int( mouseY / 30 );
  
  if ( x >= 0 && y >= 0 && x < 30 && y < 30 ) {
    
    items[x][y] = abs(items[x][y]);

  }
  
  println(score);

};