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

2015/4/5

How to make method run only once?

jennipho jennipho

2015/4/5

#
So in the code below, I wanted to have an instruction screen come up first. Then, after the player "clicks" to start the game, I want to set another screen and populate my actors. I tried doing the populate stuff in the constructor but that doesn't work. Anyways, if the player accidentally double clicks, then everything is populated twice. How can I make sure the code under the act method only run once? Or is there a code I can have to check if its already been done and how the system would then ignore the "if click...do this.." code?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public SpongeRace()
{   
    super(1000, 800, 1);
    setBackground("spongeinstruct3.jpg");
 
}
 
 
public void act()
{
    if(Greenfoot.mouseClicked(null))
    {
        setBackground("lane.jpg");
        addObject(new Snellie(), 960, 150);
        addObject(new Gary(), 960, 320);
        addObject(new Rock(), 960, 480);
        addObject(new Haru(), 960, 650);
        addObject(new Finish(), 50, 400);
    }
 
}
Super_Hippo Super_Hippo

2015/4/5

#
You can use a boolean field to save if it was already populated and only check for the click if it wasn't:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
private boolean populated = false;
 
public SpongeRace()
{   
    super(1000, 800, 1);
    setBackground("spongeinstruct3.jpg");
}
 
public void act()
{
    if(!populated && Greenfoot.mouseClicked(null))
    {
        populated = true;
        setBackground("lane.jpg");
        addObject(new Snellie(), 960, 150);
        addObject(new Gary(), 960, 320);
        addObject(new Rock(), 960, 480);
        addObject(new Haru(), 960, 650);
        addObject(new Finish(), 50, 400);
    }
}
jennipho jennipho

2015/4/5

#
BLESS YOU THANK YOU SO MUCH
You need to login to post a reply.