Having some issues with the processing language where it says the case expressions must be constants, but I could have sworn they were. I don't know what I am doing wrong here. Anyone have some tips?

int gameState;
static int MENU = 0;
static int GAME = 1;
static int OPTIONS = 2;

void setup() {
  screenSizex = 960;
  screenSizey = 640;
  size(screenSizex, screenSizey);
  gameState = MENU;
}

void draw(){
  switch(gameState) {
    case MENU:
      //does menu stuff
      break;
    case OPTIONS:
      //does options stuff
      break;
    case GAME:
      //does game stuff
      break;
    default:
      break;
  }
}

void mousePressed() {
  if (//over some object) {
    gameState = GAME;
  }
  else if (//over some object) {
    gameState = OPTIONS;
  }
  else if (//over some object) {
    exit();
  }
}
有帮助吗?

解决方案

static just makes fields belong to the class instead of an instance of the class. A static field can be modified at any time, so it isn't constant. You need to make the fields final if you want them to be treated as constant values:

static final int MENU = 0;
static final int GAME = 1;
static final int OPTIONS = 2;

Marking the fields as static final means that they both exist at the class level (they don't belong to any particular instance of the class, nor do you need an instance to access the values) and cannot be modified after initialization (effectively making the values constant).

However, I think this would really be a good place for you to use an enumeration type. Here's how I'd change the game state declaration:

GameState gameState;
enum GameState {
  MENU, GAME, OPTIONS
}

And here's what you'd have to do to get the rest of the code to work with that:

void setup() {
  screenSizex = 960;
  screenSizey = 640;
  size(screenSizex, screenSizey);
  gameState = GameState.MENU;
}


void draw(){
  switch(gameState) {
    case MENU:
      //does menu stuff
      break;
    case OPTIONS:
      //does options stuff
      break;
    case GAME:
      //does game stuff
      break;
    default:
      break;
  }
}

void mousePressed() {
  if (/*over some object*/) {
    gameState = GameState.GAME;
  }
  else if (/*over some object*/) {
    gameState = GameState.OPTIONS;
  }
  else if (/*over some object*/) {
    exit();
  }
}

Basically all I had to change was adding a qualifying GameState. in front of all occurances of MENU, GAME and OPTION, with the exception of the ones in the case statements since the compiler can infer that those are values of GameState based on the type of the expression used in the switch. Using an enum instead of an int has the added advantage that it restricts the value of gameState to only the 3 valid values, instead of the entire range of integers.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top