gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 17:45:43 25 4
gpt4 key购买 nike

我正在制作一个轮盘游戏,我为插槽创建了一个数组列表,它们已在有序列表中定义,共有 38 个插槽,其位置(0-37)、颜色和数字。

在“旋转方法”中,我尝试从轮子集合/列表中选择一个随机起始插槽,然后根据延迟功能旋转一些插槽。

如何从我的集合中选择一个随机槽来开始此过程?

我的 Collection

    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();
}
}

最佳答案

您可以使用Random::nextInt用于生成随机整数:

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
}

关于java - 如何从有序列表中选择随机起始位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55555446/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com