Moving objects around in a 2D array

I am trying to intialize an array with all zeros and move an object the "1" around in the array 14 times up and down bouncing off the boundaries and then after 14 times it should stop moving up to down and move left and right 14 times in the array, the array should print to the serial monitor after every move.

It seems majority of my code is fine but i cant figure out how to get it to change direction after 14 times, my idea was to put that for statement in the void loop and then change the DIR but then it just gets stuck bouncing on the border.

void loop() {
for (int f=0; f<14;f++);{
moveOne();
printArray();
delay(500);
}
for (int f=0; f<14;f++);{
DIR=2;
moveOne();
printArray();
delay(500);
}
}

WHOLE CODE

const int row = 8;
const int col = 8;
int currentRow = 4;
int currentCol = 6;
int myArray[col][row];
int DIR = 1;
void setup() {
Serial.begin(9600);
printArray();
moveOne();

}

void loop() {
for (int f=0; f<14;f++);{
moveOne();
printArray();
delay(500);
}
for (int f=0; f<14;f++);{
DIR=2;
moveOne();
printArray();
delay(500);
}
}
void moveOne(){
  myArray[currentRow] [currentCol] = 0;
switch (DIR) {
    case 1: // Up
      currentRow--;
      if (currentRow < 0) {
        currentRow = 1; // Reverse direction when hitting the top
        DIR = 3; // Change direction to down
      }
      break;

    case 2: // Right
      currentCol++;
      if (currentCol >=col) {
        currentCol = col - 2; // Reverse direction when hitting the right boundary
        DIR = 4; // Change direction to left
      }
      break;

    case 3: // Down
      currentRow++;
      if (currentRow >= row) {
        currentRow = row - 2; // Reverse direction when hitting the bottom
        DIR = 1; // Change direction to up
      }
      break;

    case 4: // Left
      currentCol--;
      if (currentCol < 0) {
        currentCol = 1; // Reverse direction when hitting the left boundary
        DIR = 2; // Change direction to right
      }
      break;
  }
  myArray[currentRow] [currentCol] = 1;
}
void printArray(){
  for (int i = 0; i < row; i++){
    for(int j = 0; j < col; j++){
      Serial.print(myArray[i][j]);
      Serial.print(" ");
  }
  Serial.println();
  
}
Serial.println("----------------");
}

an alternative to moving elements around is to consider a LINKED LIST

reference 1

reference 2

Reference 3

Both have distinct advantages.

1 Like

Your first for-loop starts with DIR=1 from outside of void loop() and the second initializes DIR=2 inside for every call to moveOne().

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.