This site requires JavaScript, please enable it in your browser!
Greenfoot back
PJaymz
PJaymz wrote ...

2017/3/1

Switch Statement, But For Non-Integers

PJaymz PJaymz

2017/3/1

#
Hello all... I'm working on my quiz game and have a lot of good work done, but have hit a major road block. When in the world of a specific question (I gave each question its own world), there are 9 possible answers, A-J (excluding I). I want the user to then be able to click on the answer in their keyboard, which works, but I can't get it to work dependent on the world (say, if you're in the "QuMaj" world and press "a" or "A" then it'd be correct and do a specific thing). I have tried doing if isKeyDown && getWorld == QuMaj, but I can't get that to work. If there's a way for that to work, I'd like that a lot. However, if there's no way for that to work, I'd like to implement a switch statement using the names of the worlds. This was the idea I had in mind:
        switch(getWorld())
        {
        case QuMaj(): if(Greenfoot.isKeyDown("a") || Greenfoot.isKeyDown("A"))
        {
            Greenfoot.playSound("correctamundo.mp3");
            nextQu();
        }
        else if(Greenfoot.isKeyDown("b") || Greenfoot.isKeyDown("B") || 
        Greenfoot.isKeyDown("c") || Greenfoot.isKeyDown("C") || Greenfoot.isKeyDown("d") ||
        Greenfoot.isKeyDown("D") || Greenfoot.isKeyDown("e") || Greenfoot.isKeyDown("E") ||
        Greenfoot.isKeyDown("f") || Greenfoot.isKeyDown("F") || Greenfoot.isKeyDown("g") ||
        Greenfoot.isKeyDown("G") || Greenfoot.isKeyDown("h") || Greenfoot.isKeyDown("H") ||
        Greenfoot.isKeyDown("j") || Greenfoot.isKeyDown("J"))
        {
            Greenfoot.playSound("wrong.mp3");
            nextQu();
        }
        break;
        
        
    }
In its current state, it wouldn't work, as switch statements require integers, and can't convert greenfoot.World to int, but I would like something like that if the && stated above wouldn't work. Thanks
danpost danpost

2017/3/1

#
You should probably have all your worlds extend another class that extends World -- something like my Super Level Support Class scenario Level class does. You should probably at least check it out.
davmac davmac

2017/3/1

#
I have tried doing if isKeyDown && getWorld == QuMaj
You can do:
if (getWorld() instanceof QuMaj) {
    if (Greenfoot.isKeyDown("a")) {
        // ...
    }
}
Alternatively:
if (getWorld().getClass() == QuMaj.class) {
    if (Greenfoot.isKeyDown("a")) {
        // ...
    }
}
However, from a design perspective it is better to use polymorphism (as danpost suggests). You don't need to check for "a" and "A"; they would be the same key.
You need to login to post a reply.