为了账号安全,请及时绑定邮箱和手机立即绑定

如何从有序列表中选择随机起始位置?

如何从有序列表中选择随机起始位置?

浮云间 2022-09-22 19:31:56
我正在制作一个轮盘游戏,我已经为插槽创建了一个Arraylist,它们已经在有序列表中定义,有38个插槽的位置(0-37),颜色和数字。在“Spin方法”中,我试图从车轮集合/列表中选择一个随机的起始插槽,然后根据延迟功能旋转一些插槽。如何从我的收藏中选择一个随机插槽来开始此过程?我的收藏    List<Slot> wheel = new ArrayList<Slot>();    GameEngine gameEngine;    public GameEngineImpl() {        Color colorArray[] = new Color[] { Color.GREEN00, Color.RED, Color.BLACK, Color.RED, Color.BLACK, Color.RED,                Color.BLACK, Color.RED, Color.BLACK, Color.RED, Color.BLACK, Color.RED, Color.BLACK, Color.RED,                Color.BLACK, Color.RED, Color.BLACK, Color.RED, Color.BLACK, Color.GREEN0, Color.BLACK, Color.RED,                Color.BLACK, Color.RED, Color.BLACK, Color.RED, Color.BLACK, Color.RED, Color.BLACK, Color.RED,                Color.BLACK, Color.RED, Color.BLACK, Color.RED, Color.BLACK, Color.RED, Color.BLACK, Color.RED };        int numberArray[] = new int[] { 00, 27, 10, 25, 29, 12, 8, 19, 31, 18, 6, 21, 33, 16, 4, 23, 35, 14, 2, 0, 28,                9, 26, 30, 11, 7, 20, 32, 17, 5, 22, 34, 15, 3, 24, 36, 13, 1 };        for (int position = 0; position < 38; position++) {            wheel.add(new SlotImpl(position, colorArray[position], numberArray[position]));        }    }旋转方式@Override    public void spin(int initialDelay, int finalDelay, int delayIncrement) {        Slot slot;        while (initialDelay < finalDelay) {        //  TODO selecting a random starting slot on the wheel                 }            }            // Delay function            delay(delayIncrement);            // Increase increment            initialDelay += delayIncrement;        }    }    // Method to delay spinning    private void delay(int delay) {        try {            Thread.sleep(delay);        } catch (InterruptedException e) {            Thread.currentThread().interrupt();        }    }
查看完整描述

2 回答

?
冉冉说

TA贡献1877条经验 获得超1个赞

您可以使用随机数::下一步生成随机整数:

int random = new java.util.Random().nextInt(38);

//nextInt: int value between 0 (inclusive) and the specified value (exclusive)

若要循环访问元素,可以使用流或 for 循环。下面是流的示例:


wheel.subList(random, 37).stream().forEach(e -> {

    // e is the element

});

for圈:


for(int i = random; i < 38; i++) {

    var e = wheel.get(i); // e is the element

}


查看完整回答
反对 回复 2022-09-22
?
红颜莎娜

TA贡献1842条经验 获得超12个赞

两个简单的选项:

  • 使用 java.util.Random 在数组的可能索引范围内生成一个随机 int。

  • 使用收集.shuffle() 简单地将列表按随机顺序排列,然后每次都选择第一个条目。


查看完整回答
反对 回复 2022-09-22
  • 2 回答
  • 0 关注
  • 78 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信