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

python 3 : How to generate a pseudo-random sequence per object? … here is a solution to the problem.

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

I have a test project where some of these entities can fire bullets, and depending on the direction of the hit and some random value, it can affect or deflect.

When running offline, it’s easy to generate random numbers to tell if a shot should be a ricochet, such as random.randint() or random.random().

But I want to broadcast the emitted event over UDP so that other clients can display the same entity/projectile on their screen.

The projectile is very fast, so I can’t wait for the server to tell me where it used to be and use it directly (I can correct the trajectory though). The main idea is to receive a fire call from a remote entity, get some value, such as position, velocity, randseed.

My question is how to use seeds for each entity?

Let’s say I have 10 bullets on my screen at the same time, each with its own pseudo-random seed, and I want the bullets to generate their own pseudo-sequences as if they were on one side of the network or the other.

Example:

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 random.seed() across each random.random() calls.

How to generate different pseudo-random sequences?

If that’s a bad idea, what’s the best way to broadcast the triggering event so that it’s in sync with all clients + servers?

PS: The server permissions are full, and the synchronization is for display

Solution

Use random. Random class, for example:

self.randgen = random. Random(seed)

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

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

Related Problems and Solutions