microsoft / pxt-adafruit

Microsoft MakeCode editor for Adafruit Circuit Playground Express
https://makecode.adafruit.com
Other
81 stars 77 forks source link

Repeat Pick Random not random adafruit curcuit playground blocks #1179

Open asaawens opened 4 years ago

asaawens commented 4 years ago

https://makecode.com/_CYU1mq4atcRV

I loaded this on 2 Adafruit Curcuit Playgound devices. They synch start, but despite being told to pick a random number of repeat times, both controllers repeat the loops the same amount of times. So the sequence progresses through the music in the same way. Why would the random seed be the same each time it is run?

*Describe the bug** A clear and concise description of what the bug is.

To Reproduce Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior A clear and concise description of what you expected to happen.

Screenshots Add screenshots to help explain your problem. You can copy paste the screenshot in the github report. The .gif screen recording is very useful as well.

Desktop (please complete the following information):

Smartphone (please complete the following information):

Additional context Add any other context about the problem here.

riknoll commented 4 years ago

@mmoskal FYI

mmoskal commented 4 years ago

feel free to ping me when you're doing next release

smagoun commented 3 years ago

I ran into this too. I believe the random seed is hardcoded for the SAMD21 boards (like CPX), and this is an issue upstream rather than in pxt-adafruit.

For example a simple program that prints 20 random numbers in the range 0-10:

input.buttonB.onEvent(ButtonEvent.Click, function () {
    for (let i = 0; i < 20; i++) {
        console.log(Math.randomRange(0, 10))
    }
})

...will always start: 0,6,0,6,0,0,1,9,4,2,10,3,10,3,8,10,10,5,3,2

See the initRandomSeed() implementation here; the seed is fixed: https://github.com/microsoft/pxt-common-packages/blob/master/libs/core---samd/platform.cpp#L121

The core platform has an implementation of initRandomSeed() that takes input from the temperature + light sensors, which should make it more random; maybe that could be ported to core---samd? https://github.com/microsoft/pxt-common-packages/blob/master/libs/core/platform.cpp#L8

As a workaround I made a function that uses the light + sound sensors to add entropy:

let rand = 0
function getRandom(min: number, max: number): number {
    rand = Math.randomRange(0, 255)
    rand = rand + input.soundLevel()
    rand = rand + input.lightLevel()
    rand = rand / 3
    rand = Math.round((rand % (max - min)) + min)
    return rand
}