0

So we recently started coding in college and I'm having trouble with my game in Greenfoot. I should normally be able to collect 5 coins on level 1, go to the door, and progress to level 2 and so on... This is my piece of code so far:

    private void collect () {
        Actor coin = getOneIntersectingObject(Coin.class);

        if (coin != null) {
            getWorld().removeObject(coin);
            coinsCollected++;
        }
        if (coinsCollected == 5 && fiveCoinsLevel1 == false) {
            if (this.getWorld().getClass() == Level_1.class) {
                getWorld().addObject(new door_temp(), 157, 162);
                fiveCoinsLevel1 = true;
                secondLevel();
                coinsCollected = 0;
            }
        }

        if (coinsCollected == 5 && fiveCoinsLevel2 == false && fiveCoinsLevel1 == true) {
            if (this.getWorld().getClass() == Level_2.class) {
                getWorld().addObject(new door_temp(), 157, 162);
                fiveCoinsLevel2 = true;
                thirdLevel();
            }
        }
    }

After that I have two methods that set the world to either level 2 or 3:

public void secondLevel ()  {
        Actor secondlvl = getOneIntersectingObject(door_temp.class);

        if (secondlvl != null) {
            Greenfoot.setWorld(new Level_2());
        }
    }

    public void thirdLevel ()  {
        Actor thirdlvl = getOneIntersectingObject(door_temp.class);

        if (thirdlvl != null) {
            Greenfoot.setWorld(new Level_3());
        }
    }

Now for some reason, once I collect all 5 coins on level 1 and reach the door to go to level 2, it sends me straight to level 3.

Thanks to anyone who can help me :)

Snackoverflow
  • 736
  • 9
  • 31
  • Move the third `coinsCollected` - check before the check for level two. The problem with your code is the level2 check sets the parameters such that the following level3 check is also true, so advancing to level3 immediately. – Adder Nov 18 '19 at 16:17
  • 1
    More specifically, this wouldn't be the case if your `coinsCollected = 0;` line was before `secondLevel();` *or* if your `coinsCollected == 5` checks only ran if a coin was just collected (i.e. put them in the `if(coin != null)` condition) – Klaycon Nov 18 '19 at 16:21
  • At the moment this is mistagged. Should be java, not javascript – PartyLich Nov 18 '19 at 16:34
  • I tried what you said @Adder... Unfortunately with no luck... Am I doing this correctly?```fiveCoinsLevel1 = true; coinsCollected = 0; secondLevel();}``` –  Nov 18 '19 at 20:16

0 Answers0