WKnight02 WKnight02 - 1 year ago 39
Python Question

Python3: How to generate a pseudo-random sequence per object?

I have a test project where some entity can fire a bullet, and depending on the hit orientation and some random values, it can either impact or be deflected.

When running offline, its rather easy to generate random numbers on the go in order to tell if a shot should ricochet or not, as with


But I'm looking to broadcast the firing event via UDP, so that other clients can display the same entities/projectiles on their screen.

Projectiles are very high velocity, so I can't wait for the server to tell me the past location and just use that (I could correct the trajectory though). The main idea is to receive the
call from the remote entity, get some values such as
position, velocity, randseed

My problem is how do I use seeds for each entity ?

Say I have 10 bullets at once on my screen, each with its own pseudo-random seed, I want bullets to generate their own pseudo sequence, as they would on one side of the network or another.


class Bullet(object):
def __init__(self, pos, v, seed):
self.randgen = InstanciableGenerator(seed)
# ...

def hit(self, pos, ...):
currentRandom = self.randgen.get()
# ...

So that each instance has its own random sequence, not one shared by the
across each

How to generate distinct pseudo-random sequences ?

If it were to be a bad idea, what would be the best approach to broadcast a firing event, so that it is somewhat sync with all clients + server ?

PS: The server has full authority, the sync is for display purposes.

Answer Source

Use the random.Random class, e.g.:

self.randgen = random.Random(seed)

Then calls to self.randgen.random() (or .randint(<int>)) will be local to your instance.

Alternatively, you can create a wrapper which uses self.state = random.getstate() and then random.setstate(self.state) before each call to random.random()

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download