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

我正在制作一个轮盘游戏,我已经为插槽创建了一个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();

        }

    }


浮云间
浏览 86回答 2
2回答

冉冉说

您可以使用随机数::下一步生成随机整数: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 -> {&nbsp; &nbsp; // e is the element});for圈:for(int i = random; i < 38; i++) {&nbsp; &nbsp; var e = wheel.get(i); // e is the element}

红颜莎娜

两个简单的选项:使用 java.util.Random 在数组的可能索引范围内生成一个随机 int。使用收集.shuffle() 简单地将列表按随机顺序排列,然后每次都选择第一个条目。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java