1

Using pybricks-micropython

Running this command to get a random port number, works under CPython.

import random
port = random.randint(50000,50999)

produces a number, only it is hardly random it is the same number each time I run the script. I am guessing MicroPython needs something more perhaps?

What am I missing?

user3069232
  • 8,587
  • 7
  • 46
  • 87
  • Perhaps micropython, unlike CPython, requires you to set the seed? The documentation doesn't suggest that you need to do that, but the behavior you describe is that of a RNG which is starting in the same default state every time. – John Coleman Jun 17 '19 at 18:01
  • This https://microbit-micropython.readthedocs.io/en/latest/tutorials/random.html describes a random module which doesn't need reseeding, but *pybricks* micropython seems inadequately documented. I couldn't find any online documentation that even mentioned a random module. Could you provide a link to the relevant documentation? The tag for `pybricks-micropython` itself has no information at all. – John Coleman Jun 17 '19 at 18:20
  • It is a version of MicroPython that LEGO is promoting. Here is a link to their press release and docs. https://www.ev3dev.org/news/2019/04/13/ev3-micropython/ – user3069232 Jun 17 '19 at 18:57
  • Nothing about that link (which I had already looked at) says anything about ev3-micropython and random. Perhaps there is a way to seed from an internal clock. – John Coleman Jun 17 '19 at 19:25

1 Answers1

1

John,

I looked up seed with random and used epoch time. Solved.

millis = int(round(time.time())
random.seed(millis)
port = random.randint(50000,50999)

Ok almost certainly produces a random you could predict, but hey this isn't for the lottery or anything, its for a port number :)

Thanks you, you seeded that answer, forgive the pun.

user3069232
  • 8,587
  • 7
  • 46
  • 87
  • I'm glad you found a solution. Python + Lego seems like a great combo! – John Coleman Jun 17 '19 at 19:38
  • John, are you a LEGO python man. I ask cause I am looking for some beta testers for an app I wrote that uses Python [in part]. – user3069232 Jun 17 '19 at 19:46
  • I never heard of it before today (though I am familiar with mindstorms), but I sometimes teach programming and am often looking for good ideas for examples. Maybe I'll invest in a basic kit before the next school year. – John Coleman Jun 17 '19 at 19:51
  • I only been playing around with it for a couple of months, got a gig next month and beyond to teach robotics and coding. It good fun. But you know I think spriteKit, from Apple is really the direction you should perhaps look into. Its isn't difficult and I am sure is an easy sell to students. Here look https://www.raywenderlich.com/5504-trigonometry-for-game-programming-spritekit-and-swift-tutorial-part-1-2 and this https://www.raywenderlich.com/5504-trigonometry-for-game-programming-spritekit-and-swift-tutorial-part-1-2 – user3069232 Jun 17 '19 at 19:59