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

2018/10/23

Get random number problem

Chipley Chipley

2018/10/23

#
I want to make the int variable to get a random number between 20 and 200 but its only doing 200 and i need it to make the heightshift change in the act section, here's the code if you can help me:
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
37
38
39
40
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
 
/**
 * Write a description of class FlappyWorld here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public class FlappyWorld extends World
{
    int counter = 0;
    int heightShift = Greenfoot.getRandomNumber(200);
    /**
     * Constructor for objects of class FlappyWorld.
     *
     */
    public FlappyWorld()
    {   
        // Create a new world with 600x400 cells with a cell size of 1x1 pixels.
        super(600, 400, 1, false);
         
        FlappyBird flappy = new FlappyBird();
         
        addObject(flappy, 100, getHeight()/2);
    }
     
    public void act()
    {
        counter++;
        if (counter == 100)
        {
            BottomPipe pippy = new BottomPipe();
             
            GreenfootImage image = pippy.getImage();
             
            addObject(pippy, getWidth(), getHeight()/2 + image.getHeight() - heightShift);
            counter = 0;
        }
    }
}
nolttr21 nolttr21

2018/10/23

#
The line, Greenfoot.getRandomNumber(200), will return a number between 0 and 199. Replace line 12 with this,
1
int heightShift = Greenfoot.getRandomNumber(199) + 2;
This will get a random number number between 0 and 198, and then add two. your minimum value will be 2 and your max will be 200. However, I believe your code will add a pipe at the same Y value every time.
danpost danpost

2018/10/23

#
Move line 12 to be line 35. At line 12, it is assigned a value only once (when the world is created). At line 35, it (as a new variable each time) will be assigned a (new) value each time you are creating a new BottomPipe object. Also, to get a number between 20 and 200, inclusive, use:
1
int heightShift = 20+Greenfoot.getRandomNumber(181);
You need to login to post a reply.