How to return to last stage?

Hi guys, i've got a problem here about how to return to the last page. I am writing an interactive story, and i am going to write a function when player click it the page will go back to the last one and allow the player to make choice again. But i always got bug said: Array Index Out Of Bounds Exception: Array index out of range

Here is my code

Main tab
IntList allPage;
Page page;
final int startScreen = 0; // possible states
final int play = 1;
int state = startScreen;

String txtChoices[];
int nextPage[][] = {{2, 7, 8}, 
                    {3, 4, 5}, 
                    {16, 17, 8}
                    };

int regretChance = 2;

void setup() {
  size(1600, 800);
  txtChoices = loadStrings("choices.txt");
}

void draw() {
  switch(state) {
  case startScreen:
    //do nothing
    break;

  case play:
    page.returnFunction();
     page.mouseClicked();
    break;
  }
}
void mouseClicked() {
  switch(state) {
  case startScreen:
    state=play;
    // ---------------------------------------------- 
    imageMode(CENTER);
    allPage = new IntList();
    page = new Page(0);
    break;
  case play:

    break;
  }
}

Class Page

    class Page {
  int id;
  int numberOfChoice;
  String choices[];


  Page(int idOfPage) {
    id = idOfPage;
    allPage.append(id);
    choices = split(txtChoices[id], "  ");
     numberOfChoice = 0;
  }


  void returnFunction() {//////////////////////
  if(id>0){
    if (numberOfChoice == choices.length+1) {// if player choose the last choice(back to last stage)
      allPage.remove(allPage.size()-1);//delete the last one page
      page = new Page(allPage.get(allPage.size()-1));//return to previous page
    } else {
      page = new Page(nextPage[id][numberOfChoice-1]-1);//jump to next page
    }
  }
  }


   void mouseClicked(){
     if (numberOfChoice == 0 && id != 0 && regretChance > 0 && id < 19) {
      int i = choices.length;
      float h= mouseY-(2.3 * height/3+ (i-1)*height/20);
      float w= mouseX-width/40;
      if (w > 0 && mouseX-width/40 < textWidth((i+1)+": Back to last page") && h<height/20 && mouseY-h >0) {
        numberOfChoice = i+1;
        regretChance --;
      }
    }
 }
}

What i post on the top is a part of the whole code, the whole code is too long, so i chosen the most important pieces to explain my trouble. I know you guys in this community are the best! If you are free please help me ? Many thanks!

Answers

  • At which line number is error?

    Which variable is causing it? The variable is probably <0 OR > allPage.size()

    Especially allPage could be empty then we would get that error too

    Use println to check your variables

    println(allPage.size()); etc.

Sign In or Register to comment.