使球在不同位置不断出现

时间:2013-11-15 07:41:23

标签: java

我是一名Java初学者,我正在尝试制作一个程序,其中白球不断出现在屏幕上。在一个球出现在下一个球之前应该有几秒钟的暂停,并且球需要出现在屏幕上的不同位置。我需要帮助使用RandomGenerator使球出现在不同的地方。任何帮助将不胜感激!

private RandomGenerator rgen = new RandomGenerator();

//~ Constructor ...........................................................

// ----------------------------------------------------------
/**
 * Creates a new BubbleGame object.
 */
public void init()
{
    //call method to create regions
    CreateRegions();

    //add mouse listeners
    addMouseListeners();

    //loop to add bubbles
    while (true)
    {
        //create a filled bubble
        GOval bubble = new GOval (100, 100, 50, 50);
        bubble.setFilled(true);
        bubble.setColor(Color.WHITE);

        //randomly generate coordinates within the field
        int rgen = 

        //add the bubble and pause 
        add(bubble);
        Thread.sleep(3000);

    }
}

3 个答案:

答案 0 :(得分:0)

您可以使用Random.nextInt(maxInt)生成0到maxInt-1之间的数字。

Random rnd = new Random();
rnd.nextInt(10); // 0-9

答案 1 :(得分:0)

我猜你正在使用Swing(或类似的技术)。在Event Dispatch Thread中使用while(true)总是一个坏主意。改为使用Swing Worker。

随机非常容易使用。 Random.nextInt(n)将为您提供0到n-1之间的整数。

您还可以随机化气泡颜色,其位置和大小。这是你的选择。您可以通过单击鼠标使它们消失。

答案 2 :(得分:0)

当你通过_size时,这个函数将填充一个带有menny随机数的数组,作为值和_minVal&之间的值。 _maxVal。 所以,如果你需要4个坐标,那么4个大小等等。

public int[] makeRanArray(int _Size, int _minVal, int _maxVal)
{
    int[] arr = new int[_Size];

    for (int i = 0; i < _Size; i++){ 
        arr[i] = _minVal + (int)(Math.random() * _maxVal);
    }
    return arr;
}