Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do i loop through an array backwards?

i am attempting to make snake in java script using p5.js and have the snake as an array where the head is the first index and the tail every spot after. i am trying to loop through the array backwards for moving the boxes so they don’t all end up on one square but the rest of the code stopped working when i tried this. the head is supposed to go down and this works when i loop through normally with the head at the other end, but need to go backwards so i can add more into the array. here is my code:

function setup() {
  createCanvas(400, 400);
}

class SnakeBlock{
  constructor(x, y, isHead){
    this.x = x;
    this.y = y;
    this.isHead = isHead;
  }
  
  draw(){
    fill("green");
    noStroke();
    rect(this.x * 40, this.y * 40, 40, 40)
  }
  
  move(snake, x){
    if(this.isHead == true){
      this.y += 1;
    }
    else{
      this.y = snake[x - 1].y;
      this.x = snake[x - 1].x;
    }
  }
}

var length = 4;

var moveCounter = 20;

var snake = [new SnakeBlock(0, 0, true),new SnakeBlock(1, 0, false),new SnakeBlock(2, 0, false), new SnakeBlock(3, 0, false)];

function draw() {
  background(0);
  for(let x = length - 1; x > 0; x--){
      snake[x].draw();
  }
  if(moveCounter == 0){
    for(let x = length - 1; x > 0; x--){
      snake[x].move(snake, x);
      snake[x].draw();
    }
    moveCounter = 20;
  }
  else{
    moveCounter -= 1;
  }
  
  
}

back when i had it looping the other way the snake head would move down as seen in the move() function in the snake class, but when i loop backwards it doesn’t move down at all and just stays in place. yes i did reverse the array when looping the other way.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Simple, loop the other way. Instead of i++ use i--:

for(i = 0; i < array.length; i++){
    // do something with array[i]
}

// you go backwards:
for(i = array.length - 1; i >= 0; i--){
    // do something with array[i]
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading