【问题标题】:Randomizing Coordinates through Arrays通过数组随机化坐标
【发布时间】:2018-04-24 13:38:31
【问题描述】:

当单击按钮时,我一直在尝试将按钮传送到屏幕上的随机位置(在 9 个给定坐标之一中),效果很好,但后来我看到一个常见的结果是按钮保持不动然后,我创建了一个不包含按钮当前坐标的新数组,该数组在按钮不在同一个地方的方面起作用,但是,由于某些未知的原因,现在我遇到了一个新问题-是的,我尝试调试 - 按钮只有 2 个坐标,代码如下:

    gameBtnRX = gameBtn.getX(); //Getting the current X of the button
    gameBtnRY = gameBtn.getY(); //Getting the current Y of the button


    switch ((int) gameBtnRX) { //Setting the _randArgsX array values
        case 200: _randArgsX = new float[]{600, 1000}; break;
        case 600: _randArgsX = new float[]{200, 1000}; break;
        case 1000: _randArgsX = new float[]{200, 600}; break;
        default: _randArgsX = new float[]{200, 600, 1000}; break;
    }

    switch ((int) gameBtnRY) { //Setting the _randArgsY array values
        case 500: _randArgsY = new float[]{1000, 1500}; break;
        case 1000: _randArgsY = new float[]{500, 1500}; break;
        case 1500: _randArgsY = new float[]{500, 1000}; break;
        default: _randArgsY = new float[]{500, 1000, 1500}; break;
    }

    randGameBtnX = rand.nextInt(_randArgsX.length - 1); //Randomizing one of (max 3) the values in the array
    randGameBtnY = rand.nextInt(_randArgsY.length - 1); //And putting them as the X and Y of gameBtn
    gameBtnX = _randArgsX[randGameBtnX];
    gameBtnY = _randArgsY[randGameBtnY];
    gameBtn.setX(gameBtnX);
    gameBtn.setY(gameBtnY);

(200,600,100是可能的X坐标,500,1000,15000是可能的Y坐标)

【问题讨论】:

  • 没有编译错误,所有变量都已经在代码开头设置好了
  • 第二个switch ((int) gameBtnRX)应该是switch ((int) gameBtnRY)
  • 谢谢,希望能成功。
  • 还是不行,结果一样,其实我没试过用两个开关gameBtnRX,是RY的时候试过了(后来我试过改成别的,给出了相同的结果,但风险更大且效率低下,所以我将其改回并得到了那个错字)

标签: java android arrays random


【解决方案1】:

Random.nextInt(int)

返回介于 0(含)和指定值(不含)之间的伪随机、均匀分布的 int 值。

因此,数组的长度不需要减一。

【讨论】:

  • 所以,如果gameBtnRx落入{200,600,1000},_randArgsX数组包含两个元素,因此nextInt方法只有一个选择0
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-12
  • 1970-01-01
  • 2021-10-03
相关资源
最近更新 更多