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

2017/3/11

How to negate an if statement if a button is pressed

ObliviaOng ObliviaOng

2017/3/11

#
Turning to the Greenfoot community for help, once more -w-' So I need a code that if a button is pressed it would negate an if statement?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
private boolean leftDown;
    private boolean rightDown;
    private int leftCount;
    private int rightCount;
    public void Choices()
    {
        if (!leftDown && Greenfoot.isKeyDown("left"))
        {
            leftDown= true;
            leftCount++;
            if (leftCount == 1) addObject(new Utxt(),96,45);
            else if (leftCount == 2) addObject(new Utxt2(),96, 168);
            if (leftCount == 1) addObject(new Unkown(),48,30);
            else if (leftCount == 2) addObject(new Unkown(),48, 155);
        }
         
        if (!rightDown && Greenfoot.isKeyDown("right"))
        {
            rightDown= true;
            rightCount++;
            if (rightCount == 1) addObject(new Utxt(),96,45);
            else if (rightCount == 2) addObject(new Utxt2(),96, 168);
            if (rightCount == 1) addObject(new Unkown(),48,30);
            else if (rightCount == 2) addObject(new Unkown(),48, 155);
        }
         
        if (leftDown && !Greenfoot.isKeyDown("left"))
        {
            leftDown= false;
        }
         
        if (rightDown && !Greenfoot.isKeyDown("right"))
        {
            rightDown= false;
        }
    }
here's my code and what I intend to happen is that if leftCount == 1 it would negate rightCount == 1 and vice versa but i'm not sure how to code it so that if rightCount or leftCode == 2 it won't be affected by the negated command. I'm making a choice based game and decided to use the left and right button for the player to 'choose' between 2 choices.
danpost danpost

2017/3/11

#
I think if you add the two counts together, then the remainder after dividing by two will be 0 for one action and 1 for the other:
1
2
3
4
5
6
7
8
if ( (rightCount+leftCount)%2 == 0 )
{
    // perform one action
{
else // remainder is one
{
    // perform other action
}
ObliviaOng ObliviaOng

2017/3/12

#
I was able to code for it based on your suggestion, but I didn't exactly use the else part of the code that you gave. Though it was a really big help, thanks!
You need to login to post a reply.