0

Working on a school project where we're supposed to modify a game to become educational. I want to cycle through numbers 0, 1, and 2 through the variable moduleThree. But the variable will not update when I set it equal to something else than what I originally defined it as, and it's incredibly frustrating.

I tried putting the if/else chain into a different method with return, but that didn't work. I tried putting it in multiple spots.

public class Alien extends Actor
{
    int SPEED = -7; // Speed of 10 in left direction "-"
    int tempType = (int)(Math.random() * ((2-0) + 1));
    int controlType = 0;
    int moduleThree = 0;

    public Alien() {

    }

    public void act() {
       move (SPEED);
       int timer = 10;
       if (timer>0){
           timer--;
           if(timer == 0) {
               timer = 10;
               controlType++;
               moduleThree = controlType % 3;
               if(moduleThree == 0){
                  ((SpaceLand)(getWorld())).pos.swap("bee");
               }
               else if(moduleThree  == 1){
                  ((SpaceLand)(getWorld())).pos.swap("alien");
               }
               else if(moduleThree  == 2){
                  ((SpaceLand)(getWorld())).pos.swap("soldier");
               }
           }
       }

moduleThree should cycle through 0, 1, and 2 as it calculated controlType % 3, but no update occurs. Even when I manually set it to something like 4, nothing happens. Extremely annoying.

Jack Tapia
  • 33
  • 1
  • 1
  • 4
  • This code looks specious; `timer` is `9` not `0`, so `if(timer == 0) {` is going to be `false`. Also, `((SpaceLand)(getWorld()))` scares me. – Elliott Frisch Sep 19 '19 at 03:04
  • @ElliottFrisch How is timer 9? Isn't timer-- supposed to loop, since it constantly goes when timer is above 0? – Jack Tapia Sep 19 '19 at 03:16
  • 1
    `timer--` is not a loop. It is `timer = timer - 1`; and since `timer` ***was*** ten, after that it is nine. – Elliott Frisch Sep 19 '19 at 03:19
  • 1
    @JackTapia you can make it loop by changing `if (timer>0)` to `while(timer > 0)`, though be aware you're resetting `timer` to 10 whenever it reaches 0 which will result in an infinite loop. – RyanHx Sep 19 '19 at 04:04

1 Answers1

1

The int timer = 10; line is declaring a local variable, so timer is always set to 10 at the beginning of each act() call and the variable is forgotten after each call. It looks like you meant to declare timer as a field of the class to keep its value between act calls. If you move the definition to beneath where moduleThree is declared, I think it will do what you intended.

Neil Brown
  • 3,558
  • 1
  • 27
  • 36